file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/reporter.py | import fnmatch
import glob
import json
import os
import platform
import shutil
import sys
import time
import xml.etree.ElementTree as ET
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from functools import lru_cache
from pathlib import Path
from typing import Dict, List, Optional
import carb
import carb.settings
import carb.tokens
import psutil
from .nvdf import post_coverage_to_nvdf, post_to_nvdf
from .teamcity import teamcity_message, teamcity_publish_artifact, teamcity_status
from .test_coverage import generate_coverage_report
from .utils import (
ext_id_to_fullname,
get_ext_test_id,
get_global_test_output_path,
get_setting,
get_test_output_path,
is_running_on_ci,
)
CURRENT_PATH = Path(__file__).parent
HTML_PATH = CURRENT_PATH.parent.parent.parent.joinpath("html")
REPORT_FILENAME = "report.jsonl"
RESULTS_FILENAME = "results.xml"
@lru_cache()
def get_report_filepath():
return os.path.join(get_test_output_path(), REPORT_FILENAME)
@lru_cache()
def get_results_filepath():
return os.path.join(get_test_output_path(), RESULTS_FILENAME)
def _load_report_data(report_path):
data = []
with open(report_path, "r") as f:
for line in f:
data.append(json.loads(line))
return data
def _get_tc_test_id(test_id):
return test_id.replace(".", "+")
class TestReporter:
"""Combines TC reports to stdout and JSON lines report to a file"""
def __init__(self, stream=sys.stdout):
self._stream = stream
self._timers = {}
self._report_filepath = get_report_filepath()
self.unreliable_tests = get_setting("/exts/omni.kit.test/unreliableTests", default=[])
self.parallel_run = get_setting("/exts/omni.kit.test/parallelRun", default=False)
def _get_duration(self, test_id: str) -> float:
try:
duration = round(time.time() - self._timers.pop(test_id), 3)
except KeyError:
duration = 0.0
return duration
def _is_unreliable(self, test_id):
return any(fnmatch.fnmatch(test_id, p) for p in self.unreliable_tests)
def set_output_path(self, output_path: str):
self._report_filepath = os.path.join(output_path, REPORT_FILENAME)
def _write_report(self, data: dict):
if self._report_filepath:
with open(self._report_filepath, "a") as f:
f.write(json.dumps(data))
f.write("\n")
def unittest_start(self, test_id, tc_test_id, captureStandardOutput="false"):
teamcity_message(
"testStarted", stream=self._stream, name=tc_test_id, captureStandardOutput=captureStandardOutput
)
self._timers[test_id] = time.time()
self._write_report(
{
"event": "start",
"test_type": "unittest",
"test_id": test_id,
"ext_test_id": get_ext_test_id(),
"unreliable": self._is_unreliable(test_id),
"parallel_run": self.parallel_run,
"start_time": time.time(),
}
)
def unittest_stop(self, test_id, tc_test_id, passed=False, skipped=False, skip_reason=""):
if skipped:
teamcity_message("testIgnored", stream=self._stream, name=tc_test_id, message=skip_reason)
teamcity_message("testFinished", stream=self._stream, name=tc_test_id)
self._write_report(
{
"event": "stop",
"test_type": "unittest",
"test_id": test_id,
"ext_test_id": get_ext_test_id(),
"passed": passed,
"skipped": skipped,
"skip_reason": skip_reason,
"stop_time": time.time(),
"duration": self._get_duration(test_id),
}
)
def unittest_fail(self, test_id, tc_test_id, fail_type: str, fail_message: str):
teamcity_message("testFailed", stream=self._stream, name=tc_test_id, fail_type=fail_type, message=fail_message)
self._write_report(
{
"event": "fail",
"test_type": "unittest",
"test_id": test_id,
"ext_test_id": get_ext_test_id(),
"fail_type": fail_type,
"message": fail_message,
}
)
def exttest_start(self, test_id, tc_test_id, ext_id, ext_name, captureStandardOutput="false", report=True):
teamcity_message(
"testStarted", stream=self._stream, name=tc_test_id, captureStandardOutput=captureStandardOutput
)
if report:
self._timers[test_id] = time.time()
self._write_report(
{
"event": "start",
"test_type": "exttest",
"test_id": test_id,
"ext_id": ext_id,
"ext_name": ext_name,
"start_time": time.time(),
}
)
def exttest_stop(self, test_id, tc_test_id, passed=False, skipped=False, report=True):
if skipped:
teamcity_message("testIgnored", stream=self._stream, name=tc_test_id, message="skipped")
teamcity_message("testFinished", stream=self._stream, name=tc_test_id)
if report:
self._write_report(
{
"event": "stop",
"test_type": "exttest",
"test_id": test_id,
"passed": passed,
"skipped": skipped,
"stop_time": time.time(),
"duration": self._get_duration(test_id),
}
)
def exttest_fail(self, test_id, tc_test_id, fail_type: str, fail_message: str):
teamcity_message("testFailed", stream=self._stream, name=tc_test_id, fail_type=fail_type, message=fail_message)
self._write_report(
{
"event": "fail",
"test_type": "exttest",
"test_id": test_id,
"fail_type": fail_type,
"message": fail_message,
}
)
def report_result(self, test):
"""Write tests results data we want to later show on the html report and in elastic"""
res = defaultdict(dict)
res["config"] = test.config
res["retries"] = test.retries
res["timeout"] = test.timeout if test.timeout else 0
ext_info = test.ext_info
ext_dict = ext_info.get_dict()
res["state"]["enabled"] = ext_dict.get("state", {}).get("enabled", False)
res["package"]["version"] = ext_dict.get("package", {}).get("version", "")
res.update(vars(test.result))
change = {}
if test.change_analyzer_result:
change["skip"] = test.change_analyzer_result.should_skip_test
change["startup_sequence_hash"] = test.change_analyzer_result.startup_sequence_hash
change["tested_ext_hash"] = test.change_analyzer_result.tested_ext_hash
change["kernel_version"] = test.change_analyzer_result.kernel_version
self._write_report(
{
"event": "result",
"test_type": "exttest",
"test_id": test.test_id,
"ext_id": test.ext_id,
"ext_name": test.ext_name,
"test_bucket": test.bucket_name,
"unreliable": test.config.get("unreliable", False),
"parallel_run": get_setting("/exts/omni.kit.test/parallelRun", default=False),
"change_analyzer": change,
"result": res,
}
)
# TODO: this function should be rewritten to avoid any guessing
def _get_extension_name(path: str, ext_id_to_name: dict):
# if ext_id is in the path return that extension name
for k, v in ext_id_to_name.items():
if k in path:
return v
p = Path(path)
for i, e in enumerate(p.parts):
if e == "exts" or e == "extscore":
if p.parts[i + 1][0:1].isdigit():
return ext_id_to_fullname(p.parts[i + 2])
else:
return p.parts[i + 1]
elif e == "extscache" or e == "extsPhysics":
# exts from cache will be named like this: omni.ramp-103.0.10+103.1.wx64.r.cp37
# exts from physics will be named like this: omni.physx-1.5.0-5.1
return ext_id_to_fullname(p.parts[i + 1])
elif e == "extensions":
# on linux we'll have paths from source/extensions/<ext_name>
return p.parts[i + 1]
carb.log_warn(f"Could not get extension name for {path}")
return "_unsorted"
class ExtCoverage:
def __init__(self):
self.ext_id: str = ""
self.ext_name: str = ""
self.covered_lines = []
self.num_statements = []
self.test_result = {}
def mean_cov(self):
statements = self.sum_statements()
if statements == 0:
return 0
return (self.sum_covered_lines() / statements) * 100.0
def sum_covered_lines(self):
return sum(self.covered_lines)
def sum_statements(self):
return sum(self.num_statements)
# Note that the combined coverage data will 'merge' (or 'lose') the test config because the coverage is reported
# at the filename level. For example an extension with 2 configs, omni.kit.renderer.core [default, compatibility]
# will produce 2 .pycov files, but in the combined report (json) it will be merged per source file, so no way to know
# what was the coverage for default vs compatibility, we'll get to coverage for all of omni.kit.renderer.core tests
def _build_ext_coverage(coverage_data: dict, ext_id_to_name: dict) -> Dict[str, ExtCoverage]:
exts = defaultdict(ExtCoverage)
for file, info in coverage_data["files"].items():
ext_name = _get_extension_name(file, ext_id_to_name)
exts[ext_name].ext_name = ext_name
exts[ext_name].covered_lines.append(info["summary"]["covered_lines"])
exts[ext_name].num_statements.append(info["summary"]["num_statements"])
return exts
def _report_unreliable_tests(report_data):
# Dummy tests to group all "unreliable" tests and report (convenience for TC UI)
unreliable_failed = [r for r in report_data if r["event"] == "result" and r["result"]["unreliable_fail"] == 1]
reporter = TestReporter()
total = len(unreliable_failed)
if total > 0:
dummy_test_id = "UNRELIABLE_TESTS"
summary = ""
for r in unreliable_failed:
test_result = r["result"]
summary += " [{0:5.1f}s] {1} (Count: {2})\n".format(
test_result["duration"], r["test_id"], test_result["test_count"]
)
reporter.unittest_start(dummy_test_id, dummy_test_id)
message = f"There are {total} tests that fail, but marked as unreliable:\n{summary}"
reporter.unittest_fail(dummy_test_id, dummy_test_id, "Error", message)
print(message)
reporter.unittest_stop(dummy_test_id, dummy_test_id)
def _build_test_data_html(report_data):
# consider retries: start, fail, start, (nothing) -> success
# for each fail look back and add extra data that this test will pass or fail.
# it is convenient for the next code to know ahead of time if test will pass.
started_tests = {}
for e in report_data:
if e["event"] == "start":
started_tests[e["test_id"]] = e
elif e["event"] == "fail":
started_tests[e["test_id"]]["will_pass"] = False
results = {item["test_id"]: item["result"] for item in report_data if item["event"] == "result"}
RESULT_EMOJI = {True: "✅", False: "❌"}
COLOR_CLASS = {True: "add-green-color", False: "add-red-color"}
unreliable = False
html_data = '<ul class="test_list">\n'
depth = 0
for e in report_data:
if e["event"] == "start":
# reset depth if needed (missing stop event)
if e["test_type"] == "exttest" and depth > 0:
depth -= 1
while depth > 0:
html_data += "</ul>\n"
depth -= 1
depth += 1
if depth > 1:
html_data += "<ul>\n"
test_id = e["test_id"]
passed = e.get("will_pass", True)
extra = ""
attr = ""
# Root test ([[test]] entry)
# Reset unreliable marker
if depth == 1:
unreliable = False
# Get more stats about the whole [[test]] run
if test_id in results:
test_result = results[test_id]
extra += " [{0:5.1f}s]".format(test_result["duration"])
unreliable = bool(test_result["unreliable"])
passed = test_result["passed"]
style_class = COLOR_CLASS[passed]
if unreliable:
extra += " <b>[unreliable]</b>"
style_class = "add-yellow-color unreliable"
html_data += '<li class="{0}" {4}>{3} {1} {2}</li>\n'.format(
style_class, extra, test_id, RESULT_EMOJI[passed], attr
)
if e["event"] == "stop":
depth -= 1
if depth > 0:
html_data += "</ul>\n"
html_data += "</ul>\n"
return html_data
def _post_build_status(report_data: list):
exts = {item["ext_id"] for item in report_data if item["event"] == "result"}
# there could be retry events, so only count unique tests:
tests_started = {item["test_id"] for item in report_data if item["event"] == "start"}
tests_passed = {item["test_id"] for item in report_data if item["event"] == "stop" and item["passed"]}
total_count = len(tests_started)
fail_count = total_count - len(tests_passed)
if fail_count:
status = "failure"
text = f"{fail_count} tests failed out of {total_count}"
else:
status = "success"
text = f"All {total_count} tests passed"
text += " (extensions tested: {}).".format(len(exts))
teamcity_status(text=text, status=status)
def _calculate_durations(report_data: list):
"""
Calculate startup time of each extension and time taken by each individual test
We count the time between the extension start_time to the start_time of the first test
"""
ext_startup_time = {}
ext_startup_time_found = {}
ext_tests_time = {}
for d in report_data:
test_id = d["test_id"]
test_type = d["test_type"]
ext_test_id = d.get("ext_test_id", None)
if d["event"] == "start":
if test_type == "exttest":
if not ext_startup_time_found.get(test_id):
start_time = d["start_time"]
ext_startup_time[test_id] = start_time
else:
if not ext_startup_time_found.get(ext_test_id):
t = ext_startup_time.get(ext_test_id, 0.0)
ext_startup_time[ext_test_id] = round(d["start_time"] - t, 2)
ext_startup_time_found[ext_test_id] = True
elif d["event"] == "stop":
if test_type == "unittest":
t = ext_tests_time.get(ext_test_id, 0.0)
t += d.get("duration", 0.0)
ext_tests_time[ext_test_id] = t
elif d["event"] == "result":
test_result = d.get("result", None)
if test_result:
# it's possible an extension has no tests, so we set startup_duration = duration
if ext_startup_time_found.get(test_id, False) is True:
t = ext_startup_time.get(test_id, 0.0)
test_result["startup_duration"] = t
else:
test_result["startup_duration"] = test_result.get("duration", 0.0)
# update duration of all tests
test_result["tests_duration"] = ext_tests_time.get(test_id, 0.0)
# ratios
test_result["startup_ratio"] = 0.0
test_result["tests_ratio"] = 0.0
if test_result["tests_duration"] != 0.0:
test_result["startup_ratio"] = (test_result["startup_duration"] / test_result["duration"]) * 100.0
test_result["tests_ratio"] = (test_result["tests_duration"] / test_result["duration"]) * 100.0
def generate_report():
"""After running tests this function will generate html report / post to nvdf / publish artifacts"""
# at this point all kit processes should be finished
if is_running_on_ci():
_kill_kit_processes()
try:
print("\nGenerating a Test Report...")
_generate_report_internal()
except Exception as e:
import traceback
print(f"Exception while running generate_report(): {e}, callstack: {traceback.format_exc()}")
def _kill_kit_processes():
"""Kill all Kit processes except self"""
kit_process_name = carb.tokens.get_tokens_interface().resolve("${exe-filename}")
for proc in psutil.process_iter():
if proc.pid == os.getpid():
continue
try:
if proc.name() == kit_process_name:
carb.log_warn(
"Killing a Kit process that is still running:\n"
f" PID: {proc.pid}\n"
f" Command line: {proc.cmdline()}"
)
proc.terminate()
except psutil.AccessDenied as e:
carb.log_warn(f"Access denied: {e}")
except psutil.ZombieProcess as e:
carb.log_warn(f"Encountered a zombie process: {e}")
except psutil.NoSuchProcess as e:
carb.log_warn(f"Process no longer exists: {e}")
except (psutil.Error, Exception) as e:
carb.log_warn(f"An error occurred: {str(e)}")
def _generate_report_internal():
# Get Test report and publish it
report_data = []
# combine report from various test runs (each process has own file, for parallel run)
for report_file in glob.glob(get_global_test_output_path() + "/*/" + REPORT_FILENAME):
report_data.extend(_load_report_data(report_file))
if not report_data:
return
# generate combined file
combined_report_path = get_global_test_output_path() + "/report_combined.jsonl"
with open(combined_report_path, "w") as f:
f.write(json.dumps(report_data))
teamcity_publish_artifact(combined_report_path)
# TC Build status
_post_build_status(report_data)
# Dummy test report
_report_unreliable_tests(report_data)
# Prepare output path
output_path = get_global_test_output_path()
os.makedirs(output_path, exist_ok=True)
# calculate durations (startup, total, etc)
_calculate_durations(report_data)
# post to elasticsearch
post_to_nvdf(report_data)
# write junit xml
_write_junit_results(report_data)
# get coverage results and generate html report
merged_results, coverage_results = _load_coverage_results(report_data)
html = _generate_html_report(report_data, merged_results)
# post coverage results
post_coverage_to_nvdf(_get_coverage_for_nvdf(merged_results, coverage_results))
# write and publish html report
_write_html_report(html, output_path)
# publish all test output to TC in the end:
teamcity_publish_artifact(f"{output_path}/**/*")
def _load_coverage_results(report_data, read_coverage=True) -> tuple[dict, dict]:
# build a map of extension id to extension name
ext_id_to_name = {}
for item in report_data:
if item["event"] == "result":
ext_id_to_name[item["ext_id"]] = item["ext_name"]
# Get data coverage per extension (configs are merged)
coverage_results = defaultdict(ExtCoverage)
if read_coverage:
coverage_result = generate_coverage_report()
if coverage_result and coverage_result.json_path:
coverage_data = json.load(open(coverage_result.json_path))
coverage_results = _build_ext_coverage(coverage_data, ext_id_to_name)
# combine test results and coverage data, key is the test_id (separates extensions per config)
merged_results = defaultdict(ExtCoverage)
for item in report_data:
if item["event"] == "result":
test_id = item["test_id"]
ext_id = item["ext_id"]
ext_name = item["ext_name"]
merged_results[test_id].ext_id = ext_id
merged_results[test_id].ext_name = ext_name
merged_results[test_id].test_result = item["result"]
cov = coverage_results.get(ext_name)
if cov:
merged_results[test_id].covered_lines = cov.covered_lines
merged_results[test_id].num_statements = cov.num_statements
return merged_results, coverage_results
def _get_coverage_for_nvdf(merged_results: dict, coverage_results: dict) -> dict:
json_data = {}
for ext_name, _ in coverage_results.items():
# grab the matching result
result: ExtCoverage = merged_results.get(ext_name)
if not result:
# in rare cases the default name of a test config can be different, search of the extension name instead
res: ExtCoverage
for res in merged_results.values():
if res.ext_name == ext_name:
result = res
break
test_result = result.test_result if result else None
if not test_result:
continue
test_data = {
"ext_id": result.ext_id,
"ext_name": ext_name,
}
test_data.update(test_result)
json_data.update({ext_name: {"test": test_data}})
return json_data
def _generate_html_report(report_data, merged_results):
html = ""
with open(os.path.join(HTML_PATH, "template.html"), "r") as f:
html = f.read()
class Color(Enum):
RED = 0
GREEN = 1
YELLOW = 2
def get_color(var, threshold: tuple, inverse=False, warning_only=False) -> Color:
if var == "":
return None
if inverse is True:
if float(var) >= threshold[0]:
return Color.RED
elif float(var) >= threshold[1]:
return Color.YELLOW
elif not warning_only:
return Color.GREEN
else:
if float(var) <= threshold[0]:
return Color.RED
elif float(var) <= threshold[1]:
return Color.YELLOW
elif not warning_only:
return Color.GREEN
def get_td(var, color: Color = None):
if color is Color.RED:
return f"<td ov-red>{var}</td>\n"
elif color is Color.GREEN:
return f"<td ov-green>{var}</td>\n"
elif color is Color.YELLOW:
return f"<td ov-yellow>{var}</td>\n"
else:
return f"<td>{var}</td>\n"
coverage_enabled = get_setting("/exts/omni.kit.test/pyCoverageEnabled", default=False)
coverage_threshold = get_setting("/exts/omni.kit.test/pyCoverageThreshold", default=75)
# disable coverage button when not needed
if not coverage_enabled:
html = html.replace(
"""<button class="tablinks" onclick="openTab(event, 'Coverage')">Coverage</button>""",
"""<button disabled class="tablinks" onclick="openTab(event, 'Coverage')">Coverage</button>""",
)
# Build test run data
html = html.replace("%%test_data%%", _build_test_data_html(report_data))
# Build extension table
html_data = ""
for test_id, info in sorted(merged_results.items()):
r = info.test_result
waiver = True if r.get("config", {}).get("waiver") else False
passed = r.get("passed", False)
test_count = r.get("test_count", 0)
duration = round(r.get("duration", 0.0), 1)
startup_duration = round(r.get("startup_duration", 0.0), 1)
startup_ratio = round(r.get("startup_ratio", 0.0), 1)
tests_duration = round(r.get("tests_duration", 0.0), 1)
tests_ratio = round(r.get("tests_ratio", 0.0), 1)
timeout = round(r.get("timeout", 0), 0)
timeout_ratio = 0
if timeout != 0:
timeout_ratio = round((duration / timeout) * 100.0, 0)
# an extension can override pyCoverageEnabled / pyCoverageThreshold
ext_coverage_enabled = bool(r.get("config", {}).get("pyCoverageEnabled", coverage_enabled))
ext_coverage_threshold = int(r.get("config", {}).get("pyCoverageThreshold", coverage_threshold))
ext_coverage_threshold_low = int(ext_coverage_threshold * (2 / 3))
# coverage data
num_statements = info.sum_statements()
num_covered_lines = info.sum_covered_lines()
cov_percent = round(info.mean_cov(), 2)
# add those calculated values to our results
py_coverage = {
"lines_total": num_statements,
"lines_tested": num_covered_lines,
"cov_percent": float(cov_percent),
"cov_threshold": ext_coverage_threshold,
"enabled": bool(coverage_enabled and ext_coverage_enabled),
}
info.test_result["pyCoverage"] = py_coverage
html_data += "<tr>\n"
html_data += get_td(test_id)
html_data += get_td(r.get("package", {}).get("version", ""))
html_data += get_td(waiver, Color.GREEN if waiver is True else None)
html_data += get_td(passed, Color.GREEN if bool(passed) is True else Color.RED)
html_data += get_td(test_count, Color.GREEN if waiver is True else get_color(test_count, (0, 5)))
# color code tests duration: >=60 seconds is red and >=30 seconds is yellow
html_data += get_td(str(duration), get_color(duration, (60, 30), inverse=True, warning_only=True))
html_data += get_td(str(startup_duration))
html_data += get_td(str(startup_ratio))
html_data += get_td(str(tests_duration))
html_data += get_td(str(tests_ratio))
html_data += get_td(str(timeout))
html_data += get_td(str(timeout_ratio), get_color(timeout_ratio, (90, 75), inverse=True, warning_only=True))
html_data += get_td(bool(coverage_enabled and ext_coverage_enabled))
if coverage_enabled and ext_coverage_enabled:
html_data += get_td(ext_coverage_threshold)
html_data += get_td(num_statements)
html_data += get_td(num_covered_lines)
html_data += get_td(
cov_percent,
Color.GREEN
if waiver is True
else get_color(cov_percent, (ext_coverage_threshold_low, ext_coverage_threshold)),
)
print(f" > Coverage for {test_id} is {cov_percent}%")
else:
for _ in range(4):
html_data += get_td("-")
html_data += "</tr>\n"
html = html.replace("%%table_data%%", html_data)
return html
def _write_html_report(html, output_path):
REPORT_NAME = "index.html"
REPORT_FOLDER_NAME = "test_report"
report_dir = os.path.join(output_path, REPORT_FOLDER_NAME)
os.makedirs(report_dir, exist_ok=True)
with open(os.path.join(report_dir, REPORT_NAME), "w") as f:
f.write(html)
print(f" > Full report available here {f.name}")
if not is_running_on_ci():
import webbrowser
webbrowser.open(f.name)
# copy javascript/css files
shutil.copyfile(os.path.join(HTML_PATH, "script.js"), os.path.join(report_dir, "script.js"))
shutil.copyfile(os.path.join(HTML_PATH, "style.css"), os.path.join(report_dir, "style.css"))
shutil.make_archive(os.path.join(output_path, REPORT_FOLDER_NAME), "zip", report_dir)
teamcity_publish_artifact(os.path.join(output_path, "*.zip"))
@dataclass
class Stats:
passed: int = 0
failure: int = 0
error: int = 0
skipped: int = 0
def get_total(self):
return self.passed + self.failure + self.error + self.skipped
def _write_junit_results(report_data: list):
"""Write a JUnit XML from our report data"""
testcases = []
testsuites = ET.Element("testsuites")
start_time = datetime.now()
last_failure = {"message": "", "fail_type": ""}
stats = Stats()
for data in report_data:
test_id = data["test_id"]
test_type = data["test_type"]
ext_test_id = data.get("ext_test_id", test_id)
if data["event"] == "start":
if test_type == "exttest":
start_time = datetime.fromtimestamp(data["start_time"])
elif data["event"] == "fail":
last_failure = data
elif data["event"] == "stop":
# create a testcase for each stop event (for both exttest and unittest)
testcase = ET.Element("testcase", name=test_id, classname=ext_test_id, time=f"{data['duration']:.3f}")
if data.get("skipped"):
stats.skipped += 1
node = ET.SubElement(testcase, "skipped")
node.text = data.get("skip_reason", "")
elif data.get("passed"):
stats.passed += 1
else:
# extension tests failures are of type Error
if test_type == "exttest":
stats.error += 1
node = ET.SubElement(testcase, "error")
elif last_failure["fail_type"] == "Failure":
stats.failure += 1
node = ET.SubElement(testcase, "failure")
else:
stats.error += 1
node = ET.SubElement(testcase, "error")
node.text = last_failure["message"]
testcases.append(testcase)
# extension test stop - gather all testcases and add test suite
if test_type == "exttest":
testsuite = ET.Element(
"testsuite",
name=test_id,
failures=str(stats.failure),
errors=str(stats.error),
skipped=str(stats.skipped),
tests=str(stats.get_total()),
time=f"{data['duration']:.3f}",
timestamp=start_time.isoformat(),
hostname=platform.node(),
)
testsuite.extend(testcases)
testsuites.append(testsuite)
# reset things between test suites
testcases = []
last_failure = {"message": "", "fail_type": ""}
stats = Stats()
# write our file
ET.indent(testsuites)
with open(get_results_filepath(), "w", encoding="utf-8") as f:
f.write(ET.tostring(testsuites, encoding="unicode", xml_declaration=True))
| 30,977 | Python | 37.386617 | 119 | 0.568971 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/test_coverage.py | import os
import shutil
from datetime import datetime
from functools import lru_cache
from pathlib import Path
import carb.settings
import coverage
import omni.kit.app
from .teamcity import teamcity_publish_artifact
from .utils import get_global_test_output_path, get_setting
# For Coverage.py to be able to combine data it's required that combined reports have the same prefix in the filenames.
# From https://coverage.readthedocs.io/en/coverage-6.1.2/api_coverage.htm:
# "All coverage data files whose name starts with data_file (from the coverage() constructor) will be read,
# and combined together into the current measurements."
COV_OUTPUT_DATAFILE_PREFIX = "py_cov"
COV_OUTPUT_DATAFILE_EXTENSION = ".pycov"
CURRENT_PATH = Path(__file__).parent
HTML_LOCAL_PATH = CURRENT_PATH.parent.parent.parent.joinpath("html", "coverage")
class PyCoverageCollectorSettings:
def __init__(self):
self.enabled = False
self.output_dir = None
self.filter: list = None
self.omit: list = None
self.include_modules = False
self.include_dependencies = False
self.include_test_dependencies = False
@lru_cache()
def _get_coverage_output_dir():
return os.path.join(get_global_test_output_path(), "pycov")
def read_coverage_collector_settings() -> PyCoverageCollectorSettings:
result = PyCoverageCollectorSettings()
result.enabled = get_setting("/exts/omni.kit.test/pyCoverageEnabled", True)
result.output_dir = _get_coverage_output_dir()
result.filter = get_setting("/exts/omni.kit.test/pyCoverageFilter", None)
result.omit = get_setting("/exts/omni.kit.test/pyCoverageOmit", None)
result.include_modules = get_setting("/exts/omni.kit.test/pyCoverageIncludeModules", False)
result.include_dependencies = get_setting("/exts/omni.kit.test/pyCoverageIncludeDependencies", False)
result.include_test_dependencies = get_setting("/exts/omni.kit.test/pyCoverageIncludeTestDependencies", False)
return result
class PyCoverageCollector:
"""Initializes code coverage collections and saves collected data at Python interpreter exit"""
class PyCoverageSettings:
def __init__(self):
self.filter = None
self.omit = None
self.output_data_path_prefix = None
self.output_datafile_suffix = None
def __init__(self):
self._coverage = None
def _read_collector_settings(self) -> PyCoverageSettings:
"""
Reads coverage settings and returns non None PyCoverageSettings if Python coverage is required
"""
app_name = get_setting("/app/name")
collector_settings = read_coverage_collector_settings()
if not collector_settings.enabled:
print(f"'{app_name}' has disabled Python coverage in settings")
return None
if collector_settings.output_dir is None:
print(f"Output directory for Python coverage isn't set. Skipping Python coverage for '{app_name}'.")
return None
result = self.PyCoverageSettings()
result.filter = collector_settings.filter
result.omit = collector_settings.omit
filename_timestamp = app_name + f"_{datetime.now():%Y-%m-%d_%H-%M-%S-%f}"
# PyCoverage combines report files that have the same prefix so adding the same prefix to created reports
result.output_data_path_prefix = os.path.normpath(
os.path.join(collector_settings.output_dir, COV_OUTPUT_DATAFILE_PREFIX)
)
result.output_datafile_suffix = filename_timestamp + COV_OUTPUT_DATAFILE_EXTENSION
return result
def startup(self):
# Reading settings to check if it's needed to start Python coverage
# It's needed to be done as soon as possible to properly collect data
self._settings = self._read_collector_settings()
if self._settings is not None:
self._coverage = coverage.Coverage(
source=self._settings.filter,
omit=self._settings.omit,
data_file=self._settings.output_data_path_prefix,
data_suffix=self._settings.output_datafile_suffix,
)
self._coverage.config.disable_warnings = [
"module-not-measured",
"module-not-imported",
"no-data-collected",
"couldnt-parse",
]
self._coverage.start()
# Register for app shutdown to finalize the coverage.
# For fast shutdown, shutdown function of ext will not be called.
# The following subscription will give a chance to collect coverage report.
if carb.settings.get_settings().get("/app/fastShutdown"):
self._shutdown_subs = (
omni.kit.app.get_app()
.get_shutdown_event_stream()
.create_subscription_to_pop_by_type(
omni.kit.app.POST_QUIT_EVENT_TYPE, self.shutdown, name="omni.kit.test::coverage", order=1000
)
)
else:
self._shutdown_subs = None
def shutdown(self, _=None):
if self._coverage is not None:
self._coverage.stop()
try:
# Note: trying to save report in non-internal format in the "atexit" handler will result in error
self._coverage.save()
except coverage.misc.CoverageException as err:
print(f"Couldn't save Coverage report in internal format: {err}")
self._coverage = None
self._settings = None
self._shutdown_subs = None
class PyCoverageReporterSettings:
def __init__(self):
self.source_dir = None
self.output_to_std = False
self.output_to_json = False
self.output_to_html = False
self.combine_previous_data = False
def read_coverage_reporter_settings() -> PyCoverageReporterSettings:
coverage_enabled = get_setting("/exts/omni.kit.test/pyCoverageEnabled", True)
if not coverage_enabled:
return None
pyCoverageFormats = [s.lower() for s in get_setting("/exts/omni.kit.test/pyCoverageFormats", ["json"])]
output_to_std = "stdout" in pyCoverageFormats
output_to_json = "json" in pyCoverageFormats
output_to_html = "html" in pyCoverageFormats
# Check if no Python coverage report required
if not output_to_std and not output_to_json:
return None
source_dir = _get_coverage_output_dir()
if not os.path.exists(source_dir):
return None
result = PyCoverageReporterSettings()
result.source_dir = source_dir
result.output_to_std = output_to_std
result.output_to_json = output_to_json
result.output_to_html = output_to_html
result.combine_previous_data = get_setting("/exts/omni.kit.test/pyCoverageCombinedReport", False)
return result
def _report_single_coverage_result(
cov: coverage,
src_path: str,
std_output: bool = True,
json_output_file: str = None,
title: str = None,
html_output_path: str = None,
):
"""
Creates single report and returns path for created json file (or None if it wasn't created)
"""
try:
# Note: parameter 'keep' sets if read files will be removed afterwards
# setting it to true as they might be used to regenerate overall coverage report
cov.combine(data_paths=[src_path], keep=True)
# Note: ignore errors is needed to ignore some of the errors when coverage fails to process
# .../PythonExtension.cpp::shutdown() or some other file
if std_output:
print()
print("=" * 60)
title = title if title is not None else "Python coverage report"
print(title)
print()
cov.report(ignore_errors=True)
print("=" * 60)
if json_output_file is not None:
cov.json_report(outfile=json_output_file, ignore_errors=True)
if html_output_path is not None:
cov.html_report(directory=html_output_path, ignore_errors=True)
except coverage.misc.CoverageException as err:
print(f"Couldn't create coverage report for '{src_path}': {err}")
def _modify_html_report(output_path: str):
# modify coverage html file to have a larger and clearer filter for extensions
html = ""
with open(os.path.join(output_path, "index.html"), 'r') as file:
html = file.read()
with open(os.path.join(HTML_LOCAL_PATH, "modify.html"), 'r') as file:
# find_replace [0] is the line to find, [1] the line to replace and [2] the line to add
find_replace = file.read().splitlines()
html = html.replace(find_replace[0], find_replace[1] + '\n' + find_replace[2])
with open(os.path.join(output_path, "index.html"), 'w') as file:
file.write(html)
# overwrite coverage css/js files
shutil.copyfile(os.path.join(HTML_LOCAL_PATH, "new_style.css"), os.path.join(output_path, "style.css"))
shutil.copyfile(os.path.join(HTML_LOCAL_PATH, "new_script.js"), os.path.join(output_path, "coverage_html.js"))
class PyCoverageReporterResult:
def __init__(self):
self.html_path = None
self.json_path = None
def report_coverage_results(reporter_settings: PyCoverageReporterSettings = None) -> PyCoverageReporterResult:
"""
Processes previously collected coverage data according to settings in the 'reporter_settings'
"""
result = PyCoverageReporterResult()
if reporter_settings is None:
return result
if (
not reporter_settings.output_to_std
and not reporter_settings.output_to_json
and not reporter_settings.output_to_html
):
print("No output report options selected for the coverage results. No result report generated.")
return result
# use global configuration file
config_file = str(CURRENT_PATH.joinpath(".coveragerc"))
# A helper file required by coverage for combining already existing reports
cov_internal_file = os.path.join(reporter_settings.source_dir, COV_OUTPUT_DATAFILE_PREFIX)
cov = coverage.Coverage(source=None, data_file=cov_internal_file, config_file=config_file)
cov.config.disable_warnings = ["module-not-measured", "module-not-imported", "no-data-collected", "couldnt-parse"]
if reporter_settings.combine_previous_data:
result.json_path = (
os.path.join(reporter_settings.source_dir, "combined_py_coverage" + COV_OUTPUT_DATAFILE_EXTENSION + ".json")
if reporter_settings.output_to_json
else None
)
result.html_path = (
os.path.join(reporter_settings.source_dir, "combined_py_coverage_html")
if reporter_settings.output_to_html
else None
)
_report_single_coverage_result(
cov,
reporter_settings.source_dir,
reporter_settings.output_to_std,
result.json_path,
html_output_path=result.html_path,
)
if result.html_path and os.path.exists(result.html_path):
# slightly modify the html report for our needs
_modify_html_report(result.html_path)
# add folder to zip file, while be used on TeamCity
shutil.make_archive(os.path.join(reporter_settings.source_dir, "coverage"), "zip", result.html_path)
if not os.path.exists(result.json_path):
result.json_path = None
else:
internal_reports = [
file for file in os.listdir(reporter_settings.source_dir) if file.endswith(COV_OUTPUT_DATAFILE_EXTENSION)
]
for cur_file in internal_reports:
cov.erase()
processed_filename = (
cur_file[len(COV_OUTPUT_DATAFILE_PREFIX) + 1 :]
if cur_file.startswith(COV_OUTPUT_DATAFILE_PREFIX)
else cur_file
)
json_path = None
if reporter_settings.output_to_json:
json_path = os.path.join(reporter_settings.source_dir, processed_filename + ".json")
title = None
if reporter_settings.output_to_std:
title, _ = os.path.splitext(processed_filename)
title = f"Python coverage report for '{title}'"
_report_single_coverage_result(
cov,
os.path.join(reporter_settings.source_dir, cur_file),
reporter_settings.output_to_std,
json_path,
title,
)
# Cleanup of intermediate data
cov.erase()
return result
def generate_coverage_report() -> PyCoverageReporterResult:
# processing coverage data
result = PyCoverageReporterResult()
coverage_collector_settings = read_coverage_collector_settings()
# automatically enable coverage if we detect a pycov directory present when generating a report
if os.path.exists(coverage_collector_settings.output_dir):
carb.settings.get_settings().set("/exts/omni.kit.test/pyCoverageEnabled", True)
coverage_collector_settings.enabled = True
if coverage_collector_settings.enabled:
coverage_reporter_settings = read_coverage_reporter_settings()
result = report_coverage_results(coverage_reporter_settings)
teamcity_publish_artifact(os.path.join(coverage_collector_settings.output_dir, "*.zip"))
return result
| 13,448 | Python | 38.09593 | 120 | 0.645895 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/flaky.py | import datetime
import logging
import os
from collections import defaultdict
import carb
from .utils import get_test_output_path
from .nvdf import get_app_info, query_nvdf
logger = logging.getLogger(__name__)
FLAKY_TESTS_QUERY_DAYS = 30
class FlakyTestAnalyzer:
"""Basic Flaky Tests Analyzer"""
AGG_TEST_IDS = "ids"
AGG_LAST_EXT_CONFIG = "config"
BUCKET_PASSED = "passed"
BUCKET_FAILED = "failed"
tests_failed = set()
ext_failed = defaultdict(list)
def __init__(
self, ext_test_id: str = "*", query_days=FLAKY_TESTS_QUERY_DAYS, exclude_consecutive_failure: bool = True
):
self.ext_test_id = ext_test_id
self.query_days = query_days
self.exclude_consecutive_failure = exclude_consecutive_failure
self.app_info = get_app_info()
self.query_result = self._query_nvdf()
def should_skip_test(self) -> bool:
if not self.query_result:
carb.log_info(f"{self.ext_test_id} query error - skipping test")
return True
if len(self.tests_failed) == 0:
carb.log_info(f"{self.ext_test_id} has no failed tests in last {self.query_days} days - skipping test")
return True
return False
def get_flaky_tests(self, ext_id: str) -> list:
return self.ext_failed.get(ext_id, [])
def generate_playlist(self) -> str:
test_output_path = get_test_output_path()
os.makedirs(test_output_path, exist_ok=True)
filename = "flakytest_" + self.ext_test_id.replace(".", "_").replace(":", "-")
filepath = os.path.join(test_output_path, f"{filename}_playlist.log")
if self._write_playlist(filepath):
return filepath
def _write_playlist(self, filepath: str) -> bool:
try:
with open(filepath, "w") as f:
f.write("\n".join(self.tests_failed))
return True
except IOError as e:
carb.log_warn(f"Error writing to {filepath} -> {e}")
return False
def _query_nvdf(self) -> bool:
query = self._es_query(days=self.query_days, hours=0)
r = query_nvdf(query)
for aggs in r.get("aggregations", {}).get(self.AGG_TEST_IDS, {}).get("buckets", {}):
test_id = aggs.get("key")
test_config = aggs.get("config", {}).get("hits", {}).get("hits")
if not test_config or not test_config[0]:
continue
test_config = test_config[0]
ext_test_id = test_config.get("fields", {}).get("test.s_ext_test_id")
if not ext_test_id or not ext_test_id[0]:
continue
ext_test_id = ext_test_id[0]
passed = aggs.get(self.BUCKET_PASSED, {}).get("doc_count", 0)
failed = aggs.get(self.BUCKET_FAILED, {}).get("doc_count", 0)
ratio = 0
if passed != 0 and failed != 0:
ratio = failed / (passed + failed)
carb.log_info(
f"{test_id} passed: {passed} failed: {failed} ({ratio * 100:.2f}% fail rate) in last {self.query_days} days"
)
if failed == 0:
continue
self.ext_failed[ext_test_id].append(
{"test_id": test_id, "passed": passed, "failed": failed, "ratio": ratio}
)
self.tests_failed.add(test_id)
return True
def _es_query(self, days: int, hours: int) -> dict:
target_date = datetime.datetime.utcnow() - datetime.timedelta(days=days, hours=hours)
kit_version = self.app_info["kit_version"]
carb.log_info(f"NVDF query for {self.ext_test_id} on Kit {kit_version}, last {days} days")
query = {
"aggs": {
self.AGG_TEST_IDS: {
"terms": {"field": "test.s_test_id", "order": {self.BUCKET_FAILED: "desc"}, "size": 1000},
"aggs": {
self.AGG_LAST_EXT_CONFIG: {
"top_hits": {
"fields": [{"field": "test.s_ext_test_id"}],
"_source": False,
"size": 1,
"sort": [{"ts_created": {"order": "desc"}}],
}
},
self.BUCKET_PASSED: {
"filter": {
"bool": {
"filter": [{"term": {"test.b_passed": True}}],
}
}
},
self.BUCKET_FAILED: {
"filter": {
"bool": {
"filter": [{"term": {"test.b_passed": False}}],
}
}
},
},
}
},
"size": 0,
"query": {
"bool": {
# filter out consecutive failure
# not (test.b_consecutive_failure : * and test.b_consecutive_failure : true)
"must_not": {
"bool": {
"filter": [
{
"bool": {
"should": [{"exists": {"field": "test.b_consecutive_failure"}}],
"minimum_should_match": 1,
}
},
{
"bool": {
"should": [
{"term": {"test.b_consecutive_failure": self.exclude_consecutive_failure}}
],
"minimum_should_match": 1,
}
},
]
}
},
"filter": [
{"term": {"test.s_ext_test_id": self.ext_test_id}},
{"term": {"test.s_test_type": "unittest"}},
{"term": {"test.b_skipped": False}},
{"term": {"test.b_unreliable": False}},
{"term": {"test.b_parallel_run": False}}, # Exclude parallel_run results
{"term": {"app.s_kit_version": kit_version}},
{"term": {"app.l_merge_request": 0}}, # Should we enable flaky tests from MR? For now excluded.
{
"range": {
"ts_created": {
"gte": target_date.isoformat() + "Z",
"format": "strict_date_optional_time",
}
}
},
],
}
},
}
return query
| 7,157 | Python | 38.988827 | 124 | 0.415398 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/unittests.py | import asyncio
import fnmatch
import os
import random
import sys
import traceback
import unittest
from contextlib import suppress
from glob import glob
from importlib import import_module
from itertools import islice
from os.path import basename, dirname, isfile, join, splitext
from types import ModuleType
from typing import Callable, List
import carb
import carb.tokens
import omni.kit.app
from .async_unittest import AsyncTestSuite, AsyncTextTestRunner, OmniTestResult
from .exttests import RunExtTests
from .reporter import TestReporter
from .sampling import SamplingFactor, get_tests_sampling_to_skip
from .teamcity import teamcity_message
from .test_reporters import _test_status_report
from .utils import get_ext_test_id, get_setting, get_test_output_path
def _import_if_exist(module: str):
try:
return import_module(module)
except ModuleNotFoundError as e:
# doesn't exist if that is what we trying to import or namespace
if e.name == module or module.startswith(e.name + "."):
return None
carb.log_error(
f"Failed to import python module with tests: {module}. Error: {e}. Traceback:\n{traceback.format_exc()}"
)
except Exception as e:
carb.log_error(
f"Failed to import python module with tests: {module}. Error: {e}. Traceback:\n{traceback.format_exc()}"
)
def _get_enabled_extension_modules(filter_fn: Callable[[str], bool] = None):
manager = omni.kit.app.get_app().get_extension_manager()
# For each extension get each python module it declares
module_names = manager.get_enabled_extension_module_names()
sys_modules = set()
for name in module_names:
if name in sys.modules:
if filter_fn and not filter_fn(name):
continue
sys_modules.add(sys.modules[name])
# Automatically look for and import '[some_module].tests' and '[some_module].ogn.tests' so that extensions
# don't have to put tests into config files and import them all the time.
for test_submodule in [f"{name}.tests", f"{name}.ogn.tests"]:
if filter_fn and not filter_fn(test_submodule):
continue
if test_submodule in sys.modules:
sys_modules.add(sys.modules[test_submodule])
else:
test_module = _import_if_exist(test_submodule)
if test_module:
sys_modules.add(test_module)
return sys_modules
# ----------------------------------------------------------------------
SCANNED_TEST_MODULES = {} # Dictionary of moduleName: [dynamicTestModules]
_EXTENSION_DISABLED_HOOK = None # Hook for monitoring extension state changes, to keep the auto-populated list synced
_LOG = bool(os.getenv("TESTS_DEBUG")) # Environment variable to enable debugging of the test registration
# ----------------------------------------------------------------------
def remove_from_dynamic_test_cache(module_root):
"""Get the list of tests dynamically added to the given module directory (via "scan_for_test_modules")"""
global SCANNED_TEST_MODULES
for module_suffix in ["", ".tests", ".ogn.tests"]:
module_name = module_root + module_suffix
tests_to_remove = SCANNED_TEST_MODULES.get(module_name, [])
if tests_to_remove:
if _LOG:
print(f"Removing {len(tests_to_remove)} tests from {module_name}")
del SCANNED_TEST_MODULES[module_name]
# ----------------------------------------------------------------------
def _on_ext_disabled(ext_id, *_):
"""Callback executed when an extension has been disabled - scan for tests to remove"""
config = omni.kit.app.get_app().get_extension_manager().get_extension_dict(ext_id)
for node in ("module", "modules"):
with suppress(KeyError):
for module in config["python"][node]:
remove_from_dynamic_test_cache(module["name"])
# ----------------------------------------------------------------------
def dynamic_test_modules(module_root: str, module_file: str) -> List[ModuleType]:
"""Import all of the test modules and return a list of the imports so that automatic test recognition works
The normal test recognition mechanism relies on knowing all of the file names at build time. This function is
used to support automatic recognition of all test files in a certain directory at run time.
Args:
module_root: Name of the module for which tests are being imported, usually just __name__ of the caller
module_file: File from which the import is happening, usually just __file__ of the caller
Usage:
In the directory containing your tests add this line to the __init__.py file (creating the file if necessary):
scan_for_test_modules = True
It will pick up any Python files names testXXX.py or TestXXX.py and scan them for tests when the extension
is loaded.
Important:
The __init__.py file must be imported with the extension. If you have a .tests module or .ogn.tests module
underneath your main module this will happen automatically for you.
Returns:
List of modules that were added, each pointing to a file in which tests are contained
"""
global _EXTENSION_DISABLED_HOOK
global SCANNED_TEST_MODULES
if module_root in SCANNED_TEST_MODULES:
return SCANNED_TEST_MODULES[module_root]
modules_imported = []
for module_name in [basename(f) for f in glob(join(dirname(module_file), "*.py")) if isfile(f)]:
if module_name != "__init__" and module_name.lower().startswith("test"):
imported_module = f"{module_root}.{splitext(module_name)[0]}"
modules_imported.append(import_module(imported_module))
SCANNED_TEST_MODULES[module_root] = modules_imported
# This is a singleton initialization. If ever any test modules are scanned then from then on monitor for an
# extension being disabled so that the cached list can be cleared for rebuilding on the next run.
if _EXTENSION_DISABLED_HOOK is None:
hooks = omni.kit.app.get_app().get_extension_manager().get_hooks()
_EXTENSION_DISABLED_HOOK = hooks.create_extension_state_change_hook(
_on_ext_disabled,
omni.ext.ExtensionStateChangeType.BEFORE_EXTENSION_DISABLE,
ext_dict_path="python",
hook_name="python.unit_tests",
)
return modules_imported
# ==============================================================================================================
def get_tests_to_remove_from_modules(modules, log=_LOG):
"""Return the list of tests to be removed when a module is unloaded.
This includes all tests registered or dynamically discovered from the list of modules and their .tests or
.ogn.tests submodules. Keeping this separate from get_tests_from_modules() allows the import of all three related
modules, while preventing duplication of their tests when all extension module tests are requested.
Args:
modules: List of modules to
"""
all_modules = modules
all_modules += [module.tests for module in modules if hasattr(module, "tests")]
all_modules += [module.ogn.tests for module in modules if hasattr(module, "ogn") and hasattr(module.ogn, "tests")]
return get_tests_from_modules(all_modules, log)
# ==============================================================================================================
def get_tests_from_modules(modules, log=_LOG):
"""Return the list of tests registered or dynamically discovered from the list of modules"""
loader = unittest.TestLoader()
loader.suiteClass = AsyncTestSuite
tests = []
for module in modules:
if log:
carb.log_warn(f"Getting tests from module {module.__name__}")
suite = loader.loadTestsFromModule(module)
test_count = suite.countTestCases()
if test_count > 0:
if log:
carb.log_warn(f"Found {test_count} tests in {module.__name__}")
for t in suite:
tests += t._tests
if "scan_for_test_modules" in module.__dict__:
if log:
carb.log_warn(f"Scanning for test modules in {module.__name__} loaded from {module.__file__}")
for extra_module in dynamic_test_modules(module.__name__, module.__file__):
if log:
carb.log_warn(f" Processing additional module {extra_module}")
extra_suite = loader.loadTestsFromModule(extra_module)
extra_count = extra_suite.countTestCases()
if extra_count > 0:
if log:
carb.log_warn(f"Found {extra_count} additional tests added through {extra_module.__name__}")
for extra_test in extra_suite:
tests += extra_test._tests
# Some tests can be generated at runtime out of discovered ones. For example, we can leverage that to duplicate
# tests for different configurations.
for t in islice(tests, 0, len(tests)):
generate_extra = getattr(t, "generate_extra_tests", None)
if callable(generate_extra):
generated = generate_extra()
if generated:
tests += generated
return tests
def get_tests_from_enabled_extensions():
include_tests = get_setting("/exts/omni.kit.test/includeTests", default=[])
exclude_tests = get_setting("/exts/omni.kit.test/excludeTests", default=[])
def include_test(test_id: str) -> bool:
return any(fnmatch.fnmatch(test_id, p) for p in include_tests) and not any(
fnmatch.fnmatch(test_id, p) for p in exclude_tests
)
# Filter modules before importing. That allows having test-only modules and dependencies, they will fail to import
# in non-test environment. Tricky part is filtering itself. For includeTests = "omni.foo.test_abc_def_*" we want to
# match `omni.foo` module, but not `omni.foo_test_abc` test id. Thus module filtering is more permissive and
# checks "starts with" too.
def include_module(module: str) -> bool:
def match_module(module, pattern):
return fnmatch.fnmatch(module, pattern) or pattern.startswith(module)
return any(match_module(module, p) for p in include_tests)
modules = _get_enabled_extension_modules(filter_fn=include_module)
return (t for t in get_tests_from_modules(modules) if include_test(t.id()))
def _get_tests_from_file(filepath: str) -> list:
test_list = []
try:
with open(filepath) as f:
test_list = f.read().splitlines()
except IOError as e:
carb.log_warn(f"Error opening file {filepath} -> {e}")
return test_list
def _get_tests_override(tests: list) -> list:
"""Apply some override/modifiers to get the proper list of tests in that order:
1. Add/Remove unreliable tests depending on testExtRunUnreliableTests value
2. Get list of failed tests if present (if enabled, used with retry-on-failure)
3. Get list of tests from a file (if enabled, generated when running tests)
4. Get list of tests from sampling (if enabled)
5. Shuffle (random order) is applied last
"""
def is_unreliable_test(test_id: str) -> bool:
return any(fnmatch.fnmatch(test_id, p) for p in unreliable_tests)
unreliable_tests = get_setting("/exts/omni.kit.test/unreliableTests", default=[])
run_unreliable_tests = get_setting("/exts/omni.kit.test/testExtRunUnreliableTests", default=0)
if run_unreliable_tests == RunExtTests.RELIABLE_ONLY:
tests = [t for t in tests if not is_unreliable_test(t.id())]
elif run_unreliable_tests == RunExtTests.UNRELIABLE_ONLY:
tests = [t for t in tests if is_unreliable_test(t.id())]
failed_tests = get_setting("/exts/omni.kit.test/retryFailedTests", default=[])
tests_filepath = get_setting("/exts/omni.kit.test/runTestsFromFile", default="")
sampling_factor = float(get_setting("/exts/omni.kit.test/samplingFactor", default=SamplingFactor.UPPER_BOUND))
shuffle_tests = bool(get_setting("/exts/omni.kit.test/testExtRandomOrder", default=False))
if failed_tests:
tests = [t for t in tests if t.id() in failed_tests]
elif tests_filepath:
tests_from_file = _get_tests_from_file(tests_filepath)
tests = [t for t in tests if t.id() in tests_from_file]
tests.sort(key=lambda x: tests_from_file.index(x.id()))
elif tests and sampling_factor != SamplingFactor.UPPER_BOUND:
sampling = get_tests_sampling_to_skip(get_ext_test_id(), sampling_factor, [t.id() for t in tests])
skipped_tests = [t for t in tests if t.id() in sampling]
print(
"----------------------------------------\n"
f"Tests Sampling Factor set to {int(sampling_factor * 100)}% "
f"(each test should run every ~{int(1.0 / sampling_factor)} runs)\n"
)
teamcity_message("message", text=f"Tests Sampling Factor set to {int(sampling_factor * 100)}%")
# Add unittest.skip function (decorator) to all skipped tests if not skipped already.
# It will provide an explicit reason why the test was skipped.
for t in skipped_tests:
test_method = getattr(t, t._testMethodName)
if not getattr(test_method, "__unittest_skip__", False):
setattr(t, t._testMethodName, unittest.skip("Skipped by Sampling")(test_method))
if shuffle_tests:
seed = int(get_setting("/exts/omni.kit.test/testExtSamplingSeed", default=-1))
if seed >= 0:
random.seed(seed)
random.shuffle(tests)
return tests
def get_tests(tests_filter="") -> List:
"""Default function to get all current tests.
It gets tests from all enabled extensions, but also included include and exclude settings to filter them
Args:
tests_filter(str): Additional filter string to apply on list of tests.
Returns:
List of tests.
"""
if "*" not in tests_filter:
tests_filter = f"*{tests_filter}*"
# Find all tests in loaded extensions and filter with patterns using settings above:
tests = [t for t in get_tests_from_enabled_extensions() if fnmatch.fnmatch(t.id(), tests_filter)]
tests = _get_tests_override(tests)
return tests
def _setup_output_path(test_output_path: str):
tokens = carb.tokens.get_tokens_interface()
os.makedirs(test_output_path, exist_ok=True)
tokens.set_value("test_output", test_output_path)
def _write_tests_playlist(test_output_path: str, tests: list):
n = 1
filepath = test_output_path
app_name = get_setting("/app/name", "exttest")
while os.path.exists(filepath):
filepath = os.path.join(test_output_path, f"{app_name}_playlist_{n}.log")
n += 1
try:
with open(filepath, "w") as f:
for t in tests:
f.write(f"{t.id()}\n")
except IOError as e:
carb.log_warn(f"Error writing to {filepath} -> {e}")
def run_tests_in_modules(modules, on_finish_fn=None):
run_tests(get_tests_from_modules(modules, True), on_finish_fn)
def run_tests(tests=None, on_finish_fn=None, on_status_report_fn=None):
if tests is None:
tests = get_tests()
test_output_path = get_test_output_path()
_setup_output_path(test_output_path)
_write_tests_playlist(test_output_path, tests)
loader = unittest.TestLoader()
loader.suiteClass = AsyncTestSuite
suite = AsyncTestSuite()
suite.addTests(tests)
def on_status_report(*args, **kwargs):
if on_status_report_fn:
on_status_report_fn(*args, **kwargs)
_test_status_report(*args, **kwargs)
# Use our own TC reporter:
AsyncTextTestRunner.resultclass = OmniTestResult
runner = AsyncTextTestRunner(verbosity=2, stream=sys.stdout)
async def run():
result = await runner.run(suite, on_status_report)
if on_finish_fn:
on_finish_fn(result)
print("========================================")
print("========================================")
print(f"Running Tests (count: {len(tests)}):")
print("========================================")
asyncio.ensure_future(run())
def print_tests():
tests = get_tests()
print("========================================")
print(f"Printing All Tests (count: {len(tests)}):")
print("========================================")
reporter = TestReporter()
for t in tests:
reporter.unittest_start(t.id(), t.id())
print(t.id())
reporter.unittest_stop(t.id(), t.id())
print("========================================")
| 16,769 | Python | 41.890025 | 119 | 0.62705 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/exttests.py | from __future__ import annotations
import asyncio
import fnmatch
import io
import multiprocessing
import os
import pprint
import random
import re
import subprocess
import sys
import time
from collections import defaultdict
from enum import IntEnum
from typing import Dict, List, Set, Tuple
import carb.dictionary
import carb.settings
import carb.tokens
import omni.kit.app
import psutil
from .async_unittest import KEY_FAILING_TESTS, STARTED_UNITTEST
from .code_change_analyzer import CodeChangeAnalyzer
from .crash_process import crash_process
from .flaky import FLAKY_TESTS_QUERY_DAYS, FlakyTestAnalyzer
from .repo_test_context import RepoTestContext
from .reporter import TestReporter
from .sampling import SamplingFactor
from .teamcity import is_running_in_teamcity, teamcity_message, teamcity_test_retry_support
from .test_coverage import read_coverage_collector_settings
from .test_reporters import TestRunStatus, _test_status_report
from .utils import (
clamp,
cleanup_folder,
ext_id_to_fullname,
get_argv,
get_global_test_output_path,
get_local_timestamp,
get_setting,
get_unprocessed_argv,
is_running_on_ci,
resolve_path,
)
BEGIN_SEPARATOR = "\n{0} [EXTENSION TEST START: {{0}}] {0}\n".format("|" * 30)
END_SEPARATOR = "\n{0} [EXTENSION TEST {{0}}: {{1}}] {0}\n".format("|" * 30)
DEFAULT_TEST_NAME = "default"
def _error(stream, msg):
stream.write(f"[error] [{__file__}] {msg}\n")
_debug_log = bool(os.getenv("OMNI_KIT_TEST_DEBUG", default=False))
_asyncio_process_was_terminated = False
def _debug(stream, msg):
if _debug_log:
stream.write(f"[info] [{__file__}] {msg}\n")
def matched_patterns(s: str, patterns: List[str]) -> List[str]:
return [p for p in patterns if fnmatch.fnmatch(s, p)]
def match(s: str, patterns: List[str]) -> bool:
return len(matched_patterns(s, patterns)) > 0
def escape_for_fnmatch(s: str) -> str:
return s.replace("[", "[[]")
def unescape_fnmatch(s: str) -> str:
return s.replace("[[]", "[")
class FailPatterns:
def __init__(self, include=[], exclude=[]):
self.include = [escape_for_fnmatch(s.lower()) for s in include]
self.exclude = [escape_for_fnmatch(s.lower()) for s in exclude]
def merge(self, patterns: FailPatterns):
self.include += patterns.include
self.exclude += patterns.exclude
def match_line(self, line: str) -> Tuple[str, str, bool]:
line_lower = line.lower()
include_matched = match(line_lower, self.include)
exclude_matched = match(line_lower, self.exclude)
if include_matched and not exclude_matched:
patterns = matched_patterns(line_lower, self.include)
patterns = [unescape_fnmatch(p) for p in patterns]
return ", ".join(patterns), line.strip(), exclude_matched
return "", "", exclude_matched
def __str__(self):
return pprint.pformat(vars(self))
class RunExtTests(IntEnum):
RELIABLE_ONLY = 0
UNRELIABLE_ONLY = 1
BOTH = 2
class RetryStrategy:
NO_RETRY = "no-retry"
RETRY_ON_FAILURE = "retry-on-failure"
ITERATIONS = "iterations"
RERUN_UNTIL_FAILURE = "rerun-until-failure"
# CI strategy, default to no-retry when testing locally
RETRY_ON_FAILURE_CI_ONLY = "retry-on-failure-ci-only"
class SamplingContext:
ANY = "any"
LOCAL = "local"
CI = "ci"
class TestRunContext:
def __init__(self):
# Setup output path for test data
self.output_path = get_global_test_output_path()
os.makedirs(self.output_path, exist_ok=True)
print("Test output path: {}".format(self.output_path))
self.coverage_mode = get_setting("/exts/omni.kit.test/testExtGenerateCoverageReport", default=False) or (
"--coverage" in get_argv()
)
# clean output folder?
clean_output = get_setting("/exts/omni.kit.test/testExtCleanOutputPath", default=False)
if clean_output:
cleanup_folder(self.output_path)
self.shared_patterns = FailPatterns(
get_setting("/exts/omni.kit.test/stdoutFailPatterns/include", default=[]),
get_setting("/exts/omni.kit.test/stdoutFailPatterns/exclude", default=[]),
)
self.trim_stdout_on_success = bool(get_setting("/exts/omni.kit.test/testExtTrimStdoutOnSuccess", default=False))
self.trim_excluded_messages = bool(
get_setting("/exts/omni.kit.test/stdoutFailPatterns/trimExcludedMessages", default=False)
)
self.retry_strategy = get_setting("/exts/omni.kit.test/testExtRetryStrategy", default=RetryStrategy.NO_RETRY)
self.max_test_run = int(get_setting("/exts/omni.kit.test/testExtMaxTestRunCount", default=1))
if self.retry_strategy == RetryStrategy.RETRY_ON_FAILURE_CI_ONLY:
if is_running_on_ci():
self.retry_strategy = RetryStrategy.RETRY_ON_FAILURE
self.max_test_run = 3
else:
self.retry_strategy = RetryStrategy.NO_RETRY
self.max_test_run = 1
self.run_unreliable_tests = RunExtTests(get_setting("/exts/omni.kit.test/testExtRunUnreliableTests", default=0))
self.run_flaky_tests = get_setting("/exts/omni.kit.test/testExtRunFlakyTests", default=False)
self.start_ts = get_local_timestamp()
self.repo_test_context = RepoTestContext()
self.change_analyzer = None
if get_setting("/exts/omni.kit.test/testExtCodeChangeAnalyzerEnabled", default=False) and is_running_on_ci():
self.change_analyzer = CodeChangeAnalyzer(self.repo_test_context)
def _prepare_ext_for_testing(ext_name, stream=sys.stdout):
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = None
ext_info_local = manager.get_extension_dict(ext_name)
if ext_info_local:
return ext_info_local
ext_info_remote = manager.get_registry_extension_dict(ext_name)
if ext_info_remote:
ext_id = ext_info_remote["package/id"]
else:
versions = manager.fetch_extension_versions(ext_name)
if len(versions) > 0:
ext_id = versions[0]["id"]
else:
_error(stream, f"Can't find extension: {ext_name} to run extension test on.")
return None
ext_info_local = manager.get_extension_dict(ext_id)
is_local = ext_info_local is not None
if not is_local:
if not manager.pull_extension(ext_id):
_error(stream, f"Failed to pull extension: {ext_id} to run extension test on.")
return None
ext_info_local = manager.get_extension_dict(ext_id)
if not ext_info_local:
_error(stream, f"Failed to get extension dict: {ext_id} while preparing extension for testing.")
return ext_info_local
def _prepare_app_for_testing(stream) -> Tuple[str, str]:
"""Returns path to app (kit file) and short name of an app."""
test_app = get_setting("/exts/omni.kit.test/testExtApp", default=None)
test_app = carb.tokens.get_tokens_interface().resolve(test_app)
# Test app can be either path to kit file or extension id (to optionally download and use extension as an app)
if test_app.endswith(".kit") or "/" in test_app:
return (test_app, "")
app_ext_info = _prepare_ext_for_testing(test_app, stream)
if app_ext_info:
return (app_ext_info["path"], test_app)
return (None, test_app)
class ExtTestResult:
def __init__(self):
self.duration = 0.0
self.test_count = 0
self.unreliable = 0
self.unreliable_fail = 0
self.fail = 0
self.passed = True
class TestApp:
def __init__(self, stream):
self.path, self.name = _prepare_app_for_testing(stream)
self.is_empty = not self.name
class ExtTest:
def __init__(
self,
ext_id: str,
ext_info: carb.dictionary.Item,
test_config: Dict,
test_id: str,
is_parallel_run: bool,
run_context: TestRunContext,
test_app: TestApp,
valid=True,
):
self.context = run_context
self.ext_id = ext_id
self.ext_name = ext_id_to_fullname(ext_id)
self.test_id = test_id
self.app_name = ""
# TC treats dots are separators to filter tests in UI, replace them.
self.tc_test_id = test_id.replace(".", "+") + ".[PROCESS CHECK]"
self.bucket_name = get_setting("/exts/omni.kit.test/testExtTestBucket", default="")
self.unreliable = False
self.skip = False
self.allow_sampling = True
self.args: List[str] = []
self.patterns = FailPatterns()
self.timeout = -1
self.result = ExtTestResult()
self.retries = 0
self.buffer_stdout = bool(is_parallel_run) or bool(self.context.trim_stdout_on_success)
self.stdout = io.StringIO() if self.buffer_stdout else sys.stdout
self.log_file = ""
self.parallelizable = True
self.reporter = TestReporter(self.stdout)
self.test_app = test_app
self.config = test_config
self.ext_info = ext_info
self.output_path = ""
self.valid = bool(valid and self.ext_info)
self.change_analyzer_result = None
self.failed_tests = []
if self.valid:
self._fill_ext_test()
def _fill_ext_test(self):
self.args = [get_argv()[0]]
self.app_name = "exttest_" + self.test_id.replace(".", "_").replace(":", "-")
ui_mode = get_setting("/exts/omni.kit.test/testExtUIMode", default=False) or ("--dev" in get_argv())
print_mode = get_setting("/exts/omni.kit.test/printTestsAndQuit", default=False)
use_kit_file_as_app = get_setting("/exts/omni.kit.test/testExtUseKitFileAsApp", default=True)
coverage_mode = self.context.coverage_mode
self.ext_id = self.ext_info["package/id"]
self.ext_name = self.ext_info["package/name"]
is_kit_file = self.ext_info.get("isKitFile", False)
# If extension is kit file just run startup test without using a test app
ext_path = self.ext_info.get("path", "")
if is_kit_file and use_kit_file_as_app:
self.args += [ext_path]
else:
self.args += [self.test_app.path, "--enable", self.ext_id]
# test output dir
self.output_path = f"{self.context.output_path}/{self.app_name}"
if not os.path.exists(self.output_path):
os.makedirs(self.output_path)
self.reporter.set_output_path(self.output_path)
# current ts (not precise as test run can be delayed relative to this moment)
ts = get_local_timestamp()
self.log_file = f"{self.output_path}/{self.app_name}_{ts}_0.log"
self.args += [
"--/log/flushStandardStreamOutput=1",
"--/app/name=" + self.app_name,
f"--/log/file='{self.log_file}'",
f"--/exts/omni.kit.test/testOutputPath='{self.output_path}'",
f"--/exts/omni.kit.test/extTestId='{self.test_id}'",
f"--/crashreporter/dumpDir='{self.output_path}'",
"--/crashreporter/preserveDump=1",
"--/crashreporter/gatherUserStory=0", # don't pop up the GUI on crash
"--/rtx-transient/dlssg/enabled=false", # OM-97205: Disable DLSS-G for now globally, so L40 tests will all pass. DLSS-G tests will have to enable it
]
# also set extTestId on the parent process - needed when calling unittest_* functions from exttests.py
carb.settings.get_settings().set_string("/exts/omni.kit.test/extTestId", self.test_id)
# Pass all exts folders
ext_folders = list(get_setting("/app/exts/folders", default=[]))
ext_folders += list(get_setting("/persistent/app/exts/userFolders", default=[]))
for folder in ext_folders:
self.args += ["--ext-folder", folder]
# Profiler trace enabled ?
default_profiling = get_setting("/exts/omni.kit.test/testExtEnableProfiler", default=False)
profiling = self.config.get("profiling", default_profiling)
if profiling:
self.args += [
"--/plugins/carb.profiler-cpu.plugin/saveProfile=1",
"--/plugins/carb.profiler-cpu.plugin/compressProfile=1",
"--/app/profileFromStart=1",
f"--/plugins/carb.profiler-cpu.plugin/filePath='{self.output_path}/ct_{self.app_name}_{ts}.gz'",
]
# Timeout for the process
default_timeout = int(get_setting("/exts/omni.kit.test/testExtDefaultTimeout", default=300))
max_timeout = int(get_setting("/exts/omni.kit.test/testExtMaxTimeout", default=0))
self.timeout = self.config.get("timeout", default_timeout)
# Clamp timeout if needed
if max_timeout > 0 and self.timeout > max_timeout:
self.timeout = max_timeout
# [[test]] can be marked as unreliable - meaning it will not run any of its tests unless unreliable tests are run
self.unreliable = self.config.get("unreliable", self.config.get("flaky", False))
# python tests to include
include_tests = list(self.config.get("pythonTests", {}).get("include", []))
exclude_tests = list(self.config.get("pythonTests", {}).get("exclude", []))
unreliable_tests = list(self.config.get("pythonTests", {}).get("unreliable", []))
# When running unreliable tests:
# 1. if the [[test]] is set as unreliable run all python tests (override the `unreliable_tests` list)
# 2. if running unreliable tests - set unreliable to true and disable sampling
if self.unreliable:
unreliable_tests = ["*"]
self.allow_sampling = False
elif unreliable_tests and self.context.run_unreliable_tests != RunExtTests.RELIABLE_ONLY:
self.unreliable = True
self.allow_sampling = False
# Check if we run flaky tests - if we do grab the test list as a playlist
if self.context.run_flaky_tests:
self.allow_sampling = False
query_days = int(get_setting("/exts/omni.kit.test/flakyTestsQueryDays", default=FLAKY_TESTS_QUERY_DAYS))
flaky_test_analyzer = FlakyTestAnalyzer(self.test_id, query_days)
if flaky_test_analyzer.should_skip_test():
self.skip = True
elif self.config.get("samplingFactor") == SamplingFactor.UPPER_BOUND:
pass # if an extension has disabled tests sampling we run all tests
else:
file = flaky_test_analyzer.generate_playlist()
if file:
self.args += [f"--/exts/omni.kit.test/runTestsFromFile='{file}'"]
def get_python_modules(ext_info: carb.dictionary.Item):
python_dict = ext_info.get("python", {})
if isinstance(python_dict, dict):
python_modules = python_dict.get("module", []) + python_dict.get("modules", [])
for m in python_modules:
module = m.get("name")
if module:
yield module
# By default if extension has python modules use them to fill in tests mask. Can be overridden with explicit tests list.
# Do that only for pure extensions tests, so that for tests inside an app extensions can opt in add more tests slowly.
python_modules_names = []
python_modules_names.extend(get_python_modules(self.ext_info))
if len(include_tests) == 0 and self.test_app.is_empty:
include_tests.extend(["{}.*".format(e) for e in python_modules_names])
# Cpp test libraries
test_libraries = self.config.get("cppTests", {}).get("libraries", [])
test_libraries = [resolve_path(library, ext_path) for library in test_libraries]
# If extension has tests -> run python (or cpp) tests, otherwise just do startup test
if len(include_tests) > 0 or len(test_libraries) > 0:
# We need kit.test as a test runner then
self.args += ["--enable", "omni.kit.test"]
if ui_mode:
self.args += [
"--enable",
"omni.kit.window.tests",
"--enable",
"omni.kit.window.extensions",
"--enable",
"omni.kit.renderer.core",
"--/exts/omni.kit.window.tests/openWindow=1",
"--/exts/omni.kit.test/testExtUIMode=1",
]
self.timeout = None # No timeout in that case
elif print_mode:
self.args += ["--/exts/omni.kit.test/printTestsAndQuit=true"]
else:
self.args += ["--/exts/omni.kit.test/runTestsAndQuit=true"]
for i, test_mask in enumerate(include_tests):
self.args += [f"--/exts/omni.kit.test/includeTests/{i}='{test_mask}'"]
for i, test_mask in enumerate(exclude_tests):
self.args += [f"--/exts/omni.kit.test/excludeTests/{i}='{test_mask}'"]
for i, test_mask in enumerate(unreliable_tests):
self.args += [f"--/exts/omni.kit.test/unreliableTests/{i}='{test_mask}'"]
for i, test_library in enumerate(test_libraries):
self.args += [f"--/exts/omni.kit.test/testLibraries/{i}='{test_library}'"]
else:
self.args += ["--/app/quitAfter=10", "--/crashreporter/gatherUserStory=0"]
# Reduce output on TC to make log shorter. Mostly that removes long extension startup/shutdown lists. We have
# that information in log files attached to artifacts anyway.
if is_running_on_ci():
self.args += ["--/app/enableStdoutOutput=0"]
# Test filtering (support shorter version)
argv = get_argv()
filter_value = _parse_arg_shortcut(argv, "-f")
if filter_value:
self.args += [f"--/exts/omni.kit.test/runTestsFilter='{filter_value}'"]
# Pass some args down the line:
self.args += _propagate_args(argv, "--portable")
self.args += _propagate_args(argv, "--portable-root", True)
self.args += _propagate_args(argv, "--allow-root")
self.args += _propagate_args(argv, "-d")
self.args += _propagate_args(argv, "-v")
self.args += _propagate_args(argv, "-vv")
self.args += _propagate_args(argv, "--wait-debugger")
self.args += _propagate_args(argv, "--/exts/omni.kit.test/runTestsFilter", starts_with=True)
self.args += _propagate_args(argv, "--/exts/omni.kit.test/runTestsFromFile", starts_with=True)
self.args += _propagate_args(argv, "--/exts/omni.kit.test/testExtRunUnreliableTests", starts_with=True)
self.args += _propagate_args(argv, "--/exts/omni.kit.test/doNotQuit", starts_with=True)
self.args += _propagate_args(argv, "--/exts/omni.kit.test/parallelRun", starts_with=True)
self.args += _propagate_args(argv, "--/telemetry/mode", starts_with=True)
self.args += _propagate_args(argv, "--/crashreporter/data/testName", starts_with=True)
def is_arg_prefix_present(args, prefix: str):
for arg in args:
if arg.startswith(prefix):
return True
return False
# make sure to set the telemetry mode to 'test' if it hasn't explicitly been overridden
# to something else. This prevents structured log events generated from tests from
# unintentionally polluting the telemetry analysis data.
if not is_arg_prefix_present(self.args, "--/telemetry/mode"):
self.args += ["--/telemetry/mode=test"]
# make sure to pass on the test name that was given in the settings if it was not
# explicitly given on the command line.
if not is_arg_prefix_present(self.args, "--/crashreporter/data/testName"):
test_name_setting = get_setting("/crashreporter/data/testName")
if test_name_setting != None:
self.args += [f"--/crashreporter/data/testName=\"{test_name_setting}\""]
# Read default coverage settings
default_coverage_settings = read_coverage_collector_settings()
# Sets if python test coverage enabled or disabled
py_coverage_enabled = self.config.get("pyCoverageEnabled", default_coverage_settings.enabled or coverage_mode)
# This must be set explicitly for the child test process:
# if the main process gets this setting from the command line and it's different from
# values in the configuration files then we must pass it to the child process but
# there is no way to know whether or not the value were from the command line so
# always set it explicitly for the child process
self.args += [f"--/exts/omni.kit.test/pyCoverageEnabled={py_coverage_enabled}"]
if py_coverage_enabled:
self.allow_sampling = False
py_coverage_filter = default_coverage_settings.filter or []
py_coverage_deps_omit = []
# If custom filter is specified, only use that list
custom_filter = self.config.get("pyCoverageFilter", None)
if custom_filter:
py_coverage_filter = custom_filter
else:
# Append all python modules
if self.config.get("pyCoverageIncludeModules", default_coverage_settings.include_modules):
for m in python_modules_names:
py_coverage_filter.append(m)
# Append all python modules from the dependencies
dependencies = [
{
"setting": "pyCoverageIncludeDependencies",
"default": default_coverage_settings.include_dependencies,
"config": self.ext_info,
},
{
"setting": "pyCoverageIncludeTestDependencies",
"default": default_coverage_settings.include_test_dependencies,
"config": self.config,
},
]
for d in dependencies:
if not self.config.get(d["setting"], d["default"]):
continue
deps = d["config"].get("dependencies", [])
manager = omni.kit.app.get_app().get_extension_manager()
for ext_d in manager.get_extensions():
if ext_d["name"] not in deps:
continue
ext_info = manager.get_extension_dict(ext_d["id"])
py_coverage_filter.extend(get_python_modules(ext_info))
# also look for omit in dependencies
test_info = ext_info.get("test", None)
if isinstance(test_info, list) or isinstance(test_info, tuple):
for t in test_info:
for cov_omit in t.get("pyCoverageOmit", []):
cov_omit = cov_omit.replace("\\", "/")
if not os.path.isabs(cov_omit) and not cov_omit.startswith("*/"):
cov_omit = "*/" + cov_omit
py_coverage_deps_omit.append(cov_omit)
if len(py_coverage_filter) > 0:
for i, cov_filter in enumerate(py_coverage_filter):
self.args += [f"--/exts/omni.kit.test/pyCoverageFilter/{i}='{cov_filter}'"]
# omit files/path for coverage
default_py_coverage_omit = default_coverage_settings.omit or []
py_coverage_omit = list(self.config.get("pyCoverageOmit", default_py_coverage_omit))
py_coverage_omit.extend(py_coverage_deps_omit)
if len(py_coverage_omit) > 0:
for i, cov_omit in enumerate(py_coverage_omit):
cov_omit = cov_omit.replace("\\", "/")
if not os.path.isabs(cov_omit) and not cov_omit.startswith("*/"):
cov_omit = "*/" + cov_omit
self.args += [f"--/exts/omni.kit.test/pyCoverageOmit/{i}='{cov_omit}'"]
# in coverage mode we generate a report at the end, need to set the settings on the parent process
if coverage_mode:
carb.settings.get_settings().set("/exts/omni.kit.test/pyCoverageEnabled", py_coverage_enabled)
carb.settings.get_settings().set("/exts/omni.kit.test/testExtGenerateCoverageReport", True)
# Extra extensions to run
exts_to_enable = [self.ext_id]
for ext in self.config.get("dependencies", []):
self.args += ["--enable", ext]
exts_to_enable.append(ext)
# Check if skipped by code change analyzer based on extensions it is about to enable
if self.context.change_analyzer:
self.change_analyzer_result = self.context.change_analyzer.analyze(
self.test_id, self.ext_name, exts_to_enable
)
if self.change_analyzer_result.should_skip_test:
self.skip = True
if not self.context.change_analyzer.allow_sampling():
self.allow_sampling = False
# Tests Sampling per extension
default_sampling = float(
get_setting("/exts/omni.kit.test/testExtSamplingFactor", default=SamplingFactor.UPPER_BOUND)
)
sampling_factor = clamp(
self.config.get("samplingFactor", default_sampling), SamplingFactor.LOWER_BOUND, SamplingFactor.UPPER_BOUND
)
if sampling_factor == SamplingFactor.UPPER_BOUND:
self.allow_sampling = False
if self.allow_sampling and self._use_tests_sampling():
self.args += [f"--/exts/omni.kit.test/samplingFactor={sampling_factor}"]
# tests random order
random_order = get_setting("/exts/omni.kit.test/testExtRandomOrder", default=False)
if random_order:
self.args += ["--/exts/omni.kit.test/testExtRandomOrder=1"]
# Test Sampling Seed
seed = int(get_setting("/exts/omni.kit.test/testExtSamplingSeed", default=-1))
if seed >= 0:
self.args += [f"--/exts/omni.kit.test/testExtSamplingSeed={seed}"]
# Extra args
self.args += list(get_setting("/exts/omni.kit.test/testExtArgs", default=[]))
# Extra args
self.args += self.config.get("args", [])
# if in ui mode we need to remove --no-window
if ui_mode:
self.args = [a for a in self.args if a != "--no-window"]
# Build fail patterns
self.patterns = FailPatterns(
self.config.get("stdoutFailPatterns", {}).get("include", []),
self.config.get("stdoutFailPatterns", {}).get("exclude", []),
)
self.patterns.merge(self.context.shared_patterns)
# Pass all unprocessed argv down the line at the very end. They can also have another `--` potentially.
unprocessed_argv = get_unprocessed_argv()
if unprocessed_argv:
self.args += unprocessed_argv
# Other settings
self.parallelizable = self.config.get("parallelizable", True)
def _pre_test_run(self, test_run: int, retry_strategy: RetryStrategy):
"""Update arguments that must change between each test run"""
if test_run > 0:
for index, arg in enumerate(self.args):
# make sure to use a different log file if we run tests multiple times
if arg.startswith("--/log/file="):
ts = get_local_timestamp()
self.log_file = f"{self.output_path}/{self.app_name}_{ts}_{test_run}.log"
self.args[index] = f"--/log/file='{self.log_file}'"
# make sure to use a different random seed if present, only valid on some retry strategies
if retry_strategy == RetryStrategy.ITERATIONS or retry_strategy == RetryStrategy.RERUN_UNTIL_FAILURE:
if arg.startswith("--/exts/omni.kit.test/testExtSamplingSeed="):
random_seed = random.randint(0, 2**16)
self.args[index] = f"--/exts/omni.kit.test/testExtSamplingSeed={random_seed}"
def _use_tests_sampling(self) -> bool:
external_build = get_setting("/privacy/externalBuild")
if external_build:
return False
use_sampling = get_setting("/exts/omni.kit.test/useSampling", default=True)
if not use_sampling:
return False
use_sampling = bool(os.getenv("OMNI_KIT_TEST_USE_SAMPLING", default=True))
if not use_sampling:
return False
sampling_context = get_setting("/exts/omni.kit.test/testExtSamplingContext")
if sampling_context == SamplingContext.CI and is_running_on_ci():
return True
elif sampling_context == SamplingContext.LOCAL and not is_running_on_ci():
return True
return sampling_context == SamplingContext.ANY
def get_cmd(self) -> str:
return " ".join(self.args)
def on_start(self):
self.result = ExtTestResult()
self.reporter.exttest_start(self.test_id, self.tc_test_id, self.ext_id, self.ext_name)
self.stdout.write(BEGIN_SEPARATOR.format(self.test_id))
def on_finish(self, test_result):
self.stdout.write(END_SEPARATOR.format("PASSED" if test_result else "FAILED", self.test_id))
self.reporter.exttest_stop(self.test_id, self.tc_test_id, passed=test_result)
def on_fail(self, fail_message):
# TC service messages can't match failure with a test start message when there are other tests in between.
# As a work around in that case stop test and start again (send those messages). That makes it has 2 block
# entries in the log, but gets reported as failed correctly.
if is_running_in_teamcity():
self.reporter.exttest_stop(self.test_id, self.tc_test_id, report=False)
self.reporter.exttest_start(self.test_id, self.tc_test_id, self.ext_id, self.ext_name, report=False)
self.reporter.exttest_fail(self.test_id, self.tc_test_id, "Error", fail_message)
self.stdout.write(f"{fail_message}\n")
def _kill_process_recursive(pid, stream):
def _output(msg: str):
teamcity_message("message", text=msg)
stream.write(msg)
def _terminate(proc: psutil.Process):
try:
proc.terminate()
except psutil.AccessDenied as e:
_error(stream, f"Access denied: {e}")
except psutil.ZombieProcess as e:
_error(stream, f"Encountered a zombie process: {e}")
except psutil.NoSuchProcess as e:
_error(stream, f"Process no longer exists: {e}")
except (psutil.Error, Exception) as e:
_error(stream, f"An error occurred: {str(e)}")
try:
process = psutil.Process(pid)
# kill all children of test process (if any)
for proc in process.children(recursive=True):
if crash_process(proc, stream):
_output(f"\nTest Process Timed out, crashing child test process to collect callstack, PID: {proc.pid}\n\n")
else:
_output(
f"\nAttempt to crash child test process to collect callstack failed. Killing child test process, PID: {proc.pid}\n\n"
)
_terminate(proc)
# kill the test process itself
if crash_process(process, stream):
_output(f"\nTest Process Timed out, crashing test process to collect callstack, PID: {process.pid}\n\n")
else:
_output(
f"\nAttempt to crash test process to collect callstack failed. Killing test process, PID: {process.pid}\n\n"
)
_terminate(process)
except psutil.NoSuchProcess as e:
_error(stream, f"Process no longer exists: {e}")
global _asyncio_process_was_terminated
_asyncio_process_was_terminated = True
PRAGMA_REGEX = re.compile(r"^##omni\.kit\.test\[(.*)\]")
def _extract_metadata_pragma(line, metadata):
"""
Test subprocs can print specially formatted pragmas, that get picked up here as extra fields
that get printed into the status report. Pragmas must be at the start of the line, and should
be the only thing on that line.
Format:
##omni.kit.test[op, key, value]
op = operation type, either "set", "append" or "del" (str)
key = name of the key (str)
value = string value (str)
Examples:
# set a value
##omni.kit.test[set, foo, this is a message and spaces are allowed]
# append a value to a list
##omni.kit.test[append, bah, test-13]
"""
match = PRAGMA_REGEX.match(line)
if not match:
return False
body = match.groups()[0]
args = body.split(",")
args = [x.strip() for x in args]
if not args:
return False
op = args[0]
args = args[1:]
if op in ("set", "append"):
if len(args) != 2:
return False
key, value = args
if op == "set":
metadata[key] = value
elif op == "append":
metadata.setdefault(key, []).append(value)
elif op == "del":
if len(args) != 1:
return False
key = args[0]
del metadata[key]
else:
return False # unsupported pragma op
return True
async def _run_test_process(test: ExtTest) -> Tuple[int, List[str], Dict]:
"""Run test process and read stdout (use PIPE)."""
returncode = 0
fail_messages = []
fail_patterns = defaultdict(list)
test_run_metadata = {}
proc = None
try:
test.stdout.write(f">>> running process: {test.get_cmd()}\n")
_debug(test.stdout, f"fail patterns: {test.patterns}")
async def run_proc():
nonlocal proc
proc = await asyncio.create_subprocess_exec(
*test.args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0,
)
async for line in proc.stdout:
suppress_line = False
line = line.decode(errors="replace").replace("\r\n", "\n").replace("\r", "\n")
# Check for failure on certain stdout message (like log errors)
nonlocal fail_messages
pattern_str, messages, exclude_matched = test.patterns.match_line(line)
if pattern_str and messages:
fail_patterns[pattern_str].append(messages)
# Check for special pragmas printed by the child proc that tell us to add custom
# fields to the formatted status report
try:
if _extract_metadata_pragma(line, test_run_metadata):
suppress_line = True
except: # noqa
pass
# grab the number of tests
m = re.match(r"(?:Running|Printing All) Tests \(count: (\d+)\)", line, re.M)
if m:
try:
test.result.test_count = int(m.group(1))
except: # noqa
pass
# replace with some generic message to avoid confusion when people search for [error] etc.
if exclude_matched and test.context.trim_excluded_messages:
line = "[...line contained error that was excluded by omni.kit.test...]\n"
if not suppress_line:
test.stdout.write("|| " + line)
await proc.wait()
nonlocal returncode
returncode = proc.returncode
proc = None
await asyncio.wait_for(run_proc(), timeout=test.timeout)
except subprocess.CalledProcessError as e:
returncode = e.returncode
fail_messages.append(f"subprocess.CalledProcessError was raised: {e.output}")
except asyncio.TimeoutError:
returncode = 15
fail_messages.append(
f"Process timed out (timeout: {test.timeout} seconds), terminating. Check artifacts for .dmp files."
)
if proc:
_kill_process_recursive(proc.pid, test.stdout)
except NotImplementedError as e:
fail_messages.append(
f"The asyncio loop does not implement subprocess. This is known to happen when using SelectorEventLoop on Windows, exception {e}"
)
# loop all pattern matches and put them on top of the fail messages
pattern_messages = []
for pattern, messages in fail_patterns.items():
pattern_messages.append(f"Matched {len(messages)} fail pattern '{pattern}' in stdout: ")
for msg in messages:
pattern_messages.append(f" '{msg}'")
fail_messages = pattern_messages + fail_messages
# return code failure check.
if returncode == 13:
# 13 - is code we return when python test fails
failing_tests_cnt = max(len(test_run_metadata.get(KEY_FAILING_TESTS, [])), 1)
fail_messages.append(f"{failing_tests_cnt} test(s) failed.")
elif returncode == 15:
# 15 - is code we return when a test process timeout, fail_message already added
pass
elif returncode != 0:
# other return codes usually mean crash
fail_messages.append("Process might have crashed or timed out.")
# Check if any unittests were started but never completed (crashed/timed out/etc.)
# When a test crash the 'stop' message is missing making test results harder to read, add them manually.
for key, value in test_run_metadata.items():
if type(value) == str and value.startswith(STARTED_UNITTEST):
test_id = key
tc_test_id = value.replace(STARTED_UNITTEST, "", 1)
test.reporter.unittest_fail(
test_id,
tc_test_id,
"Error",
f"Test started but never finished, test: {tc_test_id}. Test likely crashed or timed out.",
)
test.reporter.unittest_stop(test_id, tc_test_id)
return (returncode, fail_messages, test_run_metadata)
def _propagate_args(argv, arg_name, has_value=False, starts_with=False):
args = []
for i, arg in enumerate(argv):
if arg == arg_name or (starts_with and arg.startswith(arg_name)):
args += [arg]
if has_value:
args += [argv[i + 1]]
return args
def _parse_arg_shortcut(argv, arg_name):
for i, arg in enumerate(argv):
if arg == arg_name:
return argv[i + 1]
return None
def _get_test_configs_for_ext(ext_info, name_filter=None) -> List[Dict]:
test_config = ext_info.get("test", None)
configs = []
if not test_config:
# no [[test]] entry
configs.append({})
elif isinstance(test_config, dict):
# [test] entry
configs.append(test_config)
elif isinstance(test_config, list) or isinstance(test_config, tuple):
# [[test]] entry
if len(test_config) == 0:
configs.append({})
else:
configs.extend(test_config)
# Filter those matching the name filter
configs = [t for t in configs if not name_filter or match(t.get("name", DEFAULT_TEST_NAME), [name_filter])]
# Filter out disabled
configs = [t for t in configs if t.get("enabled", True)]
return configs
def is_matching_list(ext_id, ext_name, ext_list):
return any(fnmatch.fnmatch(ext_id, p) or fnmatch.fnmatch(ext_name, p) for p in ext_list)
def _build_exts_set(exts: List[str], exclude: List[str], use_registry: bool, match_version_as_string: bool) -> Set[str]:
manager = omni.kit.app.get_app().get_extension_manager()
all_exts = manager.get_extensions()
if use_registry:
manager.sync_registry()
all_exts += manager.get_registry_extensions()
def is_match_ext(ext_id, ext_name, ext_def):
return (fnmatch.fnmatch(ext_id, ext_def) or fnmatch.fnmatch(ext_name, ext_def)) and not is_matching_list(
ext_id, ext_name, exclude
)
exts_to_test = set()
for ext_def in exts:
# Empty string is same as "all"
if ext_def == "":
ext_def = "*"
# If wildcard is used, match all
if "*" in ext_def:
exts_to_test.update([e["id"] for e in all_exts if is_match_ext(e["id"], e["name"], ext_def)])
else:
# Otherwise use extension manager to get matching version and pick highest one (they are sorted)
ext_ids = [v["id"] for v in manager.fetch_extension_versions(ext_def)]
if match_version_as_string:
ext_ids = [v for v in ext_ids if v.startswith(ext_def)]
# Take highest version, but if we are not using registry skip remote local one:
for ext_id in ext_ids:
if use_registry or manager.get_extension_dict(ext_id) is not None:
exts_to_test.add(ext_id)
break
return sorted(exts_to_test)
def _format_cmdline(cmdline: str) -> str:
"""Format commandline printed from CI so that we can run it locally"""
cmdline = cmdline.replace("\\", "/").replace("//", "/")
if is_running_on_ci():
exe_path = cmdline.split(" ")[0]
index = exe_path.find("/_build/")
if index != -1:
path_to_remove = exe_path[:index]
cmdline = (
cmdline.replace(path_to_remove, ".")
.replace(path_to_remove.lower(), ".")
.replace(path_to_remove.replace("/", "\\"), ".")
)
return cmdline
def _get_test_cmdline(ext_name: str, failed_tests: list = []) -> list:
"""Return an example cmdline to run extension tests or a single unittest"""
cmdline = []
try:
shell_ext = carb.tokens.get_tokens_interface().resolve("${shell_ext}")
kit_exe = carb.tokens.get_tokens_interface().resolve("${kit}")
path_to_kit = _format_cmdline(os.path.relpath(kit_exe, os.getcwd()))
if not path_to_kit.startswith("./"):
path_to_kit = f"./{path_to_kit}"
test_file = f"{path_to_kit}/tests-{ext_name}{shell_ext}"
if failed_tests:
test_name = failed_tests[0].rsplit(".")[-1]
cmdline.append(f" Cmdline to run a single unittest: {test_file} -f *{test_name}")
cmdline.append(f" Cmdline to run the extension tests: {test_file}")
except: # noqa
pass
return cmdline
async def gather_with_concurrency(n, *tasks):
semaphore = asyncio.Semaphore(n)
async def sem_task(task):
async with semaphore:
return await task
return await asyncio.gather(*(sem_task(task) for task in tasks))
async def run_serial_and_parallel_tasks(parallel_tasks, serial_tasks, max_parallel_tasks: int):
for r in serial_tasks:
yield await r
for r in await gather_with_concurrency(max_parallel_tasks, *parallel_tasks):
yield r
async def _run_ext_test(run_context: TestRunContext, test: ExtTest, on_status_report_fn):
def _print_info(mode: str, result_str: str = None):
if result_str is None:
result_str = "succeeded" if test.result.passed else "failed"
print(f"{test.test_id} test {result_str} ({mode} {test_run + 1} out of {run_context.max_test_run})")
teamcity_test_retry_support(run_context.retry_strategy == RetryStrategy.RETRY_ON_FAILURE)
# Allow retrying tests multiple times:
for test_run in range(run_context.max_test_run):
is_last_try = (test_run == run_context.max_test_run - 1) or (
run_context.retry_strategy == RetryStrategy.NO_RETRY
)
retry_failed_tests = run_context.retry_strategy == RetryStrategy.RETRY_ON_FAILURE
test._pre_test_run(test_run, run_context.retry_strategy)
test = await _run_ext_test_once(test, on_status_report_fn, is_last_try, retry_failed_tests)
# depending on the retry strategy we might continue or exit the loop
if run_context.retry_strategy == RetryStrategy.NO_RETRY:
# max_test_run is ignored in no-retry strategy
break
elif run_context.retry_strategy == RetryStrategy.RETRY_ON_FAILURE:
# retry on failure - stop at first success otherwise continue
result_str = "succeeded"
if not test.result.passed:
result_str = "failed" if is_last_try else "failed, retrying..."
_print_info("attempt", result_str)
if test.result.passed:
break
else:
test.retries += 1
elif run_context.retry_strategy == RetryStrategy.ITERATIONS:
# iterations - continue until the end
_print_info("iteration")
elif run_context.retry_strategy == RetryStrategy.RERUN_UNTIL_FAILURE:
# rerun until failure - stop at first failure otherwise continue
_print_info("rerun")
if not test.result.passed:
break
else:
_error(sys.stderr, f"Invalid retry strategy '{run_context.retry_strategy}'")
return test
async def _run_ext_test_once(test: ExtTest, on_status_report_fn, is_last_try: bool, retry_failed_tests: bool):
ext = test.ext_id
if on_status_report_fn:
on_status_report_fn(test.test_id, TestRunStatus.RUNNING)
# Starting test
test.on_start()
err_messages = []
metadata = {}
cmd = ""
returncode = 0
if test.valid:
cmd = test.get_cmd()
# Run process
start_time = time.time()
returncode, err_messages, metadata = await _run_test_process(test)
test.result.duration = round(time.time() - start_time, 2)
else:
err_messages.append(f"Failed to run process for extension testing (ext: {ext}).")
if test.unreliable:
test.result.unreliable = 1
# Grab failed tests
test.failed_tests = list(metadata.pop(KEY_FAILING_TESTS, []))
for key, value in list(metadata.items()):
if type(value) == str and value.startswith(STARTED_UNITTEST):
test_id = key
test.failed_tests.append(test_id + " (started but never finished)")
del metadata[key]
if retry_failed_tests:
# remove failed tests from previous run if any
test.args = [item for item in test.args if not item.startswith("--/exts/omni.kit.test/retryFailedTests")]
# Only retry failed tests if all conditions are met:
# - retry-on-failure strategy selected
# - metadata with failing tests is present
# - extension tests reported failures but no crash (return code 13)
# - at least on retry left to do (ie: not last retry)
if test.failed_tests and returncode == 13 and not is_last_try:
# add new failed tests as args for the next run
for i, test_id in enumerate(test.failed_tests):
test.args.append(f"--/exts/omni.kit.test/retryFailedTests/{i}='{test_id}'")
# Report failure and mark overall run as failure
test.result.passed = True
if len(err_messages) > 0:
spaces_8 = " " * 8
spaces_12 = " " * 12
messages_str = f"\n{spaces_8}".join([""] + err_messages)
fail_message_lines = [
"",
"[fail] Extension Test failed. Details:",
f" Cmdline: {_format_cmdline(cmd)}",
]
fail_message_lines += _get_test_cmdline(test.ext_name, test.failed_tests)
fail_message_lines += [
f" Return code: {returncode} ({returncode & (2**31-1):#010x})",
f" Failure reason(s): {messages_str}",
]
details_message_lines = [" Details:"]
if metadata:
details_message_lines.append(f"{spaces_8}Metadata:")
for key, value in sorted(metadata.items()):
details_message_lines.append(f"{spaces_12}{key}: {value}")
if test.failed_tests:
messages_str = f"\n{spaces_12}".join([""] + test.failed_tests)
details_message_lines.append(f"{spaces_8}{KEY_FAILING_TESTS}: {messages_str}")
if not omni.kit.app.get_app().is_app_external():
url = f"http://omnitests.nvidia.com/?query={test.test_id}"
details_message_lines.append(f"{spaces_8}Test history:")
details_message_lines.append(f"{spaces_12}{url}")
fail_message = "\n".join(fail_message_lines + details_message_lines)
test.result.passed = False
if test.unreliable:
test.result.unreliable_fail = 1
test.stdout.write("[fail] Extension test failed, but marked as unreliable.\n")
else:
test.result.fail = 1
test.stdout.write("[fail] Extension test failed.\n")
if is_last_try:
test.on_fail(fail_message)
if on_status_report_fn:
on_status_report_fn(test.test_id, TestRunStatus.FAILED, fail_message=fail_message, ext_test=test)
else:
test.stdout.write("[ ok ] Extension test passed.\n")
test.on_finish(test.result.passed)
if test.result.passed and on_status_report_fn:
on_status_report_fn(test.test_id, TestRunStatus.PASSED, ext_test=test)
# dump stdout, acts as stdout sync point for parallel run
if test.stdout != sys.stdout:
if test.context.trim_stdout_on_success and test.result.passed:
for line in test.stdout.getvalue().splitlines():
# We still want to print all service messages to correctly output number of tests on TC and all that.
if "##teamcity[" in line:
sys.stdout.write(line)
sys.stdout.write("\n")
sys.stdout.write(
f"[omni.kit.test] Stdout was trimmed. Look for the Kit log file '{test.log_file}' in TC artifacts for the full output.\n"
)
else:
sys.stdout.write(test.stdout.getvalue())
sys.stdout.flush()
# reset test.stdout (io.StringIO)
test.stdout.truncate(0)
test.stdout.seek(0)
return test
def _build_test_id(test_type: str, ext: str, app: str = "", test_name: str = "") -> str:
s = ""
if test_type:
s += f"{test_type}:"
s += ext_id_to_fullname(ext)
if test_name and test_name != DEFAULT_TEST_NAME:
s += f"-{test_name}"
if app:
s += f"_app:{app}"
return s
async def _run_ext_tests(exts, on_status_report_fn, exclude_exts, only_list=False) -> bool:
run_context = TestRunContext()
use_registry = get_setting("/exts/omni.kit.test/testExtUseRegistry", default=False)
match_version_as_string = get_setting("/exts/omni.kit.test/testExtMatchVersionAsString", default=False)
test_type = get_setting("/exts/omni.kit.test/testExtTestType", default="exttest")
# Test Name filtering (support shorter version)
test_name_filter = _parse_arg_shortcut(get_argv(), "-n")
if not test_name_filter:
test_name_filter = get_setting("/exts/omni.kit.test/testExtTestNameFilter", default="")
max_parallel_procs = int(get_setting("/exts/omni.kit.test/testExtMaxParallelProcesses", default=-1))
if max_parallel_procs <= 0:
max_parallel_procs = multiprocessing.cpu_count()
exts_to_test = _build_exts_set(exts, exclude_exts, use_registry, match_version_as_string)
# Prepare an app:
test_app = TestApp(sys.stdout)
def fail_all(fail_message):
reporter = TestReporter(sys.stdout)
for ext in exts:
message = fail_message.format(ext)
test_id = _build_test_id(test_type, ext, test_app.name)
tc_test_id = test_id.replace(".", "+") + ".[PROCESS CHECK]"
_error(sys.stderr, message)
# add start / fail / stop messages for TC + our own reporter
reporter.exttest_start(test_id, tc_test_id, ext, ext)
reporter.exttest_fail(test_id, tc_test_id, fail_type="Error", fail_message=message)
reporter.exttest_stop(test_id, tc_test_id, passed=False)
if on_status_report_fn:
on_status_report_fn(test_id, TestRunStatus.FAILED, fail_message=message)
# If no extensions found report query entries as failures
if len(exts_to_test) == 0:
fail_all("Can't find any extension matching: '{0}'.")
# If no app found report query entries as failures
if not test_app.path:
fail_all(f"Can't find app: {test_app.name}")
exts_to_test = []
# Prepare test run tasks, put into separate serial and parallel queues
parallel_tasks = []
serial_tasks = []
is_parallel_run = max_parallel_procs > 1 and len(exts_to_test) > 1
exts_issues = []
total = 0
for ext in exts_to_test:
ext_info = _prepare_ext_for_testing(ext)
if ext_info:
test_configs = _get_test_configs_for_ext(ext_info, test_name_filter)
unique_test_names = set()
for test_config in test_configs:
valid = True
test_name = test_config.get("name", DEFAULT_TEST_NAME)
if test_name in unique_test_names:
_error(
sys.stderr,
f"Extension {ext} has multiple [[test]] entry with the same 'name' attribute. It should be unique, default is '{DEFAULT_TEST_NAME}'",
)
valid = False
else:
unique_test_names.add(test_name)
total += 1
# Build test id.
test_id = _build_test_id(test_type, ext, test_app.name, test_name)
if only_list:
print(f"test_id: '{test_id}'")
continue
test = ExtTest(
ext,
ext_info,
test_config,
test_id,
is_parallel_run,
run_context=run_context,
test_app=test_app,
valid=valid,
)
# fmt: off
# both means we run all tests (reliable and unreliable)
# otherwise we either run reliable tests only or unreliable tests only, so we skip accordingly
if run_context.run_unreliable_tests != RunExtTests.BOTH and int(run_context.run_unreliable_tests) != int(test.unreliable):
test_unreliable = "unreliable" if test.unreliable else "reliable"
run_unreliable = "unreliable" if run_context.run_unreliable_tests == RunExtTests.UNRELIABLE_ONLY else "reliable"
print(f"[INFO] {test_id} skipped because it's marked as {test_unreliable} and we currently run all {run_unreliable} tests")
total -= 1
continue
# fmt: on
# Test skipped itself? (it should have explained it already by now)
if test.skip:
total -= 1
continue
# A single test may be invoked in more than one way, gather them all
from .ext_test_generator import get_tests_to_run
for test_instance in get_tests_to_run(test, ExtTest, run_context, is_parallel_run, valid):
task = _run_ext_test(run_context, test_instance, on_status_report_fn)
if test_instance.parallelizable:
parallel_tasks.append(task)
else:
serial_tasks.append(task)
else:
exts_issues.append(ext)
intro = f"Running {total} Extension Test Process(es)."
if run_context.run_unreliable_tests == RunExtTests.UNRELIABLE_ONLY:
intro = "[Unreliable Tests Run] " + intro
print(intro)
# Actual test run:
finished_tests: List[ExtTest] = []
fail_count = 0
unreliable_fail_count = 0
unreliable_total = 0
async for test in run_serial_and_parallel_tasks(parallel_tasks, serial_tasks, max_parallel_procs):
unreliable_total += test.result.unreliable
unreliable_fail_count += test.result.unreliable_fail
fail_count += test.result.fail
finished_tests.append(test)
if only_list:
print(f"Found {total} tests processes to run.")
return True
return_result = True
def generate_summary():
for test in finished_tests:
if test.result.passed:
if test.retries > 0:
res_str = "[retry ok]"
else:
res_str = "[ ok ]"
else:
res_str = "[ fail ]"
if test.result.unreliable:
res_str += " [unreliable]"
res_str += f" [{test.result.duration:5.1f}s]"
res_str += f" {test.test_id}"
res_str += f" (Count: {test.result.test_count})"
yield f"{res_str}"
for ext in exts_issues:
res_str = f"[ fail ] {ext} (extension registry issue)"
yield f"{res_str}"
def get_failed_tests():
all_failed_tests = [t for test in finished_tests for t in test.failed_tests]
if all_failed_tests:
yield f"\nFailing tests (Count: {len(all_failed_tests)}) :"
for test_name in all_failed_tests:
yield f" - {test_name}"
# Print summary
test_results_file = os.path.join(run_context.output_path, "ext_test_results.txt")
with open(test_results_file, "a") as f:
def report(line):
print(line)
f.write(line + "\n")
report("\n")
report("=" * 60)
report(f"Extension Tests Run Summary (Date: {run_context.start_ts})")
report("=" * 60)
report(" app: {}".format(test_app.name if not test_app.is_empty else "[empty]"))
report(f" retry strategy: {run_context.retry_strategy}," f" max test run: {run_context.max_test_run}")
report("=" * 60)
for line in generate_summary():
report(line)
for line in get_failed_tests():
report(line)
report("=" * 60)
report("=" * 60)
if unreliable_total > 0:
report(
f"UNRELIABLE TESTS REPORT: {unreliable_fail_count} unreliable tests processes failed out of {unreliable_total}."
)
# Exit with non-zero code on failure
if fail_count > 0 or len(exts_issues) > 0:
if fail_count > 0:
report(f"[ERROR] {fail_count} tests processes failed out of {total}.")
if len(exts_issues) > 0:
report(f"[ERROR] {len(exts_issues)} extension registry issue.")
return_result = False
else:
report(f"[OK] All {total} tests processes returned 0.")
# Report all results
for test in finished_tests:
test.reporter.report_result(test)
return return_result
def run_ext_tests(test_exts, on_finish_fn=None, on_status_report_fn=None, exclude_exts=[]):
def on_status_report(*args, **kwargs):
if on_status_report_fn:
on_status_report_fn(*args, **kwargs)
_test_status_report(*args, **kwargs)
async def run():
result = await _run_ext_tests(test_exts, on_status_report, exclude_exts)
if on_finish_fn:
on_finish_fn(result)
return asyncio.ensure_future(run())
def shutdown_ext_tests():
# When running extension tests and killing the process after timeout, asyncio hangs somewhere in python shutdown.
# Explicitly closing event loop here helps with that.
if _asyncio_process_was_terminated:
def exception_handler(_, exc):
print(f"Asyncio exception on shutdown: {exc}")
asyncio.get_event_loop().set_exception_handler(exception_handler)
asyncio.get_event_loop().close()
| 60,071 | Python | 40.572318 | 161 | 0.594397 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/code_change_analyzer.py | import json
import os
import omni.kit.app
import logging
from typing import List
from .repo_test_context import RepoTestContext
from .utils import sha1_path, sha1_list, get_global_test_output_path
logger = logging.getLogger(__name__)
KNOWN_EXT_SOURCE_PATH = ["kit/source/extensions/", "source/extensions/"]
# We know for sure that this hash changes all the time and used in many many tests, don't want it to mess with our logic for now
STARTUP_SEQUENCE_EXCLUDE = ["omni.rtx.shadercache.d3d12", "omni.rtx.shadercache.vulkan"]
def _get_extension_hash(path):
path = os.path.normpath(path)
hash_cache_file = f"{get_global_test_output_path()}/exts_hash.json"
ext_hashes = {}
# cache hash calculation in a file to speed up things (it's slow)
try:
with open(hash_cache_file, "r") as f:
ext_hashes = json.load(f)
except FileNotFoundError:
pass
except Exception as e:
logger.warn(f"Failed to load extension hashes from {hash_cache_file}, error: {e}")
ext_hash = ext_hashes.get(path, None)
if ext_hash:
return ext_hash
ext_hash = sha1_path(path)
# read from file again in case it changed while calculating hash (parallel run) to update
try:
with open(hash_cache_file, "r") as f:
ext_hashes = json.load(f)
except FileNotFoundError:
pass
except Exception as e:
logger.warn(f"Failed to load extension hashes from {hash_cache_file}, error: {e}")
ext_hashes[path] = ext_hash
with open(hash_cache_file, "w") as f:
json.dump(ext_hashes, f)
return ext_hash
def _get_extension_name_for_file(file):
for path in KNOWN_EXT_SOURCE_PATH:
if file.startswith(path):
ext = file[len(path) :].split("/")[0]
return ext
return None
def _print(str, *argv):
print(f"[omni.kit.test.code_change_analyzer] {str}", *argv)
class ChangeAnalyzerResult:
def __init__(self):
self.should_skip_test = False
self.startup_sequence = []
self.startup_sequence_hash = ""
self.tested_ext_hash = ""
self.kernel_version = ""
class CodeChangeAnalyzer:
"""repo_test can provide (if in MR and on TC) with a list of changed files using env var.
Check if changed ONLY extensions. If any change is not in `source/extensions` -> run all tests
If changed ONLY extensions than for each test solve list of ALL enabled extensions and check against that list.
"""
def __init__(self, repo_test_context: RepoTestContext):
self._allow_sampling = True
self._allow_skipping = False
self._changed_extensions = self._gather_changed_extensions(repo_test_context)
def _gather_changed_extensions(self, repo_test_context: RepoTestContext):
data = repo_test_context.get()
if data:
changed_files = data.get("changed_files", [])
if changed_files:
self._allow_skipping = True
changed_extensions = set()
for file in changed_files:
ext = _get_extension_name_for_file(file)
if ext:
logger.info(f"Changed path: {file} is an extension: {ext}")
changed_extensions.add(ext)
elif self._allow_skipping:
_print("All tests will run. At least one changed file is not in an extension:", file)
self._allow_skipping = False
self._allow_sampling = False
if self._allow_skipping:
ext_list_str = "\n".join(("\t - " + e for e in changed_extensions))
_print(f"Only tests that use those extensions will run. Changed extensions:\n{ext_list_str}")
return changed_extensions
logger.info("No changed files provided")
return set()
def get_changed_extensions(self) -> List[str]:
return list(self._changed_extensions)
def allow_sampling(self) -> bool:
return self._allow_sampling
def _build_startup_sequence(self, result: ChangeAnalyzerResult, ext_name: str, exts: List):
result.kernel_version = omni.kit.app.get_app().get_kernel_version()
result.startup_sequence = [("kernel", result.kernel_version)]
for ext in exts:
if ext["name"] in STARTUP_SEQUENCE_EXCLUDE:
continue
path = ext.get("path", None)
if path:
hash = _get_extension_hash(path)
result.startup_sequence.append((ext["name"], hash))
if ext["name"] == ext_name:
result.tested_ext_hash = hash
# Hash whole startup sequence
result.startup_sequence_hash = sha1_list([hash for ext, hash in result.startup_sequence])
def analyze(self, test_id: str, ext_name: str, exts_to_enable: List[str]) -> ChangeAnalyzerResult:
result = ChangeAnalyzerResult()
result.should_skip_test = False
# Ask manager for extension startup sequence
manager = omni.kit.app.get_app().get_extension_manager()
solve_result, exts, err = manager.solve_extensions(
exts_to_enable, add_enabled=False, return_only_disabled=False
)
if not solve_result:
logger.warn(f"Failed to solve dependencies for extension(s): {exts_to_enable}, error: {err}")
return result
# Build hashes for a startup sequence
self._build_startup_sequence(result, ext_name, exts)
if not self._allow_skipping:
return result
if not self._changed_extensions:
return result
for ext in exts:
if ext["name"] in self._changed_extensions:
_print(f"{test_id} test will run because it uses the changed extension:", ext["name"])
self._allow_sampling = False
return result
_print(
f"{test_id} skipped by code change analyzer. Extensions enabled in this tests were not changed in this MR."
)
result.should_skip_test = True
return result
| 6,153 | Python | 34.572254 | 128 | 0.609946 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/gitlab.py | import os
from functools import lru_cache
# GitLab CI/CD variables :
# https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
@lru_cache()
def is_running_in_gitlab():
return bool(os.getenv("GITLAB_CI"))
@lru_cache()
def get_gitlab_build_url() -> str:
return os.getenv("CI_PIPELINE_URL") or ""
| 317 | Python | 18.874999 | 67 | 0.700315 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/tests/test_reporter.py | from pathlib import Path
import omni.kit.test
from ..reporter import _calculate_durations, _load_report_data, _load_coverage_results, _generate_html_report
CURRENT_PATH = Path(__file__).parent
DATA_TESTS_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data/tests")
class TestReporter(omni.kit.test.AsyncTestCase):
async def test_success_report_data(self):
"""
omni_kit_test_success_report.jsonl contains the report.jsonl of a successful run testing omni.kit.test
"""
path = DATA_TESTS_PATH.joinpath("omni_kit_test_success_report.jsonl")
report_data = _load_report_data(path)
self.assertEqual(len(report_data), 11)
result = report_data[10]
test_result = result.get("result", None)
self.assertNotEqual(test_result, None)
# make sure durations are good
_calculate_durations(report_data)
startup_duration = test_result["startup_duration"]
tests_duration = test_result["tests_duration"]
self.assertAlmostEqual(startup_duration, 1.040, places=3)
self.assertAlmostEqual(tests_duration, 0.007, places=3)
# make sure our ratio are good
duration = test_result["duration"]
startup_ratio = test_result["startup_ratio"]
tests_ratio = test_result["tests_ratio"]
self.assertAlmostEqual(startup_ratio, 100 * (startup_duration / duration), places=3)
self.assertAlmostEqual(tests_ratio, 100 * (tests_duration / duration), places=3)
async def test_fail_report_data(self):
"""
omni_kit_test_fail_report.jsonl contains the report.jsonl of a failed run of testing omni.kit.test
with a few failed tests and also a test that crash
"""
path = DATA_TESTS_PATH.joinpath("omni_kit_test_fail_report.jsonl")
report_data = _load_report_data(path)
self.assertEqual(len(report_data), 18)
result = report_data[17]
test_result = result.get("result", None)
self.assertNotEqual(test_result, None)
# make sure durations are good
_calculate_durations(report_data)
startup_duration = test_result["startup_duration"]
tests_duration = test_result["tests_duration"]
self.assertAlmostEqual(startup_duration, 0.950, places=3)
self.assertAlmostEqual(tests_duration, 0.006, places=3)
# make sure our ratio are good
duration = test_result["duration"]
startup_ratio = test_result["startup_ratio"]
tests_ratio = test_result["tests_ratio"]
self.assertAlmostEqual(startup_ratio, 100 * (startup_duration / duration), places=3)
self.assertAlmostEqual(tests_ratio, 100 * (tests_duration / duration), places=3)
async def test_html_report(self):
path = DATA_TESTS_PATH.joinpath("omni_kit_test_success_report.jsonl")
report_data = _load_report_data(path)
_calculate_durations(report_data)
merged_results, _ = _load_coverage_results(report_data, read_coverage=False)
html = _generate_html_report(report_data, merged_results)
# total duration is 1.32 seconds, in the hmtl report we keep 1 decimal so it will be shown as 1.3
self.assertTrue(html.find("<td>1.3</td>") != -1)
# startup duration will be 78.8 %
self.assertTrue(html.find("<td>78.8</td>") != -1)
| 3,342 | Python | 47.449275 | 110 | 0.664572 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/tests/test_kit_test.py | import unittest
import carb
import omni.kit.app
import omni.kit.test
# uncomment for dev work
# import unittest
class TestKitTest(omni.kit.test.AsyncTestCase):
async def test_test_settings(self):
# See [[test]] section
carb.log_error("This message will not fail the test because it is excluded in [[test]]")
self.assertEqual(carb.settings.get_settings().get("/extra_arg_passed/param"), 123)
async def test_test_other_settings(self):
self.assertEqual(carb.settings.get_settings().get("/extra_arg_passed/param"), 456)
async def test_that_is_excluded(self):
self.fail("Should not be called")
async def test_get_test(self):
if any("test_that_is_unreliable" in t.id() for t in omni.kit.test.get_tests()):
self.skipTest("Skipping if test_that_is_unreliable ran")
self.assertSetEqual(
{t.id() for t in omni.kit.test.get_tests()},
set(
[
"omni.kit.test.tests.test_kit_test.TestKitTest.test_are_async",
"omni.kit.test.tests.test_kit_test.TestKitTest.test_can_be_skipped_1",
"omni.kit.test.tests.test_kit_test.TestKitTest.test_can_be_skipped_2",
"omni.kit.test.tests.test_kit_test.TestKitTest.test_can_be_sync",
"omni.kit.test.tests.test_kit_test.TestKitTest.test_get_test",
"omni.kit.test.tests.test_kit_test.TestKitTest.test_test_settings",
"omni.kit.test.tests.test_kit_test.TestKitTest.test_with_metadata",
"omni.kit.test.tests.test_kit_test.TestKitTest.test_with_subtest",
"omni.kit.test.tests.test_lookups.TestLookups.test_lookups",
"omni.kit.test.tests.test_nvdf.TestNVDF.test_convert_advanced_types",
"omni.kit.test.tests.test_nvdf.TestNVDF.test_convert_basic_types",
"omni.kit.test.tests.test_nvdf.TestNVDF.test_convert_reserved_types",
"omni.kit.test.tests.test_reporter.TestReporter.test_fail_report_data",
"omni.kit.test.tests.test_reporter.TestReporter.test_html_report",
"omni.kit.test.tests.test_reporter.TestReporter.test_success_report_data",
"omni.kit.test.tests.test_sampling.TestSampling.test_sampling_factor_one",
"omni.kit.test.tests.test_sampling.TestSampling.test_sampling_factor_point_five",
"omni.kit.test.tests.test_sampling.TestSampling.test_sampling_factor_zero",
"omni.kit.test.tests.test_sampling.TestSampling.test_with_fake_nvdf_query",
]
),
)
self.assertListEqual(
[t.id() for t in omni.kit.test.get_tests(tests_filter="test_settings")],
[
"omni.kit.test.tests.test_kit_test.TestKitTest.test_test_settings",
],
)
async def test_are_async(self):
app = omni.kit.app.get_app()
update = app.get_update_number()
await app.next_update_async()
self.assertEqual(app.get_update_number(), update + 1)
def test_can_be_sync(self):
self.assertTrue(True)
@unittest.skip("Skip test with @unittest.skip")
async def test_can_be_skipped_1(self):
self.assertTrue(False)
async def test_can_be_skipped_2(self):
self.skipTest("Skip test with self.skipTest")
self.assertTrue(False)
# subTest will get fixes in python 3.11, see https://bugs.python.org/issue25894
async def test_with_subtest(self):
with self.subTest(msg="subtest example"):
self.assertTrue(True)
async def test_with_metadata(self):
"""This is an example to use metadata"""
print("##omni.kit.test[set, my_key, This line will be printed if the test fails]")
self.assertTrue(True)
async def test_that_is_unreliable(self):
"""This test will not run unless we run unreliable tests"""
self.assertTrue(True) # we don't make it fail when running unreliable tests
# Development tests - uncomment when doing dev work to test all ways a test can succeed / fail
# async def test_success(self):
# self.assertTrue(True)
# async def test_fail_1(self):
# self.assertTrue(False)
# async def test_fail_2(self):
# raise Exception("fuff")
# self.assertTrue(False)
# will crash with stack overflow
# async def test_fail_3(self):
# __import__("sys").setrecursionlimit(100000000)
# def crash():
# crash()
# crash()
| 4,638 | Python | 41.559633 | 101 | 0.617076 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/tests/test_nvdf.py | import omni.kit.test
from ..nvdf import remove_nvdf_form, to_nvdf_form
class TestNVDF(omni.kit.test.AsyncTestCase):
async def test_convert_basic_types(self):
d = {
"some_boolean": True,
"some_int": -123,
"some_float": 0.001,
"array_of_string": ["a", "b"],
}
nv = to_nvdf_form(d)
self.assertDictEqual(
nv, {"b_some_boolean": True, "l_some_int": -123, "d_some_float": 0.001, "s_array_of_string": ["a", "b"]}
)
r = remove_nvdf_form(nv)
self.assertDictEqual(d, r)
async def test_convert_advanced_types(self):
class myClass:
def __init__(self, int_value: int, float_value: float) -> None:
self.cl_int: int = int_value
self.cl_float: float = float_value
m = myClass(12, 0.1)
d = {
"some_list": [3, 4],
"some_tuple": (1, 2),
"some_class": m,
}
nv = to_nvdf_form(d)
self.assertDictEqual(
nv, {"l_some_list": [3, 4], "l_some_tuple": (1, 2), "some_class": {"l_cl_int": 12, "d_cl_float": 0.1}}
)
d["some_class"] = m.__dict__
r = remove_nvdf_form(nv)
self.assertDictEqual(d, r)
async def test_convert_reserved_types(self):
d = {
"ts_anything": 2992929,
"ts_created": 56555,
"_id": 69988,
}
nv = to_nvdf_form(d)
self.assertDictEqual(
nv, {"ts_anything": 2992929, "ts_created": 56555, "_id": 69988}
)
r = remove_nvdf_form(nv)
self.assertDictEqual(d, r)
| 1,649 | Python | 30.132075 | 116 | 0.4906 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/tests/__init__.py | from .test_kit_test import *
from .test_lookups import *
from .test_nvdf import *
from .test_reporter import *
from .test_sampling import *
| 140 | Python | 22.499996 | 28 | 0.742857 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/tests/test_lookups.py | """Test the functionality used by the test runner."""
import omni.kit.app
import omni.kit.test
class TestLookups(omni.kit.test.AsyncTestCase):
async def test_lookups(self):
"""Oddly self-referencing test that uses the test runner test lookup utility to confirm that the utility
finds this test.
"""
manager = omni.kit.app.get_app().get_extension_manager()
my_extension_id = manager.get_enabled_extension_id("omni.kit.test")
module_map = omni.kit.test.get_module_to_extension_map()
self.assertTrue("omni.kit.test" in module_map)
extension_info = module_map["omni.kit.test"]
self.assertEqual((my_extension_id, True), extension_info)
this_test_info = omni.kit.test.extension_from_test_name("omni.kit.test.TestLookups.test_lookups", module_map)
self.assertIsNotNone(this_test_info)
this_test_info_no_module = tuple(e for i, e in enumerate(this_test_info) if i != 2)
self.assertEqual((my_extension_id, True, False), this_test_info_no_module)
| 1,049 | Python | 44.652172 | 117 | 0.682555 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/tests/test_sampling.py | import urllib.error
from contextlib import suppress
import omni.kit.test
from ..nvdf import get_app_info
from ..sampling import Sampling
class TestSampling(omni.kit.test.AsyncTestCase):
def setUp(self):
self.sampling = Sampling(get_app_info())
self.unittests = ["test_one", "test_two", "test_three", "test_four"]
async def test_sampling_factor_zero(self):
self.sampling.run_query("omni.foo", self.unittests, running_on_ci=False)
samples = self.sampling.get_tests_to_skip(0.0)
# will return the same list but with a different order
self.assertEqual(len(samples), len(self.unittests))
async def test_sampling_factor_one(self):
self.sampling.run_query("omni.foo", self.unittests, running_on_ci=False)
samples = self.sampling.get_tests_to_skip(1.0)
self.assertListEqual(samples, [])
async def test_sampling_factor_point_five(self):
self.sampling.run_query("omni.foo", self.unittests, running_on_ci=False)
samples = self.sampling.get_tests_to_skip(0.5)
self.assertEqual(len(samples), len(self.unittests) / 2)
async def test_with_fake_nvdf_query(self):
with suppress(urllib.error.URLError):
self.sampling.run_query("omni.foo", self.unittests, running_on_ci=True)
samples = self.sampling.get_tests_to_skip(0.5)
if self.sampling.query_result is True:
self.assertEqual(len(samples), len(self.unittests) / 2)
else:
self.assertListEqual(samples, [])
| 1,551 | Python | 38.794871 | 83 | 0.662153 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/omni_test_registry/omni_test_registry.py | def omni_test_registry(*args, **kwargs):
"""
The decorator for Python tests.
NOTE: currently passing in the test uuid as a kwarg 'guid'
"""
def decorator(func):
func.guid = kwargs.get("guid", None)
return func
return decorator
| 269 | Python | 21.499998 | 62 | 0.6171 |
omniverse-code/kit/exts/omni.kit.test_suite.menu/omni/kit/test_suite/menu/tests/__init__.py | from .context_menu_bind_material_listview import *
| 51 | Python | 24.999988 | 50 | 0.803922 |
omniverse-code/kit/exts/omni.kit.test_suite.menu/omni/kit/test_suite/menu/tests/context_menu_bind_material_listview.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 os
import omni.kit.app
import omni.usd
import omni.kit.commands
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, Usd, UsdShade
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
delete_prim_path_children,
arrange_windows
)
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class ContextMenuBindMaterialListview(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 300.0)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
async def test_l1_context_menu_bind_material_listview(self):
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# grid_view_enabled = True doesn't work with item_offset
to_select = ["/World/Cube", "/World/Sphere", "/World/Cylinder"]
stage = omni.usd.get_context().get_stage()
material_test_helper = MaterialLibraryTestHelper()
content_browser_helper = ContentBrowserTestHelper()
await content_browser_helper.toggle_grid_view_async(False)
mdl_list = await omni.kit.material.library.get_mdl_list_async()
for mtl_name, mdl_path, submenu in mdl_list:
# delete any materials in looks
await delete_prim_path_children("/World/Looks")
# get content browser file
await content_browser_helper.navigate_to_async(mdl_path)
await ui_test.human_delay(10)
item = await content_browser_helper.get_treeview_item_async(os.path.basename(mdl_path))
self.assertFalse(item == None)
# get content browser treeview
content_treeview = ui_test.find("Content//Frame/**/TreeView[*].identifier=='content_browser_treeview'")
# select prims
await select_prims(to_select)
# right click content browser
await content_treeview.right_click(item.center)
# click on context menu item
await ui_test.select_context_menu("Bind material to selected prim(s)")
# use create material dialog
await material_test_helper.handle_create_material_dialog(mdl_path, mtl_name)
# verify item(s)
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == f"/World/Looks/{mtl_name}")
| 3,328 | Python | 40.098765 | 115 | 0.683894 |
omniverse-code/kit/exts/omni.ujitso.python/omni/ujitso/__init__.py | from ._ujitso import *
| 23 | Python | 10.999995 | 22 | 0.695652 |
omniverse-code/kit/exts/omni.ujitso.python/omni/ujitso/tests/test_bindings.py | # Copyright (c) 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.
#
import numpy as np
import omni.kit.test
from omni.ujitso import *
class TestBindings(omni.kit.test.AsyncTestCase):
"""Test bindings in this extension"""
async def test_operation_result(self):
"""validate binding of OperationResult"""
self.assertEqual(len(OperationResult.__members__), 11)
self.assertEqual(int(OperationResult.SUCCESS), 0)
self.assertEqual(int(OperationResult.FAILURE), 1)
self.assertEqual(int(OperationResult.OVERFLOW_ERROR), 2)
self.assertEqual(int(OperationResult.INVALIDHANDLE_ERROR), 3)
self.assertEqual(int(OperationResult.NOPROCESSOR_ERROR), 4)
self.assertEqual(int(OperationResult.NOTFOUND_ERROR), 5)
self.assertEqual(int(OperationResult.NOTBUILT_ERROR), 6)
self.assertEqual(int(OperationResult.INVALIDMETADATA_ERROR), 7)
self.assertEqual(int(OperationResult.OUTOFMEMORY_ERROR), 8)
self.assertEqual(int(OperationResult.DATAVALIDATION_ERROR), 10)
self.assertEqual(int(OperationResult.INTERNAL), 0xffff)
async def test_validation_type(self):
"""validate binding of ValidationType"""
self.assertEqual(len(ValidationType.__members__), 3)
self.assertEqual(int(ValidationType.MANDATORY), 0)
self.assertEqual(int(ValidationType.DEFERRED), 1)
self.assertEqual(int(ValidationType.NONE), 2)
async def test_match_result(self):
"""validate binding of MatchResult"""
self.assertEqual(len(MatchResult.__members__), 4)
self.assertEqual(int(MatchResult.FAILURE), 0)
self.assertEqual(int(MatchResult.LOWEST_PRIORITY), 1)
self.assertEqual(int(MatchResult.NORMAL_PRIORITY), 1000)
self.assertEqual(int(MatchResult.HIGHEST_PRIORITY), 2000)
async def test_global_key_token(self):
"""validate binding of GlobalKeyToken"""
self.assertEqual(len(IRegistry.GlobalKeyToken.__members__), 9)
self.assertEqual(int(IRegistry.PATH), 0)
self.assertEqual(int(IRegistry.VERSION), 1)
self.assertEqual(int(IRegistry.TIME), 2)
self.assertEqual(int(IRegistry.FLAGS), 3)
self.assertEqual(int(IRegistry.PARAM0), 4)
self.assertEqual(int(IRegistry.PARAM1), 5)
self.assertEqual(int(IRegistry.PARAM2), 6)
self.assertEqual(int(IRegistry.PARAM3), 7)
self.assertEqual(int(IRegistry.CUSTOM_START), 1 << 16)
self.assertEqual(int(IRegistry.GlobalKeyToken.PATH), 0)
self.assertEqual(int(IRegistry.GlobalKeyToken.VERSION), 1)
self.assertEqual(int(IRegistry.GlobalKeyToken.TIME), 2)
self.assertEqual(int(IRegistry.GlobalKeyToken.FLAGS), 3)
self.assertEqual(int(IRegistry.GlobalKeyToken.PARAM0), 4)
self.assertEqual(int(IRegistry.GlobalKeyToken.PARAM1), 5)
self.assertEqual(int(IRegistry.GlobalKeyToken.PARAM2), 6)
self.assertEqual(int(IRegistry.GlobalKeyToken.PARAM3), 7)
self.assertEqual(int(IRegistry.GlobalKeyToken.CUSTOM_START), 1 << 16)
async def test_retrieve_flags(self):
"""validate binding of RetrieveFlags"""
self.assertEqual(len(IDataStore.RetrieveFlags.__members__), 6)
self.assertEqual(int(IDataStore.EN_RETRIEVEFLAG_NONE), 0)
self.assertEqual(int(IDataStore.EN_RETRIEVEFLAG_SYNC), 1 << 0)
self.assertEqual(int(IDataStore.EN_RETRIEVEFLAG_SIZE_ONLY), 1 << 1)
self.assertEqual(int(IDataStore.EN_RETRIEVEFLAG_EXISTENCE_ONLY), 1 << 2)
self.assertEqual(int(IDataStore.EN_RETRIEVEFLAG_LOCAL), 1 << 3)
self.assertEqual(int(IDataStore.EN_RETRIEVEFLAG_CLUSTER), 1 << 4)
self.assertEqual(int(IDataStore.RetrieveFlags.EN_RETRIEVEFLAG_NONE), 0)
self.assertEqual(int(IDataStore.RetrieveFlags.EN_RETRIEVEFLAG_SYNC), 1 << 0)
self.assertEqual(int(IDataStore.RetrieveFlags.EN_RETRIEVEFLAG_SIZE_ONLY), 1 << 1)
self.assertEqual(int(IDataStore.RetrieveFlags.EN_RETRIEVEFLAG_EXISTENCE_ONLY), 1 << 2)
self.assertEqual(int(IDataStore.RetrieveFlags.EN_RETRIEVEFLAG_LOCAL), 1 << 3)
self.assertEqual(int(IDataStore.RetrieveFlags.EN_RETRIEVEFLAG_CLUSTER), 1 << 4)
async def test_store_flags(self):
"""validate binding of StoreFlags"""
self.assertEqual(len(IDataStore.StoreFlags.__members__), 10)
self.assertEqual(int(IDataStore.EN_STOREFLAG_DEFAULT), 0)
self.assertEqual(int(IDataStore.EN_STOREFLAG_NO_LOCAL), 1 << 0)
self.assertEqual(int(IDataStore.EN_STOREFLAG_LOCAL_INCONSISTENT), 1 << 1)
self.assertEqual(int(IDataStore.EN_STOREFLAG_NO_CLUSTER), 1 << 2)
self.assertEqual(int(IDataStore.EN_STOREFLAG_CLUSTER_INCONSISTENT), 1 << 3)
self.assertEqual(int(IDataStore.EN_STOREFLAG_NO_REMOTE), 1 << 4)
self.assertEqual(int(IDataStore.EN_STOREFLAG_REMOTE_INCONSISTENT), 1 << 5)
self.assertEqual(int(IDataStore.EN_STOREFLAG_PERSISTENCE_PRIORITY_LOW), 1 << 6)
self.assertEqual(int(IDataStore.EN_STOREFLAG_PERSISTENCE_PRIORITY_MEDIUM), 2 << 6)
self.assertEqual(int(IDataStore.EN_STOREFLAG_PERSISTENCE_PRIORITY_HIGH), 3 << 6)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_DEFAULT), 0)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_NO_LOCAL), 1 << 0)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_LOCAL_INCONSISTENT), 1 << 1)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_NO_CLUSTER), 1 << 2)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_CLUSTER_INCONSISTENT), 1 << 3)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_NO_REMOTE), 1 << 4)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_REMOTE_INCONSISTENT), 1 << 5)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_PERSISTENCE_PRIORITY_LOW), 1 << 6)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_PERSISTENCE_PRIORITY_MEDIUM), 2 << 6)
self.assertEqual(int(IDataStore.StoreFlags.EN_STOREFLAG_PERSISTENCE_PRIORITY_HIGH), 3 << 6)
async def test_request_handle(self):
"""validate binding of RequestHandle"""
# validate the default value
handle = RequestHandle()
self.assertEqual(handle.value, 0)
# only positive integer is accepted
valid_values = [1, 1<<64 - 1, 0]
invalid_values = [-1, -1.0, 1.0, 1<<64]
# validate setter with valid values
for val in valid_values:
handle.value = val
self.assertEqual(handle.value, val)
# validate setter with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
handle.value = val
# only positive integer is accepted
valid_indices = [1, 1<<32 - 1, 0]
# validate initialization with valid values
for val in valid_values:
handle = RequestHandle(val)
self.assertEqual(handle.value, val)
handle = RequestHandle(value = val)
self.assertEqual(handle.value, val)
# validate initialization with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
handle = RequestHandle(val)
with self.assertRaises(TypeError):
handle = RequestHandle(value = val)
async def test_key_token(self):
"""validate binding of KeyToken"""
# validate the default value
token = KeyToken()
self.assertEqual(token.value, 0)
# only positive integer is accepted
valid_values = [1, 1<<32 - 1, 0]
invalid_values = [-1, -1.0, 1.0, 1<<32]
# validate setter with valid values
for val in valid_values:
token.value = val
self.assertEqual(token.value, val)
# validate setter with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
token.value = val
# the value shouldn't change
self.assertEqual(token.value, valid_values[-1])
# validate initialization with valid values
for val in valid_values:
token = KeyToken(val)
self.assertEqual(token.value, val)
token = KeyToken(value = val)
self.assertEqual(token.value, val)
# validate initialization with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
token = KeyToken(val)
with self.assertRaises(TypeError):
token = KeyToken(value = val)
# validate the value of STATIC_STRING_HASH_MARKER
self.assertEqual(KeyToken.STATIC_STRING_HASH_MARKER, 0x80000000)
# can't set attribute
with self.assertRaises(AttributeError):
KeyToken.STATIC_STRING_HASH_MARKER = 0
# validate __eq__
for val in valid_values:
self.assertEqual(KeyToken(val), KeyToken(val))
self.assertNotEqual(KeyToken(val), KeyToken(2))
async def test_key_token_ex(self):
"""validate binding of KeyTokenEx"""
key_token_ex = KeyTokenEx(IRegistry.GlobalKeyToken.PATH)
self.assertEqual(key_token_ex.value, IRegistry.GlobalKeyToken.PATH)
key_token_ex = KeyTokenEx(IRegistry.PATH)
self.assertEqual(key_token_ex.value, IRegistry.PATH)
key_token_ex = KeyTokenEx("")
key_token_ex = KeyTokenEx("test")
key_token_ex = KeyTokenEx(KeyToken())
self.assertEqual(key_token_ex.value, 0)
valid_values = [0, 1, 1<<32 - 1]
for val in valid_values:
key_token_ex_a = KeyTokenEx(KeyToken(val))
self.assertEqual(key_token_ex_a.value, val)
key_token_ex_b = KeyTokenEx(KeyToken())
key_token_ex_b.value = val
self.assertEqual(key_token_ex_b.value, val)
self.assertTrue(key_token_ex_a == key_token_ex_b)
self.assertTrue(key_token_ex_b == key_token_ex_a)
self.assertFalse(key_token_ex_a != key_token_ex_b)
self.assertFalse(key_token_ex_b != key_token_ex_a)
key_token = KeyToken(val)
self.assertTrue(key_token_ex_a == key_token)
self.assertTrue(key_token == key_token_ex_a)
self.assertFalse(key_token_ex_a != key_token)
self.assertFalse(key_token != key_token_ex_a)
key_token_100 = KeyToken(100)
self.assertFalse(key_token_ex_a == key_token_100)
self.assertFalse(key_token_100 == key_token_ex_a)
self.assertTrue(key_token_ex_a != key_token_100)
self.assertTrue(key_token_100 != key_token_ex_a)
key_token_ex_100 = KeyTokenEx(key_token_100)
self.assertFalse(key_token_ex_a == key_token_ex_100)
self.assertFalse(key_token_ex_100 == key_token_ex_a)
self.assertTrue(key_token_ex_a != key_token_ex_100)
self.assertTrue(key_token_ex_100 != key_token_ex_a)
with self.assertRaises(TypeError):
key_token_ex = KeyTokenEx()
with self.assertRaises(TypeError):
key_token_ex = KeyTokenEx(0)
# This following line will end up calling C++ KeyTokenEx::KeyTokenEx(const char* str) with `str` being nullptr.
# It will lead to crash but it is a problem of the C++ implementation rather than the Python binding code.
#
# key_token_ex = KeyTokenEx(None)
async def test_dynamic_request(self):
"""validate binding of DynamicRequest"""
# validate the default constructor
dynamic_request = DynamicRequest()
self.assertEqual(dynamic_request.size(), 0)
request = dynamic_request.get_request()
self.assertEqual(request.type.count, 0)
self.assertEqual(request.type.keys.tolist(), [])
self.assertEqual(request.type.types.tolist(), [])
self.assertEqual(request.tokenValues, b'')
# validate addition of different data types
buf = [12, 13, 14]
buf_token_type = UjitsoUtils.make_uint8_request_token_type()
buf_token_type.size = len(buf)
key_value_pairs = [
(KeyTokenEx("void"),),
(KeyTokenEx("key token"), KeyToken(1)),
(KeyTokenEx("8-bit unsigned interger"), 2),
(KeyTokenEx("16-bit signed integer"), 3),
(KeyTokenEx("16-bit unsigned integer"), 4),
(KeyTokenEx("32-bit signed integer"), 5),
(KeyTokenEx("32-bit unsigned integer"), 6),
(KeyTokenEx("64-bit signed integer"), 7),
(KeyTokenEx("64-bit unsigned integer"), 8),
(KeyTokenEx("double precision floating point"), 9.0),
(KeyTokenEx("single precision floating point"), 10.0),
(KeyTokenEx("string"), "11"),
(KeyTokenEx("buffer"), buf_token_type, buf)]
token_type_size_list = [0, 4, 1, 2, 2, 4, 4, 8, 8, 8, 4, 3, len(buf)]
self.assertEqual(len(key_value_pairs), len(token_type_size_list))
dynamic_request.reserve(len(key_value_pairs))
counter = 0
index = dynamic_request.add(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_key_token(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_uint8(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_int16(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_uint16(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_int(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_uint(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_int64(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_uint64(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_double(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_float(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_string(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
counter += 1
index = dynamic_request.add_buffer(*(key_value_pairs[counter]))
self.assertEqual(index, counter)
self.assertEqual(dynamic_request.size(), counter + 1)
for i in range(dynamic_request.size()):
key_value_pair = key_value_pairs[i]
token_type_size = token_type_size_list[i]
key = key_value_pair[0]
found, request_token_type = dynamic_request.find_key(key)
self.assertTrue(found)
self.assertEqual(request_token_type.size, token_type_size)
self.assertEqual(dynamic_request.get_key(i), key)
self.assertEqual(dynamic_request.get_type(i), request_token_type)
# validate reading of existent requests through matching template.
counter = 1
found, value = dynamic_request.get_as_key_token(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_uint8(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_int16(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_uint16(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_int32(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_uint32(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_int64(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_uint64(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_double(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_float(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
counter += 1
found, value = dynamic_request.get_as_string(key_value_pairs[counter][0])
self.assertTrue(found)
self.assertEqual(value, key_value_pairs[counter][1])
# validate reading of an existent request through mismatching template.
found, value = dynamic_request.get_as_uint8(key_value_pairs[counter][0])
self.assertFalse(found)
self.assertEqual(value, 0)
found, value = dynamic_request.get_as_uint8(key_value_pairs[0][0])
self.assertFalse(found)
self.assertEqual(value, 0)
# validate reading of an nonexistent request.
nonexistent_key_token = KeyTokenEx("nonexistent")
found, value = dynamic_request.get_as_key_token(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, KeyToken())
found, value = dynamic_request.get_as_uint8(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, 0)
found, value = dynamic_request.get_as_int16(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, 0)
found, value = dynamic_request.get_as_uint16(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, 0)
found, value = dynamic_request.get_as_int32(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, 0)
found, value = dynamic_request.get_as_uint32(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, 0)
found, value = dynamic_request.get_as_int64(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, 0)
found, value = dynamic_request.get_as_uint64(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, 0)
found, value = dynamic_request.get_as_double(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, 0.0)
found, value = dynamic_request.get_as_float(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, 0.0)
found, value = dynamic_request.get_as_string(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(value, None)
# validate the constructor with arguments
new_dynamic_request = DynamicRequest(Request())
self.assertEqual(new_dynamic_request.size(), 0)
request = new_dynamic_request.get_request()
self.assertEqual(request.type.count, 0)
self.assertEqual(request.type.keys.tolist(), [])
self.assertEqual(request.type.types.tolist(), [])
self.assertEqual(request.tokenValues, b'')
# validate copying of nonexistent requests between DynamicRequest instances
found = new_dynamic_request.copy(nonexistent_key_token, dynamic_request)
self.assertFalse(found)
self.assertEqual(new_dynamic_request.size(), 0)
# validate copying of existent requests between DynamicRequest instances
existent_key_token = KeyTokenEx("8-bit unsigned interger")
found = new_dynamic_request.copy(existent_key_token, dynamic_request)
self.assertTrue(found)
self.assertEqual(new_dynamic_request.size(), 1)
# validate key replacement of a nonexistent request
new_key_token = KeyTokenEx("unsigned char")
found = new_dynamic_request.replace_key(nonexistent_key_token, new_key_token)
self.assertFalse(found)
# validate key replacement of an existent request
found = new_dynamic_request.replace_key(existent_key_token, new_key_token)
self.assertTrue(found)
found, value = new_dynamic_request.get_as_uint8(new_key_token)
self.assertTrue(found)
self.assertEqual(value, 2)
# validate value replacement
found = new_dynamic_request.replace_value_uint8(new_key_token, 100)
self.assertTrue(found)
# validate removal of a nonexistent request
found = new_dynamic_request.remove_key(nonexistent_key_token)
self.assertFalse(found)
self.assertEqual(new_dynamic_request.size(), 1)
# validate removal of an existent request
found = new_dynamic_request.remove_key(new_key_token)
self.assertTrue(found)
self.assertEqual(new_dynamic_request.size(), 0)
async def test_request_token_type(self):
"""validate binding of RequestTokenType"""
# validate the default value
request_token_type = RequestTokenType()
self.assertEqual(request_token_type.size, 0)
self.assertEqual(request_token_type.typeNameHash, 0)
# only positive integer is accepted
valid_values = [1, 1<<32 - 1, 0]
invalid_values = [-1, -1.0, 1.0, 1<<32]
# validate setter with valid values
for val in valid_values:
request_token_type.size = val
self.assertEqual(request_token_type.size, val)
request_token_type.typeNameHash = val
self.assertEqual(request_token_type.typeNameHash, val)
# validate setter with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
request_token_type.size = val
with self.assertRaises(TypeError):
request_token_type.typeNameHash = val
# the value shouldn't change
self.assertEqual(request_token_type.size, valid_values[-1])
self.assertEqual(request_token_type.typeNameHash, valid_values[-1])
# validate initialization with valid values
for val in valid_values:
request_token_type = RequestTokenType(val, val)
self.assertEqual(request_token_type.size, val)
self.assertEqual(request_token_type.typeNameHash, val)
request_token_type = RequestTokenType(size = val, type_name_hash= val)
self.assertEqual(request_token_type.size, val)
self.assertEqual(request_token_type.typeNameHash, val)
# validate initialization with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
request_token_type = KeyToken(val, val)
with self.assertRaises(TypeError):
request_token_type = KeyToken(value = val, type_name_hash = val)
async def test_make_request_token_type(self):
"""validate bindings of template function makeRequestTokenType()"""
request_token_type = UjitsoUtils.make_key_token_request_token_type()
self.assertEqual(request_token_type.size, 4)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_uint8_request_token_type()
self.assertEqual(request_token_type.size, 1)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_int16_request_token_type()
self.assertEqual(request_token_type.size, 2)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_uint16_request_token_type()
self.assertEqual(request_token_type.size, 2)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_int32_request_token_type()
self.assertEqual(request_token_type.size, 4)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_uint32_request_token_type()
self.assertEqual(request_token_type.size, 4)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_int64_request_token_type()
self.assertEqual(request_token_type.size, 8)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_uint64_request_token_type()
self.assertEqual(request_token_type.size, 8)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_double_request_token_type()
self.assertEqual(request_token_type.size, 8)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_float_request_token_type()
self.assertEqual(request_token_type.size, 4)
self.assertNotEqual(request_token_type.typeNameHash, 0)
request_token_type = UjitsoUtils.make_void_request_token_type()
self.assertEqual(request_token_type.size, 0)
self.assertEqual(request_token_type.typeNameHash, 0)
async def test_get_request_value(self):
"""validate bindings of template function getRequestValue()"""
# validate whether these functions are available in UjitsoUtils.
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_key_token"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_uint8"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_int16"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_uint16"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_int"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_uint"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_int64"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_uint64"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_double"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_float"))
self.assertTrue(hasattr(UjitsoUtils, "get_request_value_string"))
async def test_request_type(self):
"""validate binding of RequestType"""
# validate the default constructor
request_type = RequestType()
self.assertEqual(request_type.count, 0)
self.assertEqual(request_type.keys.tolist(), [])
self.assertEqual(request_type.types.tolist(), [])
# can't set attribute
with self.assertRaises(AttributeError):
request_type.count = 1
with self.assertRaises(AttributeError):
request_type.keys = []
with self.assertRaises(AttributeError):
request_type.types = []
valid_args_list = [
([], []),
([(0,), (1,), (2,)], [(1, 2), (11, 12), (21, 22)]),
]
for keys, types in valid_args_list:
count = len(keys)
self.assertEqual(count, len(types))
request_type = RequestType(keys, types)
self.assertEqual(request_type.count, count)
self.assertEqual(request_type.keys.tolist(), keys)
self.assertEqual(request_type.types.tolist(), types)
# The array size of keys and types doesn't match
with self.assertRaises(ValueError):
request_type = RequestType([(0,), (1,), (2,)], [])
async def test_request_filter(self):
"""validate binding of RequestFilter"""
# validate the default constructor
request_filter = RequestFilter()
self.assertEqual(request_filter.count, 0)
self.assertEqual(request_filter.keys.tolist(), [])
# can't set attribute
with self.assertRaises(AttributeError):
request_filter.count = 1
with self.assertRaises(AttributeError):
request_filter.keys = []
valid_args_list = [
[],
[(0,), (1,), (2,)],
]
for keys in valid_args_list:
request_filter = RequestFilter(keys)
self.assertEqual(request_filter.count, len(keys))
self.assertEqual(request_filter.keys.tolist(), keys)
async def test_request(self):
"""validate binding of Request"""
# validate the default constructor
request = Request()
self.assertEqual(request.type.count, 0)
self.assertEqual(request.type.keys.tolist(), [])
self.assertEqual(request.type.types.tolist(), [])
self.assertEqual(request.tokenValues, b'')
# can't set attribute
with self.assertRaises(AttributeError):
request.type = RequestType()
with self.assertRaises(AttributeError):
request.tokenValues = b''
request = Request(RequestType(), b'')
self.assertEqual(request.type.count, 0)
self.assertEqual(request.type.keys.tolist(), [])
self.assertEqual(request.type.types.tolist(), [])
self.assertEqual(request.tokenValues, b'')
# validate non-default arguments
keys = [(0,), (1,), (2,)]
types = [(1, 2), (2, 12), (3, 22)]
request_type = RequestType(keys, types)
token_values = b'\x01\x02\x03\x04\x05\x06'
request_size = sum([t[0] for t in types])
self.assertEqual(request_size, len(token_values))
request = Request(request_type, token_values)
self.assertEqual(request.type.count, 3)
self.assertEqual(request.type.keys.tolist(), keys)
self.assertEqual(request.type.types.tolist(), types)
self.assertEqual(request.tokenValues, token_values)
async def test_agent(self):
"""validate binding of Agent"""
with self.assertRaises(TypeError):
agent = Agent()
async def test_request_callback_data(self):
"""validate binding of RequestCallbackData"""
# validate the default constructor
request_callback_data = RequestCallbackData()
self.assertEqual(request_callback_data.callbackContext0, None)
self.assertEqual(request_callback_data.callbackContext1, None)
# can't read and write the callback attribute
with self.assertRaises(AttributeError):
callback = request_callback_data.callback
with self.assertRaises(AttributeError):
request_callback_data.callback = None
class _Context:
def __init__(self, name):
self.name = name
def print_name(self):
print(self.name)
def _callback(callback_context0, callback_context1, request_handle, request_index, operation_result):
callback_context0.print_name()
callback_context1.print_name()
context0 = _Context("context0")
context1 = _Context("context1")
request_callback_data = RequestCallbackData(_callback, context0, context1)
self.assertEqual(request_callback_data.callbackContext0, context0)
self.assertEqual(request_callback_data.callbackContext1, context1)
async def test_external_storage(self):
"""validate binding of ExternalStorage"""
values = list(range(4))
external_storage = ExternalStorage(values)
self.assertEqual(external_storage.values.tolist(), values)
external_storage = ExternalStorage(tuple(values))
self.assertEqual(external_storage.values.tolist(), values)
values = list(range(100, 104))
external_storage.values = values
self.assertEqual(external_storage.values.tolist(), values)
external_storage.values = tuple(values)
self.assertEqual(external_storage.values.tolist(), values)
with self.assertRaises(TypeError):
external_storage.values = None
with self.assertRaises(ValueError):
external_storage.values = list(range(3))
with self.assertRaises(ValueError):
external_storage.values = list(range(5))
with self.assertRaises(TypeError):
external_storage = ExternalStorage()
with self.assertRaises(TypeError):
external_storage = ExternalStorage(*values)
with self.assertRaises(ValueError):
external_storage = ExternalStorage(list(range(3)))
with self.assertRaises(ValueError):
external_storage = ExternalStorage(list(range(5)))
async def test_service_interface(self):
"""validate binding of IService"""
service_interface = acquire_service_interface()
self.assertIsNotNone(service_interface)
release_service_interface(service_interface)
async def test_local_data_store_interface(self):
""" validate binding of ILocalDataStore"""
local_data_store_interface = acquire_local_data_store_interface()
self.assertIsNotNone(local_data_store_interface)
data_store = local_data_store_interface.create("test", 1024)
self.assertIsNotNone(data_store)
local_data_store_interface.destroy(data_store)
release_local_data_store_interface(local_data_store_interface)
async def test_nucleus_data_store_interface(self):
""" validate binding of INucleusDataStore"""
nucleus_data_store_interface = acquire_nucleus_data_store_interface()
self.assertIsNotNone(nucleus_data_store_interface)
data_store = nucleus_data_store_interface.create("test", "test", False)
self.assertIsNotNone(data_store)
nucleus_data_store_interface.destroy(data_store)
release_nucleus_data_store_interface(nucleus_data_store_interface)
async def test_processor_information(self):
""" validate binding of ProcessorInformation"""
valid_args_list = [(None, 0, 0), ("", 0, 0), ("test1", 0, 0), ("test2", 1, 1)]
for name, version, remote_execution_batch_hint in valid_args_list:
processor_information = ProcessorInformation(name, version, remote_execution_batch_hint)
self.assertEqual(processor_information.name, name)
self.assertEqual(processor_information.version, version)
self.assertEqual(processor_information.remoteExecutionBatchHint, remote_execution_batch_hint)
with self.assertRaises(TypeError):
processor_information = ProcessorInformation()
invalid_args_list = [("test1", -1, 0), ("test2", 0, -1), ("test3", 0.5, 0), ("test4", 0, 0.5)]
for name, version, remote_execution_batch_hint in invalid_args_list:
with self.assertRaises(TypeError):
processor_information = ProcessorInformation(name, version, remote_execution_batch_hint)
processor_information = ProcessorInformation(None, 0, 0)
for name, version, remote_execution_batch_hint in valid_args_list:
processor_information.name = name
processor_information.version = version
processor_information.remoteExecutionBatchHint = remote_execution_batch_hint
self.assertEqual(processor_information.name, name)
self.assertEqual(processor_information.version, version)
self.assertEqual(processor_information.remoteExecutionBatchHint, remote_execution_batch_hint)
processor_information = ProcessorInformation(None, 0, 0)
for name, version, remote_execution_batch_hint in invalid_args_list:
with self.assertRaises(TypeError):
processor_information.name = name
processor_information.version = version
processor_information.remoteExecutionBatchHint = remote_execution_batch_hint
async def test_processor(self):
""" validate binding of Processor"""
processor = Processor(None, None, None, None)
# It is fine to intialize with functions with mismatched signature, exception will be raised later when triggering these callbacks.
processor = Processor(lambda : None, lambda : None, lambda : None, lambda : None)
with self.assertRaises(TypeError):
processor = Processor()
with self.assertRaises(TypeError):
processor = Processor(None, None, None)
with self.assertRaises(TypeError):
processor = Processor("", "", "", "")
with self.assertRaises(TypeError):
processor = Processor(0, 0, 0, 0)
async def test_match_context(self):
""" validate binding of MatchContext"""
with self.assertRaises(TypeError):
match_context = MatchContext()
async def test_dependency_context(self):
""" validate binding of DependencyContext"""
with self.assertRaises(TypeError):
dependency_context = DependencyContext()
async def test_build_context(self):
""" validate binding of BuildContext"""
with self.assertRaises(TypeError):
build_context = BuildContext()
async def test_dependency_handle(self):
"""validate binding of DependencyHandle"""
# validate the default value
handle = DependencyHandle()
self.assertEqual(handle.value, 0)
# only positive integer is accepted
valid_values = [1, 1<<64 - 1, 0]
invalid_values = [-1, -1.0, 1.0, 1<<64]
# validate setter with valid values
for val in valid_values:
handle.value = val
self.assertEqual(handle.value, val)
# validate setter with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
handle.value = val
# the value shouldn't change
self.assertEqual(handle.value, valid_values[-1])
# validate initialization with valid values
for val in valid_values:
handle = DependencyHandle(val)
self.assertEqual(handle.value, val)
handle = DependencyHandle(value = val)
self.assertEqual(handle.value, val)
# validate initialization with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
handle = DependencyHandle(val)
with self.assertRaises(TypeError):
handle = DependencyHandle(value = val)
async def test_build_handle(self):
"""validate binding of BuildHandle"""
# validate the default value
handle = BuildHandle()
self.assertEqual(handle.value, 0)
# only positive integer is accepted
valid_values = [1, 1<<64 - 1, 0]
invalid_values = [-1, -1.0, 1.0, 1<<64]
# validate setter with valid values
for val in valid_values:
handle.value = val
self.assertEqual(handle.value, val)
# validate setter with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
handle.value = val
# the value shouldn't change
self.assertEqual(handle.value, valid_values[-1])
# validate initialization with valid values
for val in valid_values:
handle = BuildHandle(val)
self.assertEqual(handle.value, val)
handle = BuildHandle(value = val)
self.assertEqual(handle.value, val)
# validate initialization with invalid values
for val in invalid_values:
with self.assertRaises(TypeError):
handle = BuildHandle(val)
with self.assertRaises(TypeError):
handle = BuildHandle(value = val)
async def test_dependency_job(self):
""" validate binding of DependencyJob"""
# validate default values
dependency_job = DependencyJob()
request = dependency_job.request
self.assertEqual(request.type.count, 0)
self.assertEqual(request.type.keys.tolist(), [])
self.assertEqual(request.type.types.tolist(), [])
self.assertEqual(request.tokenValues, b'')
keys = [(0,), (1,), (2,)]
types = [(1, 2), (2, 12), (3, 22)]
request_type = RequestType(keys, types)
token_values = b'\x11\x12\x13\x14\x15\x16'
request_size = sum([t[0] for t in types])
self.assertEqual(request_size, len(token_values))
# validate setter and getter
dependency_job.request = Request(request_type, token_values)
request = dependency_job.request
self.assertEqual(request.type.count, len(keys))
self.assertEqual(request.type.keys.tolist(), keys)
self.assertEqual(request.type.types.tolist(), types)
self.assertEqual(request.tokenValues, token_values)
# validate resetting of requests
dependency_job.request = Request()
request = dependency_job.request
self.assertEqual(request.type.count, 0)
self.assertEqual(request.type.keys.tolist(), [])
self.assertEqual(request.type.types.tolist(), [])
self.assertEqual(request.tokenValues, b'')
with self.assertRaises(TypeError):
dependency_job.request = None
async def test_build_job(self):
""" validate binding of BuildJob"""
# validate default values
build_job = BuildJob()
request = build_job.request
self.assertEqual(request.type.count, 0)
self.assertEqual(request.type.keys.tolist(), [])
self.assertEqual(request.type.types.tolist(), [])
self.assertEqual(request.tokenValues, b'')
keys = [(0,), (1,), (2,)]
types = [(1, 2), (2, 12), (3, 22)]
request_type = RequestType(keys, types)
token_values = b'\x11\x12\x13\x14\x15\x16'
request_size = sum([t[0] for t in types])
self.assertEqual(request_size, len(token_values))
# validate setter and getter
request = Request(request_type, token_values)
build_job.request = request
request = build_job.request
self.assertEqual(request.type.count, len(keys))
self.assertEqual(request.type.keys.tolist(), keys)
self.assertEqual(request.type.types.tolist(), types)
self.assertEqual(request.tokenValues, token_values)
# validate resetting of requests
build_job.request = Request()
request = build_job.request
self.assertEqual(request.type.count, 0)
self.assertEqual(request.type.keys.tolist(), [])
self.assertEqual(request.type.types.tolist(), [])
self.assertEqual(request.tokenValues, b'')
with self.assertRaises(TypeError):
build_job.request = None
async def test_data_grid(self):
""" validate binding of DataGrid"""
with self.assertRaises(TypeError):
data_grid = DataGrid()
async def test_data_grid_interface(self):
"""validate binding of IDataGrid"""
data_grid_interface = acquire_data_grid_interface()
self.assertIsNotNone(data_grid_interface)
data_grid = data_grid_interface.create_data_grid()
self.assertIsNotNone(data_grid)
self.assertIsNotNone(data_grid.iface)
# can't set attribute
with self.assertRaises(AttributeError):
data_grid.iface = None
data_grid_interface.destroy_data_grid(data_grid)
release_data_grid_interface(data_grid_interface)
async def test_in_progress_factory_interface(self):
""" validate binding of IInProgressFactory"""
factory_interface = acquire_in_progress_factory_interface()
self.assertIsNotNone(factory_interface)
task_agent = factory_interface.create_agent()
self.assertIsNotNone(task_agent)
task_service = factory_interface.get_service(task_agent)
self.assertIsNotNone(task_service)
task_service.destroy()
task_agent.destroy()
release_in_progress_factory_interface(factory_interface)
async def test_tcp_factory_interface(self):
""" validate binding of ITCPFactory"""
factory_interface = acquire_tcp_factory_interface()
self.assertIsNotNone(factory_interface)
port = 1113
task_service = factory_interface.create_service(port)
self.assertIsNotNone(task_service)
address_and_port = ("127.0.0.1", port)
addresses = [address_and_port]
task_agent = factory_interface.create_agent(addresses)
self.assertIsNotNone(task_agent)
service_ip = factory_interface.get_service_ip(task_service)
self.assertIsNotNone(service_ip)
self.assertTrue(isinstance(service_ip, str))
task_service.destroy()
task_agent.destroy()
release_tcp_factory_interface(factory_interface)
async def test_http_factory_interface(self):
""" validate binding of IHTTPFactory"""
factory_interface = acquire_http_factory_interface()
self.assertIsNotNone(factory_interface)
task_agent = factory_interface.create_agent("test")
self.assertIsNotNone(task_agent)
task_service = factory_interface.create_service()
self.assertIsNotNone(task_service)
result = factory_interface.run_http_jobs(task_service, "desc", "store_path")
self.assertIsNotNone(result)
self.assertTrue(isinstance(result, str))
task_service.destroy()
task_agent.destroy()
release_http_factory_interface(factory_interface)
| 47,293 | Python | 40.053819 | 139 | 0.646058 |
omniverse-code/kit/exts/omni.ujitso.python/omni/ujitso/tests/__init__.py | scan_for_test_modules = True
"""The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
| 142 | Python | 46.666651 | 112 | 0.78169 |
omniverse-code/kit/exts/omni.ujitso.python/omni/ujitso/tests/test_UJITSO.py | # Copyright (c) 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.
#
import numpy as np
from omni.kit.test import AsyncTestCase
from omni.ujitso import *
kTokenTypeUSDPath = KeyToken(11)
kTokenTypeRTXPackedMeshLODs = KeyToken(12)
kTokenTypeRTXPackedMeshLOD = KeyToken(13)
kTokenTypeMeshLOD = KeyToken(14)
kTokenTypeTriangulatedMesh = KeyToken(15)
kTokenTypeMesh = KeyToken(16)
kTokenMeshReduceFactor = KeyToken(17)
class ProcessorImpl(Processor):
def __init__(self, agent, key_token, get_info_impl, match_impl, gather_dependencies_impl, build_impl):
super().__init__(get_info_impl, match_impl, gather_dependencies_impl, build_impl)
self._agent = agent
request_filter = RequestFilter([(key_token.value,)])
agent.registry.register_processor(self, request_filter)
def __del__(self):
self._agent.registry.unregister_processor(self)
@staticmethod
def _match_impl(match_context, request_array):
return OperationResult.SUCCESS, MatchResult.NORMAL_PRIORITY
@staticmethod
def _build_impl(build_context, build_job, build_handle):
return OperationResult.SUCCESS
class ProcessorRTXPackedMeshLODs(ProcessorImpl):
def __init__(self, agent, key_token):
super().__init__(agent, key_token, ProcessorRTXPackedMeshLODs._get_info_impl, ProcessorRTXPackedMeshLODs._match_impl, ProcessorRTXPackedMeshLODs._gather_dependencies_impl, ProcessorRTXPackedMeshLODs._build_impl)
@staticmethod
def _get_info_impl(processor):
return OperationResult.SUCCESS, ProcessorInformation("ProcessorRTXPackedMeshLODs", 1, 1)
@staticmethod
def _gather_dependencies_impl(dependency_context, dependency_job, dependency_handle):
dynamic_request = DynamicRequest(dependency_job.request)
dynamic_request.replace_key(KeyTokenEx(kTokenTypeRTXPackedMeshLODs), KeyTokenEx(kTokenTypeRTXPackedMeshLOD))
dynamic_request.add_float(KeyTokenEx(kTokenMeshReduceFactor), 1.0)
dependency_context.agent.service.add_dependency(dependency_context.agent, dependency_handle, dynamic_request.get_request())
dynamic_request.replace_value_float(KeyTokenEx(kTokenMeshReduceFactor), 0.3)
dependency_context.agent.service.add_dependency(dependency_context.agent, dependency_handle, dynamic_request.get_request())
dynamic_request.replace_value_float(KeyTokenEx(kTokenMeshReduceFactor), 0.1)
dependency_context.agent.service.add_dependency(dependency_context.agent, dependency_handle, dynamic_request.get_request())
return OperationResult.SUCCESS
class ProcessorRTXPackedMeshLOD(ProcessorImpl):
def __init__(self, agent, key_token):
super().__init__(agent, key_token, ProcessorRTXPackedMeshLOD._get_info_impl, ProcessorRTXPackedMeshLOD._match_impl, ProcessorRTXPackedMeshLOD._gather_dependencies_impl, ProcessorRTXPackedMeshLOD._build_impl)
@staticmethod
def _get_info_impl(processor):
return OperationResult.SUCCESS, ProcessorInformation("ProcessorRTXPackedMeshLOD", 1, 1)
@staticmethod
def _gather_dependencies_impl(dependency_context, dependency_job, dependency_handle):
dynamic_request = DynamicRequest(dependency_job.request)
dynamic_request.replace_key(KeyTokenEx(kTokenTypeRTXPackedMeshLOD), KeyTokenEx(kTokenTypeMeshLOD))
dependency_context.agent.service.add_dependency(dependency_context.agent, dependency_handle, dynamic_request.get_request())
return OperationResult.SUCCESS
class ProcessorMeshLOD(ProcessorImpl):
def __init__(self, agent, key_token):
super().__init__(agent, key_token, ProcessorMeshLOD._get_info_impl, ProcessorMeshLOD._match_impl, ProcessorMeshLOD._gather_dependencies_impl, ProcessorMeshLOD._build_impl)
@staticmethod
def _get_info_impl(processor):
return OperationResult.SUCCESS, ProcessorInformation("ProcessorMeshLOD", 1, 1)
@staticmethod
def _gather_dependencies_impl(dependency_context, dependency_job, dependency_handle):
dynamic_request = DynamicRequest(dependency_job.request)
dynamic_request.replace_key(KeyTokenEx(kTokenTypeMeshLOD), KeyTokenEx(kTokenTypeTriangulatedMesh))
dynamic_request.remove_key(KeyTokenEx(kTokenMeshReduceFactor))
dependency_context.agent.service.add_dependency(dependency_context.agent, dependency_handle, dynamic_request.get_request())
return OperationResult.SUCCESS
class ProcessorTriangulatedMesh(ProcessorImpl):
def __init__(self, agent, key_token):
super().__init__(agent, key_token, ProcessorTriangulatedMesh._get_info_impl, ProcessorTriangulatedMesh._match_impl, ProcessorTriangulatedMesh._gather_dependencies_impl, ProcessorTriangulatedMesh._build_impl)
@staticmethod
def _get_info_impl(processor):
return OperationResult.SUCCESS, ProcessorInformation("ProcessorTriangulatedMesh", 1, 1)
@staticmethod
def _gather_dependencies_impl(dependency_context, dependency_job, dependency_handle):
dynamic_request = DynamicRequest(dependency_job.request)
dynamic_request.replace_key(KeyTokenEx(kTokenTypeTriangulatedMesh), KeyTokenEx(kTokenTypeMesh))
dependency_context.agent.service.add_dependency(dependency_context.agent, dependency_handle, dynamic_request.get_request())
return OperationResult.SUCCESS
class ProcessorMesh(ProcessorImpl):
def __init__(self, agent, key_token):
super().__init__(agent, key_token, ProcessorMesh._get_info_impl, ProcessorMesh._match_impl, ProcessorMesh._gather_dependencies_impl, ProcessorMesh._build_impl)
@staticmethod
def _get_info_impl(processor):
return OperationResult.SUCCESS, ProcessorInformation("ProcessorMesh", 1, 1)
@staticmethod
def _gather_dependencies_impl(dependency_context, dependency_job, dependency_handle):
return OperationResult.SUCCESS
class TestUJITSO(AsyncTestCase):
"""Test UJITSO (ported from TestUJITSO.cpp)"""
async def test_ujitso_agent(self):
"""UJITSO agent test"""
self._test_UJITSO()
def _test_UJITSO(self, task_agent = None, task_service = None):
factory_interface = acquire_factory_interface()
self.assertIsNotNone(factory_interface)
data_grid_interface = acquire_data_grid_interface()
self.assertIsNotNone(data_grid_interface)
data_grid = data_grid_interface.create_data_grid()
self.assertIsNotNone(data_grid)
local_data_store_interface = acquire_local_data_store_interface()
self.assertIsNotNone(local_data_store_interface)
data_store = local_data_store_interface.create(None, 0)
self.assertIsNotNone(data_store)
agent = factory_interface.create_agent(data_grid, data_store, task_agent, task_service, AgentConfigFlags.Default)
self.assertIsNotNone(agent)
self.assertIsNotNone(agent.agent)
self._test_registry(agent)
self._test_request(agent)
self._test_lod_mockup(agent)
self._test_build(agent, data_grid, data_store)
factory_interface.destroy_agent(agent)
data_grid_interface.destroy_data_grid(data_grid)
local_data_store_interface.destroy(data_store)
release_factory_interface(factory_interface)
release_local_data_store_interface(local_data_store_interface)
release_data_grid_interface(data_grid_interface)
def _test_registry(self, agent):
string1 = KeyTokenEx("Test1")
string2 = KeyTokenEx("Test2")
string3 = KeyTokenEx("Test1")
self.assertTrue(string1 != string2)
self.assertTrue(string2 != string3)
self.assertTrue(string1 == string3)
def _test_request(self, agent):
agent_interface = agent.agent
keys = [(123,)]
key_token_rtype = UjitsoUtils.make_key_token_request_token_type()
types = [(key_token_rtype.size, key_token_rtype.typeNameHash)]
request_type = RequestType(keys, types)
key_token_dtype = np.dtype([('value', np.uint32)])
key_token_value = [1]
request_values = np.array(key_token_value, key_token_dtype).tobytes()
request = Request(request_type, request_values)
request_callback_data = RequestCallbackData()
operation_result, request_handle = agent_interface.request_build(agent, request, request_callback_data)
self.assertEqual(operation_result, OperationResult.SUCCESS)
self.assertIsNotNone(request_handle)
self.assertNotEqual(request_handle.value, 0)
operation_result = agent_interface.wait_all(agent, TIME_OUT_INFINITE)
self.assertEqual(operation_result, OperationResult.SUCCESS)
operation_result, result_handle = agent_interface.get_request_result(request_handle)
self.assertEqual(operation_result, OperationResult.NOPROCESSOR_ERROR)
operation_result = agent_interface.destroy_request(request_handle)
self.assertEqual(operation_result, OperationResult.SUCCESS)
operation_result = agent_interface.destroy_request(request_handle)
self.assertEqual(operation_result, OperationResult.INVALIDHANDLE_ERROR)
operation_result, result_handle = agent_interface.get_request_result(request_handle)
self.assertEqual(operation_result, OperationResult.INVALIDHANDLE_ERROR)
def _test_lod_mockup(self, agent):
agent_interface = agent.agent
procPackedLODs = ProcessorRTXPackedMeshLODs(agent, kTokenTypeRTXPackedMeshLODs)
procPackedLOD = ProcessorRTXPackedMeshLOD(agent, kTokenTypeRTXPackedMeshLOD)
procMeshLOD = ProcessorMeshLOD(agent, kTokenTypeMeshLOD)
procTriangulatedMesh = ProcessorTriangulatedMesh(agent, kTokenTypeTriangulatedMesh)
procMesh = ProcessorMesh(agent, kTokenTypeMesh)
dynamic_request = DynamicRequest()
dynamic_request.add(KeyTokenEx(kTokenTypeRTXPackedMeshLODs))
dynamic_request.add_string(KeyTokenEx(kTokenTypeUSDPath), "/Meshes/TestMesh")
request = dynamic_request.get_request()
self.assertIsNotNone(request)
request_callback_data = RequestCallbackData()
operation_result, request_handle = agent_interface.request_build(agent, request, request_callback_data)
self.assertEqual(operation_result, OperationResult.SUCCESS)
self.assertIsNotNone(request_handle)
self.assertNotEqual(request_handle.value, 0)
operation_result = agent_interface.wait_all(agent, TIME_OUT_INFINITE)
self.assertEqual(operation_result, OperationResult.SUCCESS)
agent_interface.destroy_request(request_handle)
def _test_build(self, agent, data_grid, data_store):
class ProcessorBuild(ProcessorImpl):
def __init__(self, agent, key_token):
super().__init__(agent, key_token, ProcessorBuild._get_info_impl, ProcessorBuild._match_impl, ProcessorBuild._gather_dependencies_impl, ProcessorBuild._build_impl)
@staticmethod
def _get_info_impl(processor):
return OperationResult.SUCCESS, ProcessorInformation("ProcessorBuild", 1, 1)
@staticmethod
def _gather_dependencies_impl(dependency_context, dependency_job, dependency_handle):
agent = dependency_context.agent
service = agent.service
dynamic_request = DynamicRequest(dependency_job.request)
service.add_request_tuple_input(agent, dependency_handle, dynamic_request.get_request(), False, False)
service.set_storage_context(agent, dependency_handle, "TestStorageContext")
return OperationResult.SUCCESS
@staticmethod
def _build_impl(build_context, build_job, build_handle):
agent = build_context.agent
string_value = UjitsoUtils.get_request_value_string(agent, build_job.request, KeyTokenEx("String"), None)
int_value = UjitsoUtils.get_request_value_int(agent, build_job.request, KeyTokenEx("IntParam"), 0)
dtype = np.dtype('uint32')
elem_size = dtype.itemsize
operation_result, metadata = agent.service.allocate_meta_data_storage(agent, build_handle, elem_size * 255)
self.assertEqual(operation_result, OperationResult.SUCCESS)
# reinterpret data type
metadata_array = np.frombuffer(metadata, dtype)
for i in range(len(metadata_array)):
metadata_array[i] = int_value
external_data = [np.frombuffer(string_value.encode(), dtype=np.uint8)]
validation_data = [ValidationType.MANDATORY]
operation_result = agent.service.store_external_data(agent, build_handle, external_data, validation_data)
return OperationResult.SUCCESS
kIntValue = 0x102
kStringValue = "MyTestStringForFun"
kTokenRequest = KeyTokenEx("String")
test_processor = ProcessorBuild(agent, kTokenRequest)
dynamic_request = DynamicRequest()
dynamic_request.add_int(KeyTokenEx("IntParam"), kIntValue)
dynamic_request.add_string(KeyTokenEx("String"), kStringValue)
request = dynamic_request.get_request()
request_callback_data = RequestCallbackData()
agent_interface = agent.agent
operation_result, request_handle = agent_interface.request_build(agent, request, request_callback_data)
self.assertEqual(operation_result, OperationResult.SUCCESS)
self.assertIsNotNone(request_handle)
self.assertNotEqual(request_handle.value, 0)
operation_result = agent_interface.wait_request(request_handle, TIME_OUT_INFINITE)
self.assertEqual(operation_result, OperationResult.SUCCESS)
operation_result, result_handle = agent_interface.get_request_result(request_handle)
operation_result, metadata = agent_interface.get_request_meta_data(result_handle)
self.assertEqual(operation_result, OperationResult.SUCCESS)
# reinterpret data type
metadata_array = np.frombuffer(metadata, dtype='uint32')
for i in range(len(metadata_array)):
self.assertEqual(metadata_array[i], kIntValue)
operation_result, storages = agent_interface.get_request_external_data(result_handle)
self.assertEqual(operation_result, OperationResult.SUCCESS)
self.assertEqual(len(storages), 1)
operation_result = agent_interface.validate_request_external_data(request_handle, result_handle, [True], True)
self.assertEqual(operation_result, OperationResult.SUCCESS)
storage = storages[0]
operation_result, data_block = DataStoreUtils.copy_data_block(data_store, "", storage)
string_value = ''.join(chr(v) for v in data_block)
self.assertEqual(string_value, kStringValue)
operation_result, storage_context = agent_interface.get_request_storage_context(request_handle)
self.assertEqual(operation_result, OperationResult.SUCCESS)
self.assertEqual(storage_context, "TestStorageContext")
agent_interface.destroy_request(request_handle)
| 15,517 | Python | 46.895062 | 219 | 0.7147 |
omniverse-code/kit/exts/omni.kit.autocapture/omni/kit/autocapture/scripts/extension.py | import os
import importlib
import carb
import carb.settings
try:
import omni.renderer_capture
omni_renderer_capture_present = True
except ImportError:
omni_renderer_capture_present = False
import omni.ext
import omni.kit.app
from omni.hydra.engine.stats import HydraEngineStats
class Extension(omni.ext.IExt):
def __init__(self):
super().__init__()
pass
def _set_default_settings(self):
self._settings.set_default_int("/app/captureFrame/startFrame", -1)
self._settings.set_default("/app/captureFrame/startMultipleFrame/0", -1)
self._settings.set_default_bool("/app/captureFrame/closeApplication", False)
self._settings.set_default_string("/app/captureFrame/fileName", "no-filename-specified")
self._settings.set_default_string("/app/captureFrame/outputPath", "")
self._settings.set_default_bool("/app/captureFrame/setAlphaTo1", True)
self._settings.set_default_bool("/app/captureFrame/saveFps", False)
self._settings.set_default_bool("/app/captureFrame/hdr", False)
self._settings.set_default_int("/app/captureFrame/asyncBufferSizeMB", 2048)
self._settings.set_default_bool("/renderer/gpuProfiler/record", False)
self._settings.set_default_int("/renderer/gpuProfiler/maxIndent", 1)
def on_startup(self):
self._settings = carb.settings.get_settings()
self._set_default_settings()
self._app = omni.kit.app.get_app()
try:
module_omni_usd = importlib.import_module('omni.usd')
self._usd_context = module_omni_usd.get_context()
self._opened_state = module_omni_usd.StageState.OPENED
except ImportError:
self._usd_context = None
self._opened_state = None
if omni_renderer_capture_present:
self._renderer_capture = omni.renderer_capture.acquire_renderer_capture_interface()
self._renderer_capture.start_frame_updates()
else:
self._renderer_capture = None
carb.log_error("Autocapture initialization failed: renderer.capture extension should be present!")
return
# Initial configuration
self._frame_no = 0
# App is exiting before last image has been saved, exit after _quitFrameCounter frames
self._quitFrameCounter = 10
self._multiple_frame_no = 0
self._start_frame = self._settings.get("/app/captureFrame/startFrame")
self._start_multiple_frame = self._settings.get("/app/captureFrame/startMultipleFrame")
self._close_app = self._settings.get("/app/captureFrame/closeApplication")
self._file_name = self._settings.get("/app/captureFrame/fileName")
self._output_path = self._settings.get("/app/captureFrame/outputPath")
if len(self._output_path) == 0:
module_carb_tokens = importlib.import_module('carb.tokens')
self._output_path = module_carb_tokens.get_tokens_interface().resolve("${kit}") + "/../../../outputs/"
self._record_gpu_performance = self._settings.get("/renderer/gpuProfiler/record")
self._recording_max_indent = self._settings.get("/renderer/gpuProfiler/maxIndent")
self._gpu_perf = []
# viewport_api = get_active_viewport()
# self.__stats = HydraEngineStats(viewport_api.usd_context_name, viewport_api.hydra_engine)
self.__stats = HydraEngineStats()
self._count_loading_frames = False
self._next_frame_exit = False
if self._start_frame > 0 or self._start_multiple_frame[0] > 0:
def on_post_update(e: carb.events.IEvent):
if not self._app.is_app_ready():
return
if self._next_frame_exit:
if self._quitFrameCounter <= 0:
self._app.post_quit()
self._quitFrameCounter = self._quitFrameCounter - 1
return None
count_frame = True
if not self._count_loading_frames and self._usd_context is not None:
if self._usd_context.get_stage_state() != self._opened_state:
count_frame = True
if count_frame:
if self._record_gpu_performance and self.__stats:
frame_perf = self.__stats.get_nested_gpu_profiler_result(self._recording_max_indent)
dev_count = len(frame_perf)
has_data = False
for dev_idx in range(dev_count):
if len(frame_perf[dev_idx]) > 0:
has_data = True
break
if has_data:
if len(self._gpu_perf) == 0:
self._gpu_perf.extend(frame_perf)
for dev_idx in range(dev_count):
self._gpu_perf[dev_idx] = {}
for dev_idx in range(dev_count):
self._gpu_perf[dev_idx]["frame %d" % (self._frame_no)] = frame_perf[dev_idx]
self._frame_no += 1
if self._start_frame > 0:
if self._frame_no >= self._start_frame:
self._renderer_capture.capture_next_frame_swapchain(self._output_path + self._file_name)
self._next_frame_exit = self._close_app
if self._start_multiple_frame[0] > 0 and self._multiple_frame_no < len(self._start_multiple_frame):
if self._frame_no >= self._start_multiple_frame[self._multiple_frame_no] :
self._renderer_capture.capture_next_frame_swapchain(self._output_path + self._file_name + "_" +str(self._start_multiple_frame[self._multiple_frame_no]))
self._multiple_frame_no += 1
if self._multiple_frame_no >= len(self._start_multiple_frame):
self._next_frame_exit = self._close_app
self._post_update_subs = self._app.get_post_update_event_stream().create_subscription_to_pop(on_post_update, name="Autocapture post-update")
def on_shutdown(self):
if self._record_gpu_performance:
json_filename = self._output_path + self._file_name + ".json"
dump_json = {}
dev_count = len(self._gpu_perf)
for dev_idx in range(dev_count):
dump_json["GPU-%d" % (dev_idx)] = self._gpu_perf[dev_idx]
import json
with open(json_filename, 'w', encoding='utf-8') as json_file:
json.dump(dump_json, json_file, ensure_ascii=False, indent=4)
self._gpu_perf = None
self._settings = None
self._usd_context = None
self._opened_state = None
self._renderer_capture = None
self._post_update_subs = None
| 7,035 | Python | 44.393548 | 180 | 0.572139 |
omniverse-code/kit/exts/omni.kit.property.render/omni/kit/property/render/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
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class RenderPropertiesExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self.__wg_registered = False
# Register custom UI for Property widget
self.__register_widgets()
def on_shutdown(self):
self.__unregister_widgets()
def __register_widgets(self):
import omni.kit.window.property as p
from omni.kit.property.usd.usd_property_widget import MultiSchemaPropertiesWidget
from .product_schema import ProductSchemaAttributesWidget
from pxr import UsdRender
w = p.get_window()
if w:
self.__wg_registered = True
w.register_widget(
'prim',
'rendersettings_base',
MultiSchemaPropertiesWidget('Render Settings', UsdRender.Settings, [UsdRender.SettingsBase], group_api_schemas = True),
)
w.register_widget(
'prim',
'renderproduct_base',
ProductSchemaAttributesWidget('Render Product',
UsdRender.Product,
[UsdRender.SettingsBase],
include_list=["camera", "orderedVars"],
exclude_list=["aspectRatioConformPolicy", "dataWindowNDC", "instantaneousShutter", "pixelAspectRatio", "productName", "productType"],
group_api_schemas = True),
)
w.register_widget(
'prim',
'rendervar_base',
MultiSchemaPropertiesWidget('Render Var', UsdRender.Var, [UsdRender.Var], group_api_schemas = True),
)
def __unregister_widgets(self):
if self.__wg_registered:
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget('prim', 'rendersettings_base')
w.unregister_widget('prim', 'renderproduct_base')
w.unregister_widget('prim', 'rendervar_base')
self.__wg_registered = False
| 3,015 | Python | 45.399999 | 179 | 0.605307 |
omniverse-code/kit/exts/omni.kit.property.render/omni/kit/property/render/__init__.py | from .extension import RenderPropertiesExtension
| 49 | Python | 23.999988 | 48 | 0.897959 |
omniverse-code/kit/exts/omni.kit.property.render/omni/kit/property/render/product_schema.py | import carb
import omni.ext
from typing import List, Sequence
from pxr import Kind, Sdf, Usd, UsdGeom, Vt, UsdRender
from omni.kit.property.usd.usd_property_widget import MultiSchemaPropertiesWidget, UsdPropertyUiEntry
class ProductSchemaAttributesWidget(MultiSchemaPropertiesWidget):
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = [], api_schemas: Sequence[str] = None, group_api_schemas: bool = False):
super().__init__(title, schema, schema_subclasses, include_list, exclude_list, api_schemas, group_api_schemas)
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim or not prim.IsA(self._schema):
return False
used += [attr for attr in prim.GetAttributes() if attr.GetName() in self._schema_attr_names and not attr.IsHidden()]
return used
def _customize_props_layout(self, attrs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.window.property.templates import (
SimplePropertyWidget,
LABEL_WIDTH,
LABEL_HEIGHT,
HORIZONTAL_SPACING,
)
frame = CustomLayoutFrame(hide_extra=False)
anchor_prim = self._get_prim(self._payload[-1])
with frame:
with CustomLayoutGroup("Render Product"):
CustomLayoutProperty("resolution", "Resolution")
CustomLayoutProperty("camera", "Camera")
CustomLayoutProperty("orderedVars", "Ordered Vars")
# https://github.com/PixarAnimationStudios/USD/commit/dbbe38b94e6bf113acbb9db4c85622fe12a344a5
if hasattr(UsdRender.Tokens, 'disableMotionBlur'):
CustomLayoutProperty("disableMotionBlur", "Disable Motion Blur")
return frame.apply(attrs)
| 2,268 | Python | 38.120689 | 186 | 0.632275 |
omniverse-code/kit/exts/omni.kit.property.render/omni/kit/property/render/tests/test_render_properties.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 pathlib
import omni.kit.app
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import wait_stage_loading
class TestRenderPropertiesWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
test_data_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests")
self.__golden_img_dir = test_data_path.absolute().joinpath('golden_img').absolute()
self.__usd_path = str(test_data_path.joinpath('render_prim_test.usda').absolute())
# After running each test
async def tearDown(self):
await super().tearDown()
# Test(s)
async def __test_render_prim_ui(self, prim_name):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=650,
restore_window = ui.Workspace.get_window('Layer') or ui.Workspace.get_window('Stage'),
restore_position = ui.DockPosition.BOTTOM)
await usd_context.open_stage_async(self.__usd_path)
await wait_stage_loading()
# NOTE: cannot do DomeLight as it contains a file path which is build specific
# Select the prim.
usd_context.get_selection().set_selected_prim_paths([f'/World/RenderTest/{prim_name}'], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self.__golden_img_dir, golden_img_name=f'test_{prim_name}_ui.png')
# Test(s)
async def test_rendersettings_ui(self):
await self.__test_render_prim_ui('rendersettings1')
async def test_renderproduct_ui(self):
await self.__test_render_prim_ui('renderproduct1')
async def test_rendervar_ui(self):
await self.__test_render_prim_ui('rendervar1')
| 2,685 | Python | 37.371428 | 114 | 0.686406 |
omniverse-code/kit/exts/omni.kit.widget.highlight_label/omni/kit/widget/highlight_label/style.py | from omni.ui import color as cl
cl.highlight_default = cl.shade(cl('#848484'))
cl.highlight_highlight = cl.shade(cl('#DFCB4A'))
cl.highlight_selected = cl.shade(cl("#1F2123"))
UI_STYLE = {
"HighlightLabel": {"color": cl.highlight_default},
"HighlightLabel:selected": {"color": cl.highlight_selected},
"HighlightLabel::highlight": {"color": cl.highlight_highlight},
}
| 381 | Python | 30.833331 | 67 | 0.695538 |
omniverse-code/kit/exts/omni.kit.widget.highlight_label/omni/kit/widget/highlight_label/__init__.py | from .highlight_label import HighlightLabel
| 44 | Python | 21.499989 | 43 | 0.863636 |
omniverse-code/kit/exts/omni.kit.widget.highlight_label/omni/kit/widget/highlight_label/highlight_label.py | import carb
import math
from omni import ui
from typing import Optional, Dict
from .style import UI_STYLE
def split_selection(text, selection, match_case: bool = False):
"""
Split given text to substrings to draw selected text. Result starts with unselected text.
Example: "helloworld" "o" -> ["hell", "o", "w", "o", "rld"]
Example: "helloworld" "helloworld" -> ["", "helloworld"]
"""
if not selection:
return [text, ""]
else:
origin_text = text
if not match_case:
selection = selection.lower()
text = text.lower()
elif text == selection:
return ["", text]
selection_len = len(selection)
result = []
while True:
found = text.find(selection)
result.append(origin_text if found < 0 else origin_text[:found])
if found < 0:
break
else:
result.append(origin_text[found : found + selection_len])
text = text[found + selection_len :]
origin_text = origin_text[found + selection_len :]
return result
class HighlightLabel:
"""
Represents a label widget could show hightlight word.
Args:
text (str): String of label.
Keyword args:
highlight (Optional[str]): Word to show highlight
match_case (bool): Show highlight word with case sensitive. Default False.
width (ui.Length): Widget length. Default ui.Fraction(1)
height (ui.Length): Widget height. Default 0
style (Dict): Custom style
"""
def __init__(
self,
text: str,
highlight: Optional[str] = None,
match_case: bool = False,
width: ui.Length=ui.Fraction(1),
height: ui.Length=0,
style: Dict = {}
):
self._container: Optional[ui.HStack] = None
self.__text = text
self.__hightlight = highlight
self.__match_case = match_case
self.__width = width
self.__height = height
self.__style = UI_STYLE.copy()
self.__style.update(style)
self._build_ui()
def _build_ui(self):
if not self._container:
self._container = ui.HStack(width=self.__width, height=self.__height, style=self.__style)
else:
self._container.clear()
if not self.__hightlight:
with self._container:
ui.Label(
self.__text,
width=0,
name="",
style_type_name_override="HighlightLabel",
)
else:
selection_chain = split_selection(self.__text, self.__hightlight, match_case=self.__match_case)
labelnames_chain = ["", "highlight"]
# Extend the label names depending on the size of the selection chain. Example, if it was [a, b]
# and selection_chain is [z,y,x,w], it will become [a, b, a, b].
labelnames_chain *= int(math.ceil(len(selection_chain) / len(labelnames_chain)))
with self._container:
for current_text, current_name in zip(selection_chain, labelnames_chain):
if not current_text:
continue
ui.Label(
current_text,
width=0,
name=current_name,
style_type_name_override="HighlightLabel",
)
@property
def widget(self) -> Optional[ui.HStack]:
return self._container
@property
def visible(self) -> None:
"""
Widget visibility
"""
return self._container.visible
@visible.setter
def visible(self, value: bool) -> None:
self._container.visible = value
@property
def text(self) -> str:
return self.__text
@text.setter
def text(self, value: str) -> None:
self.__text = value
self._build_ui()
@property
def hightlight(self) -> Optional[str]:
return self.__hightlight
@hightlight.setter
def highlight(self, value: Optional[str]) -> None:
self.__hightlight = value
self._build_ui()
@property
def text(self) -> str:
return self.__text
@text.setter
def text(self, value: str) -> None:
self.__text = value | 4,346 | Python | 28.773972 | 108 | 0.546019 |
omniverse-code/kit/exts/omni.kit.widget.highlight_label/omni/kit/widget/highlight_label/tests/test_ui.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.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from .. import HighlightLabel
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests")
TEST_WIDTH = 400
TEST_HEIGHT = 200
CUSTOM_UI_STYLE = {
"HighlightLabel": {"color": 0xFFFFFFFF},
"HighlightLabel::highlight": {"color": 0xFF0000FF},
}
class HightlightLabelTestCase(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_general(self):
"""Testing general look of SearchField"""
window = await self.create_test_window(width=TEST_WIDTH, height=TEST_HEIGHT)
with window.frame:
with ui.VStack(spacing=10):
HighlightLabel("No highlight")
HighlightLabel("Highlight All", highlight="Highlight All")
HighlightLabel("Highlight 'gh'", highlight="gh")
label = HighlightLabel("Highlight 't' via property")
label.highlight = "t"
HighlightLabel("Highlight 'H' MATCH Case", highlight="H", match_case=True)
HighlightLabel("Match Case All", highlight="Match Case All", match_case=True)
HighlightLabel("Highlight style CUSTOM", highlight="style", style=CUSTOM_UI_STYLE)
await self.docked_test_window(window=window, width=TEST_WIDTH, height=TEST_HEIGHT)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="highlight_label.png")
| 2,189 | Python | 42.799999 | 108 | 0.687985 |
omniverse-code/kit/exts/omni.kit.test_suite.stage_window/omni/kit/test_suite/stage_window/tests/visibility_toggle.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.kit.test
import math
import omni.usd
import omni.kit.app
from pxr import UsdGeom
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, get_prims, arrange_windows
class VisibilityToggleUsdStage(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 512)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_eye_visibility_icon(self):
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
def verify_prim_state(expected):
stage = omni.usd.get_context().get_stage()
for prim_path in [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]:
if not "Looks" in prim_path:
self.assertEqual(UsdGeom.Imageable(stage.GetPrimAtPath(prim_path)).ComputeVisibility(), expected[prim_path])
# veirfy default state
verify_prim_state({"/World": "inherited", "/World/defaultLight": "inherited", "/World/Cone": "inherited", "/World/Cube": "inherited", "/World/Sphere": "inherited", "/World/Cylinder": "inherited"})
# build table of eye buttons
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
widgets = {}
for w in stage_widget.find_all("**/Label[*]"):
widget_name = w.widget.text if w.widget.text != "World (defaultPrim)" else "World"
for wtb in stage_widget.find_all(f"**/ToolButton[*]"):
if math.isclose(wtb.widget.screen_position_y, w.widget.screen_position_y):
widgets[widget_name] = wtb
break
# click world eye & verify
await widgets["World"].click()
verify_prim_state({"/World": "invisible", "/World/defaultLight": "invisible", "/World/Cone": "invisible", "/World/Cube": "invisible", "/World/Sphere": "invisible", "/World/Cylinder": "invisible"})
await widgets["World"].click()
verify_prim_state({"/World": "inherited", "/World/defaultLight": "inherited", "/World/Cone": "inherited", "/World/Cube": "inherited", "/World/Sphere": "inherited", "/World/Cylinder": "inherited"})
# click individual prima eye & verify
for prim_name in ["defaultLight", "Cone", "Cube", "Sphere", "Cylinder"]:
expected = {"/World": "inherited", "/World/defaultLight": "inherited", "/World/Cone": "inherited", "/World/Cube": "inherited", "/World/Sphere": "inherited", "/World/Cylinder": "inherited"}
verify_prim_state(expected)
await widgets[prim_name].click()
expected[f"/World/{prim_name}"] = "invisible"
verify_prim_state(expected)
await widgets[prim_name].click()
| 3,523 | Python | 50.823529 | 204 | 0.652853 |
omniverse-code/kit/exts/omni.kit.test_suite.stage_window/omni/kit/test_suite/stage_window/tests/stage_menu_create_custom_materials.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.usd
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, delete_prim_path_children, arrange_windows
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
class TestCreateMenuContextMenu(OmniUiTest):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
DATA = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"]
async def test_l1_stage_menu_create_custom_materials(self):
stage_window = ui_test.find("Stage")
await stage_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = self.DATA
# test custom materials
material_test_helper = MaterialLibraryTestHelper()
for material_url, mtl_name in [("mahogany_floorboards.mdl", "mahogany_floorboards"), ("multi_hair.mdl", "OmniHair_Green"), ("multi_hair.mdl", "OmniHair_Brown")]:
# delete any materials in looks
await delete_prim_path_children("/World/Looks")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item
await ui_test.select_context_menu("Create/Material/Add MDL File", offset=ui_test.Vec2(50, 10))
# use add material dialog
mdl_path = get_test_data_path(__name__, f"mtl/{material_url}")
await material_test_helper.handle_add_material_dialog(mdl_path, mtl_name)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify item(s)
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid())
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, f"/World/Looks/{mtl_name}")
| 3,042 | Python | 43.101449 | 169 | 0.672584 |
omniverse-code/kit/exts/omni.kit.test_suite.stage_window/omni/kit/test_suite/stage_window/tests/select_bound_objects_stage_window.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 platform
import unittest
import omni.kit.app
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class SelectBoundObjectsStageWindow(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
DATA = [
("/World/Looks/OmniPBR", {"/World/Cone", "/World/Cylinder"}),
("/World/Looks/OmniGlass", {"/World/Cube", "/World/Sphere"}),
]
async def test_l1_select_bound_objects_stage_window(self):
usd_context = omni.usd.get_context()
for to_select, to_verify in self.DATA:
# select prims
await select_prims([to_select])
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select}'").right_click()
# click on context menu item
await ui_test.select_context_menu("Select Bound Objects")
# verify
selected = usd_context.get_selection().get_selected_prim_paths()
self.assertSetEqual(set(selected), to_verify)
| 1,937 | Python | 36.999999 | 121 | 0.681982 |
omniverse-code/kit/exts/omni.kit.test_suite.stage_window/omni/kit/test_suite/stage_window/tests/__init__.py | from .select_bound_objects_stage_window import *
from .stage_menu_create_materials import *
from .stage_menu_create_custom_materials import *
from .stage_assign_material_single import *
from .stage_assign_material_multi import *
from .drag_drop_material_stage_item import *
from .drag_drop_material_stage import *
from .drag_drop_usd_stage_item import *
from .drag_drop_usd_external_stage_item import *
from .drag_drop_external_audio_stage import *
from .visibility_toggle import *
| 482 | Python | 39.249997 | 49 | 0.784232 |
omniverse-code/kit/exts/omni.kit.test_suite.stage_window/omni/kit/test_suite/stage_window/tests/drag_drop_usd_external_stage_item.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 os
import carb
import omni.usd
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, arrange_windows
class ExternalDragDropUsdStageItem(AsyncTestCase):
# Before running each test
async def setUp(self):
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
await arrange_windows("Stage", 512)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
async def test_l1_external_drag_drop_usd_stage_item_reference(self):
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
# set dragDropImport
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
# get file
usd_path = get_test_data_path(__name__, f"shapes/basic_sphere.usda").replace("\\", "/")
# position mouse
await ui_test.find("Stage").click()
await ui_test.human_delay()
# simulate drag/drop
omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': [usd_path]})
await ui_test.human_delay(50)
# verify
prim = stage.GetPrimAtPath("/World/basic_sphere")
payloads = omni.usd.get_composed_payloads_from_prim(prim)
references = omni.usd.get_composed_references_from_prim(prim)
self.assertEqual(payloads, [])
self.assertEqual(len(references), 1)
for (ref, layer) in references:
absolute_path = layer.ComputeAbsolutePath(ref.assetPath)
self.assertEqual(os.path.normpath(absolute_path).lower(), os.path.normpath(usd_path).lower())
async def test_l1_external_drag_drop_usd_stage_item_payload(self):
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
# set dragDropImport
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "payload")
# get file
usd_path = get_test_data_path(__name__, f"shapes/basic_cone.usda").replace("\\", "/")
# position mouse
await ui_test.find("Stage").click()
await ui_test.human_delay()
# simulate drag/drop
omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': [usd_path]})
await ui_test.human_delay(50)
# verify
prim = stage.GetPrimAtPath("/World/basic_cone")
payloads = omni.usd.get_composed_payloads_from_prim(prim)
references = omni.usd.get_composed_references_from_prim(prim)
self.assertEqual(references, [])
self.assertEqual(len(payloads), 1)
for (ref, layer) in payloads:
absolute_path = layer.ComputeAbsolutePath(ref.assetPath)
self.assertEqual(os.path.normpath(absolute_path).lower(), os.path.normpath(usd_path).lower())
| 3,800 | Python | 39.870967 | 112 | 0.670263 |
omniverse-code/kit/exts/omni.kit.test_suite.stage_window/omni/kit/test_suite/stage_window/tests/stage_menu_create_materials.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 os
import omni.kit.app
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, delete_prim_path_children, arrange_windows
class StageMenuCreateMaterials(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows(topleft_window="Stage", topleft_height=512, topleft_width=768)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
DATA = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"]
async def test_l1_stage_menu_create_materials(self):
stage_window = ui_test.find("Stage")
await stage_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = self.DATA
# don't write to list returned by get_mdl_list as its ptr to class list
mdl_list = await omni.kit.material.library.get_mdl_list_async(use_hidden=True)
items_to_test = mdl_list.copy()
items_to_test.append(("USD_Preview_Surface", "", None))
items_to_test.append(("USD_Preview_Surface_Texture", "", None))
for mtl_name, _, submenu in items_to_test:
# delete any materials in looks
await delete_prim_path_children("/World/Looks")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item
menu_name = f"Create/Material/{submenu}/{mtl_name.replace('_', ' ')}" if submenu else f"Create/Material/{mtl_name.replace('_', ' ')}"
await ui_test.select_context_menu(menu_name)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify item(s)
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
if mtl_name in ["USD_Preview_Surface", "USD_Preview_Surface_Texture"]:
cmp_name = mtl_name.replace('USD_', '').replace('_', '')
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == f"/World/Looks/{cmp_name}")
else:
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == f"/World/Looks/{mtl_name}")
prim = stage.GetPrimAtPath(f"/World/Looks/{mtl_name}/Shader")
asset_path = prim.GetAttribute("info:mdl:sourceAsset").Get()
self.assertFalse(os.path.isabs(asset_path.path))
self.assertTrue(os.path.isabs(asset_path.resolvedPath))
| 3,639 | Python | 46.272727 | 148 | 0.642209 |
omniverse-code/kit/exts/omni.kit.test_suite.stage_window/omni/kit/test_suite/stage_window/tests/drag_drop_external_audio_stage.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.kit.test
import os
import carb
import omni.usd
import omni.kit.app
from os import listdir
from os.path import isfile, join
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, get_prims, arrange_windows
class ExternalDragDropUsdStageAudio(AsyncTestCase):
# Before running each test
async def setUp(self):
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
await arrange_windows("Stage", 512)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
async def test_l1_external_drag_drop_audio_viewport_item(self):
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
audio_list = []
audio_path = get_test_data_path(__name__, f"media/")
prims = get_prims(stage)
for item_path in [join(audio_path, f) for f in listdir(audio_path) if isfile(join(audio_path, f))]:
# position mouse
await ui_test.find("Stage").click()
await ui_test.human_delay()
# simulate drag/drop
omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': [item_path]})
await ui_test.human_delay(50)
prim_list = get_prims(stage, prims)
self.assertEqual(len(prim_list), 1)
audio_list.append([prim_list[0], os.path.relpath(item_path, audio_path)])
prims.append(prim_list[0])
# verify
self.assertEqual(len(audio_list), 5)
for prim, audio_file in audio_list:
asset_path = prim.GetAttribute('filePath').Get()
self.assertTrue(asset_path.resolvedPath.endswith(audio_file))
| 2,559 | Python | 38.999999 | 118 | 0.675655 |
omniverse-code/kit/exts/omni.kit.test_suite.stage_window/omni/kit/test_suite/stage_window/tests/stage_assign_material_multi.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.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, wait_for_window, arrange_windows
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
class StageAssignMaterialMulti(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
DATA = [["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"],
["", "/World/Looks/OmniGlass", "/World/Looks/OmniPBR", "/World/Looks/OmniSurface_Plastic"]]
async def test_l1_stage_assign_material_multi(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = self.DATA[0]
for index, mtl_path in enumerate(self.DATA[1]):
# select prims
await select_prims(to_select)
# right click on prim
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item
await ui_test.select_context_menu("Assign Material")
#use assign material dialog
async with MaterialLibraryTestHelper() as material_test_helper:
await material_test_helper.handle_assign_material_dialog(index)
# verify
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == mtl_path)
| 2,463 | Python | 42.999999 | 138 | 0.681283 |
omniverse-code/kit/exts/omni.kit.test_suite.stage_window/omni/kit/test_suite/stage_window/tests/drag_drop_usd_stage_item.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 os
import carb
import omni.usd
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropUsdStageItem(AsyncTestCase):
# Before running each test
async def setUp(self):
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
await arrange_windows("Stage", 512)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
async def test_l1_drag_drop_usd_stage_item_reference(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
# set dragDropImport
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.toggle_grid_view_async(show_grid_view=False)
await ui_test.human_delay(50)
usd_path = get_test_data_path(__name__, f"shapes/basic_sphere.usda").replace("\\", "/")
stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
await content_browser_helper.drag_and_drop_tree_view(usd_path, drag_target=drag_target)
await wait_stage_loading()
# verify
prim = stage.GetPrimAtPath("/World/basic_sphere")
payloads = omni.usd.get_composed_payloads_from_prim(prim)
references = omni.usd.get_composed_references_from_prim(prim)
self.assertEqual(payloads, [])
self.assertEqual(len(references), 1)
for (ref, layer) in references:
absolute_path = layer.ComputeAbsolutePath(ref.assetPath)
self.assertEqual(os.path.normpath(absolute_path).lower(), os.path.normpath(usd_path).lower())
async def test_l1_drag_drop_usd_stage_item_payload(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
# set dragDropImport
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "payload")
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.toggle_grid_view_async(show_grid_view=False)
await ui_test.human_delay(50)
usd_path = get_test_data_path(__name__, f"shapes/basic_cone.usda").replace("\\", "/")
stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
await content_browser_helper.drag_and_drop_tree_view(usd_path, drag_target=drag_target)
await wait_stage_loading()
# verify
prim = stage.GetPrimAtPath("/World/basic_cone")
payloads = omni.usd.get_composed_payloads_from_prim(prim)
references = omni.usd.get_composed_references_from_prim(prim)
self.assertEqual(references, [])
self.assertEqual(len(payloads), 1)
for (ref, layer) in payloads:
absolute_path = layer.ComputeAbsolutePath(ref.assetPath)
self.assertEqual(os.path.normpath(absolute_path).lower(), os.path.normpath(usd_path).lower())
| 4,277 | Python | 47.067415 | 113 | 0.680851 |
omniverse-code/kit/exts/omni.kit.livestream.webrtc/omni/kit/livestream/webrtc/scripts/extension.py | import omni.ext
import omni.kit.livestream.bind
class Extension(omni.ext.IExt):
def __init__(self):
pass
def on_startup(self):
self._kit_livestream = omni.kit.livestream.bind.acquire_livestream_interface()
self._kit_livestream.startup()
def on_shutdown(self):
self._kit_livestream.shutdown()
self._kit_livestream = None
| 376 | Python | 22.562499 | 86 | 0.656915 |
omniverse-code/kit/exts/omni.mtlx/omni/mtlx/extension.py | import omni.ext
import os
from pathlib import Path
# path to set to the environment variable `PXR_MTLX_STDLIB_SEARCH_PATHS` while usd is initialized
# i.e., called by omni.usd.config
def get_mtlx_stdlib_search_path() -> str:
# compute the real path without symlinks in order to get it working with usdmtlx
current_dir = os.path.dirname(__file__)
mtlx_libraries_dir = os.path.join(current_dir, '..', '..', 'libraries')
mtlx_libraries_dir = os.path.realpath(mtlx_libraries_dir)
return str(Path(mtlx_libraries_dir).resolve())
class MtlxExtension(omni.ext.IExt):
def on_startup(self):
pass
def on_shutdown(self):
pass | 670 | Python | 32.549998 | 97 | 0.68806 |
omniverse-code/kit/exts/omni.mtlx/omni/mtlx/__init__.py | from .extension import * | 24 | Python | 23.999976 | 24 | 0.791667 |
omniverse-code/kit/exts/omni.mtlx/omni/mtlx/tests/__init__.py | from .setup import *
from .render import *
| 43 | Python | 13.666662 | 21 | 0.72093 |
omniverse-code/kit/exts/omni.mtlx/omni/mtlx/tests/setup.py | import omni.kit.test
import omni.mtlx
import os
import carb
class SetupTest(omni.kit.test.AsyncTestCase):
def test_verify_mtlx_search_path(self):
path:str = omni.mtlx.get_mtlx_stdlib_search_path()
# check the library folder that contains all mtlx standard library modules
exists = os.path.isdir(path)
if not exists:
carb.log_info(f"MaterialX Standard Library Search Path is not existing: {path}")
self.assertTrue(exists)
carb.log_info(f"MaterialX Standard Library Search Path found: {path}")
# test some important libraries as secondary check
self.assertTrue(os.path.exists(os.path.join(path, "bxdf", "standard_surface.mtlx")))
self.assertTrue(os.path.exists(os.path.join(path, "pbrlib", "genmdl", "pbrlib_genmdl_impl.mtlx")))
| 834 | Python | 40.749998 | 106 | 0.677458 |
omniverse-code/kit/exts/omni.mtlx/omni/mtlx/tests/render.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 wait_for_update
from omni.kit.test_helpers_gfx.compare_utils import ComparisonMetric
import carb
from pathlib import Path
import os
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')
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
# This class is auto-discoverable by omni.kit.test
class MtlxRenderTest(RtxTest):
WINDOW_SIZE = (1280, 768)
THRESHOLD = 5e-5
# common settings used for all renderers
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
# Overridden with custom paths
async def capture_and_compare(self,
renderer: str,
img_subdir: Path = "",
test_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)
golden_img_name = f"{test_name}_{renderer}.png"
return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric)
# Open the scene, overridden with custom paths
async def open_usd(self, usdSubpath: Path):
path = USD_DIR.joinpath(usdSubpath)
# This settings should be set before stage opening/creation
self.set_settings(testSettings)
# Actually open the stage
self.ctx.open_stage(str(path))
await omni.kit.app.get_app().next_update_async()
# Settings that should override settings that was set on stage opening/creation
self.set_settings(postLoadTestSettings)
# Close the scene
def close_usd(self):
self.ctx.close_stage()
# do string replacements and save a new file
def prepare_temp_file(self, srcFilename, destFilename, replacementMap):
with open(srcFilename, 'r') as srcFile, \
open(destFilename, 'w') as destFile:
src = srcFile.read()
for key, value in replacementMap.items():
src = src.replace(key, value)
destFile.write(src)
# base test script
async def run_image_test(self, usd_file: str, test_name: str = None):
# load the scene
if usd_file:
await self.open_usd(usd_file)
# wait for rendering and capture
await wait_for_update(wait_frames=128+10)
# golden image path need the renderer
settings = carb.settings.get_settings()
renderer:str = settings.get("/renderer/active")
await self.capture_and_compare(renderer = renderer, test_name = test_name)
# close the scene to also test clean-up
# self.close_usd() # getting `[Error] [omni.usd] Stage opening or closing already in progress!!`
await wait_for_update()
# ==============================================================================================
# The tests
# ==============================================================================================
# StandardSurface presets that ship with the MaterialX SDK
# ----------------------------------------------------------------------------------------------
async def test_standardsurface_composition(self):
await self.run_image_test('StandardSurface/Composition.usda', 'mtlx_standardsurface_composition')
# A selection of the materials published by AMD on https://matlib.gpuopen.com
# ----------------------------------------------------------------------------------------------
async def test_amd_composition(self):
await self.run_image_test('AMD/Composition.usda', 'mtlx_amd_composition')
# Open Chess Set as released by the USD Work Group
# ----------------------------------------------------------------------------------------------
async def test_open_chess_set(self):
await self.run_image_test('OpenChessSet/chess_set_light_camera.usda', 'mtlx_open_chess_set')
# MaterialX tests published in the USD workgroup on https://github.com/usd-wg/assets
# Added a single root prim to each test scene and recomposed them into one test case.
# ----------------------------------------------------------------------------------------------
async def test_usd_wg_assets_composition(self):
try:
# replace the token by an absolute file path in order to test absolute paths
sceneDir = USD_DIR.joinpath('usd-wg-assets')
tempSceneFile = sceneDir.joinpath('basicTextured_flatten.usda')
self.prepare_temp_file(
srcFilename = sceneDir.joinpath('basicTextured_flatten_template.usda'),
destFilename = tempSceneFile,
replacementMap = {"${USD_DIR}":f"{sceneDir}"})
tempMtlxFile = sceneDir.joinpath('standard_surface_brass_tiled_absolute_paths.mtlx')
self.prepare_temp_file(
srcFilename = sceneDir.joinpath('standard_surface_brass_tiled_absolute_paths_template.mtlx'),
destFilename = tempMtlxFile,
replacementMap = {"${USD_DIR}":f"{sceneDir}"})
# run the test
await self.run_image_test('usd-wg-assets/Composition.usda', 'mtlx_usd-wg-assets_composition')
finally:
# remove the temp files
if tempSceneFile.exists():
tempSceneFile.unlink()
if tempMtlxFile.exists():
tempMtlxFile.unlink()
| 5,928 | Python | 44.259542 | 114 | 0.579622 |
omniverse-code/kit/exts/omni.kit.test_suite.helpers/omni/kit/test_suite/helpers/helpers.py | import os
import carb
from pkgutil import iter_modules
import omni.usd
import omni.kit.app
from typing import List
from pxr import Usd
from functools import lru_cache
from pathlib import Path
from omni.kit import ui_test
from omni.kit.ui_test import Vec2
from omni.kit.ui_test import WidgetRef
@lru_cache()
def get_test_data_path(module: str, subpath: str = "") -> str:
if not subpath:
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(module)
return str(Path(ext_path) / "data" / "tests")
return str(Path(get_test_data_path(module)) / subpath)
async def wait():
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
async def wait_stage_loading(usd_context=omni.usd.get_context()):
while True:
_, files_loaded, total_files = usd_context.get_stage_loading_status()
if files_loaded or total_files:
await omni.kit.app.get_app().next_update_async()
continue
break
await wait()
async def open_stage(path: str, usd_context=omni.usd.get_context()):
await usd_context.open_stage_async(path)
await wait_stage_loading(usd_context)
async def select_prims(paths, usd_context=omni.usd.get_context()):
usd_context.get_selection().set_selected_prim_paths(paths, True)
await wait()
# wait for any marterials to load
await wait_stage_loading()
def get_prims(stage, exclude_list=[]):
prims = []
for p in stage.Traverse(Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded)):
if p not in exclude_list:
prims.append(p)
return prims
async def wait_for_window(window_name: str):
MAX_WAIT = 100
# Find active window
for _ in range(MAX_WAIT):
window_root = ui_test.find(f"{window_name}")
if window_root and window_root.widget.visible:
await ui_test.human_delay()
break
await ui_test.human_delay(1)
if not window_root:
raise Exception("Can't find window {window_name}, wait time exceeded.")
async def handle_assign_material_dialog(index, strength_index=0):
carb.log_warn("WARNING: 'handle_assign_material_dialog' is being DEPRECATED. Please use the function of the same name from 'omni.kit.material.library.test_helper.MaterialLibraryTestHelper'")
from pxr import Sdf
# handle assign dialog
prims = omni.usd.get_context().get_selection().get_selected_prim_paths()
if len(prims) == 1:
shape = Sdf.Path(prims[0]).name
window_name = f"Bind material to {shape}###context_menu_bind"
else:
window_name = f"Bind material to {len(prims)} selected models###context_menu_bind"
await wait_for_window(window_name)
# open listbox
widget = ui_test.find(f"{window_name}//Frame/**/Button[*].identifier=='combo_open_button'")
await ui_test.emulate_mouse_move_and_click(widget.center, human_delay_speed=4)
# select material item on listbox
await wait_for_window("MaterialPropertyPopupWindow")
widget = ui_test.find(f"MaterialPropertyPopupWindow//Frame/**/TreeView[*]")
# FIXME - can't use widget.click as open combobox has no readable size and clicks goto stage window
item_name = widget.model.get_item_children(None)[index].name_model.as_string if index else "None"
await ui_test.find(f"MaterialPropertyPopupWindow//Frame/**/Label[*].text=='{item_name}'").click(human_delay_speed=4)
# select strength item on listbox
widget = ui_test.find(f"{window_name}//Frame/**/ComboBox[*]")
if widget:
widget.model.set_value(strength_index)
# click ok
widget = ui_test.find(f"{window_name}//Frame/**/Button[*].identifier=='assign_material_ok_button'")
await ui_test.emulate_mouse_move_and_click(widget.center, human_delay_speed=4)
# wait for materials to load
await ui_test.human_delay()
await wait_stage_loading()
async def handle_create_material_dialog(mdl_path: str, mtl_name: str):
carb.log_warn("WARNING: 'handle_create_material_dialog' is being DEPRECATED. Please use the function of the same name from 'omni.kit.material.library.test_helper.MaterialLibraryTestHelper'")
subid_list = []
def have_subids(id_list):
nonlocal subid_list
subid_list = id_list
await omni.kit.material.library.get_subidentifier_from_mdl(mdl_file=mdl_path, on_complete_fn=have_subids)
if len(subid_list)> 1:
# material has subid and dialog is shown
await wait_for_window("Create Material")
create_widget = ui_test.find("Create Material//Frame/**/Button[*].identifier=='create_material_ok_button'")
subid_widget = ui_test.find("Create Material//Frame/**/ComboBox[*].identifier=='create_material_subid_combo'")
subid_list = subid_widget.model.get_item_list()
subid_index = 0
for index, subid in enumerate(subid_list):
if subid.name == mtl_name:
subid_index = index
subid_widget.model.set_current_index(subid_index)
await ui_test.human_delay()
create_widget.widget.call_clicked_fn()
await ui_test.human_delay(4)
await wait_stage_loading()
async def delete_prim_path_children(prim_path: str):
stage = omni.usd.get_context().get_stage()
root_prim = stage.GetPrimAtPath(prim_path)
purge_list = []
for prim in Usd.PrimRange(root_prim):
if prim.GetPath().pathString != root_prim.GetPath().pathString:
purge_list.append(prim)
for prim in purge_list:
stage.RemovePrim(prim.GetPath())
# wait for refresh after deleting prims
await ui_test.human_delay()
async def build_sdf_asset_frame_dictonary():
widget_table = {}
for frame in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if frame.widget.title != "Raw USD Properties":
for widget in frame.find_all("Property//Frame/**/StringField[*].identifier!=''"):
if widget.widget.identifier.startswith('sdf_asset_'):
if not frame.widget.title in widget_table:
widget_table[frame.widget.title] = {}
if not widget.widget.identifier in widget_table[frame.widget.title]:
widget_table[frame.widget.title][widget.widget.identifier] = 0
widget_table[frame.widget.title][widget.widget.identifier] += 1
return widget_table
def push_window_height(cls, window_name, new_height=None):
window = ui_test.find(window_name)
if window:
if not hasattr(cls, "_original_window_height"):
cls._original_window_height = {}
cls._original_window_height[window_name] = window.widget.height
if new_height is not None:
window.widget.height = new_height
def pop_window_height(cls, window_name):
window = ui_test.find(window_name)
if window:
if hasattr(cls, "_original_window_height"):
window.widget.height = cls._original_window_height[window_name]
del cls._original_window_height[window_name]
async def handle_multiple_descendents_dialog(stage, prim_path: str, target_prim: str):
root_prim = stage.GetPrimAtPath(prim_path)
if not root_prim:
return
descendents = omni.usd.get_prim_descendents(root_prim)
# skip if only root_prim
if descendents == [root_prim]:
return
await ui_test.human_delay(10)
await wait_for_window("Target prim has multiple descendents")
await ui_test.human_delay(10)
# need to select target_prim in combo_widget
combo_widget = ui_test.find("Target prim has multiple descendents//Frame/**/ComboBox[*].identifier=='multi_descendents_combo'")
combo_list = combo_widget.model.get_item_children(None)
combo_index = 0
for index, item in enumerate(combo_list):
if item.prim.GetPrimPath().pathString == target_prim:
combo_index = index
combo_widget.model.set_current_index(combo_index)
await ui_test.human_delay()
ok_widget = ui_test.find("Target prim has multiple descendents//Frame/**/Button[*].identifier=='multi_descendents_ok_button'")
await ok_widget.click()
await wait_stage_loading()
async def arrange_windows(topleft_window="Stage", topleft_height=421.0, topleft_width=436.0, hide_viewport=False):
from omni.kit.viewport.utility import get_active_viewport_window
viewport_window = get_active_viewport_window()
# omni.ui & legacy viewport synch
await wait()
if viewport_window:
vp_width = int(1436 - topleft_width)
viewport_window.position_x = 0
viewport_window.position_y = 0
viewport_window.width = vp_width
viewport_window.height = 425
viewport_window.visible = (not hide_viewport)
# # XXX: force the legacy API
# if hasattr(viewport_window, 'legacy_window'):
# legacy_window = viewport_window.legacy_window
# legacy_window.set_window_pos(0, 0)
# legacy_window.set_window_size(vp_width, 425)
# viewport.show_hide_window(not hide_viewport)
import omni.ui as ui
content_window = ui.Workspace.get_window("Content")
if content_window:
content_window.position_x = 0.0
content_window.position_y = 448.0
content_window.width = 1436.0 - topleft_width
content_window.height = 421.0
await ui_test.human_delay()
stage_window = ui.Workspace.get_window("Stage")
if stage_window:
stage_window.position_x = 1436.0 - topleft_width
stage_window.position_y = 0.0
stage_window.width = topleft_width
stage_window.height = topleft_height
await ui_test.human_delay()
layer_window = ui.Workspace.get_window("Layer")
if layer_window:
layer_window.position_x = 1436.0 - topleft_width
layer_window.position_y = 0.0
layer_window.width = topleft_width
layer_window.height = topleft_height
await ui_test.human_delay()
tl_window = ui.Workspace.get_window(topleft_window)
if tl_window:
tl_window.focus()
property_window = ui.Workspace.get_window("Property")
if property_window:
property_window.position_x = 1436.0 - topleft_width
property_window.position_y = topleft_height + 27.0
property_window.width = topleft_width
property_window.height = 846.0 - topleft_height
await ui_test.human_delay()
# Wait for the layout to complete
await wait()
return viewport_window
| 10,555 | Python | 37.246377 | 194 | 0.665656 |
omniverse-code/kit/exts/omni.kit.test_suite.helpers/omni/kit/test_suite/helpers/__init__.py | from .helpers import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
omniverse-code/kit/exts/omni.kit.test_suite.helpers/omni/kit/test_suite/helpers/test_populators.py | """Support for utility classes that populate a list of tests from various locations"""
| 87 | Python | 42.999979 | 86 | 0.781609 |
omniverse-code/kit/exts/omni.kit.window.file_importer/scripts/demo_file_importer.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import asyncio
import omni.ui as ui
import omni.usd as usd
from typing import List
from omni.kit.window.file_importer import get_file_importer, ImportOptionsDelegate
# BEGIN-DOC-import_options
class MyImportOptionsDelegate(ImportOptionsDelegate):
def __init__(self):
super().__init__(build_fn=self._build_ui_impl, destroy_fn=self._destroy_impl)
self._widget = None
def _build_ui_impl(self):
self._widget = ui.Frame()
with self._widget:
with ui.VStack():
with ui.HStack(height=24, spacing=2, style={"background_color": 0xFF23211F}):
ui.Label("Prim Path", width=0)
ui.StringField().model = ui.SimpleStringModel()
ui.Spacer(height=8)
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
# END-DOC-import_options
# BEGIN-DOC-tagging_options
class MyTaggingOptionsDelegate(ImportOptionsDelegate):
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
filename_changed_fn=self._filename_changed_impl,
selection_changed_fn=self._selection_changed_impl,
destroy_fn=self._destroy_impl
)
self._widget = None
def _build_ui_impl(self, file_type: str=''):
self._widget = ui.Frame()
with self._widget:
with ui.VStack():
ui.Button(f"Tags for {file_type or 'unknown'} type", height=24)
def _filename_changed_impl(self, filename: str):
if filename:
_, ext = os.path.splitext(filename)
self._build_ui_impl(file_type=ext)
def _selection_changed_impl(self, selections: List[str]):
if len(selections) == 1:
_, ext = os.path.splitext(selections[0])
self._build_ui_impl(file_type=ext)
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
# END-DOC-tagging_options
class DemoFileImporterDialog:
"""
Example that demonstrates how to invoke the file importer dialog.
"""
def __init__(self):
self._app_window: ui.Window = None
self._import_options: ImportOptionsDelegate = None
self._tagging_options: ImportOptionsDelegate = None
self.build_ui()
def build_ui(self):
""" """
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
self._app_window = ui.Window("File Importer", width=1000, height=500, flags=window_flags)
with self._app_window.frame:
with ui.VStack(spacing=10):
with ui.HStack(height=30):
ui.Spacer()
button = ui.Button(text="Import File", width=120)
button.set_clicked_fn(self._show_dialog)
ui.Spacer()
asyncio.ensure_future(self._dock_window("File Importer", ui.DockPosition.TOP))
def _show_dialog(self):
# BEGIN-DOC-get_instance
# Get the singleton extension.
file_importer = get_file_importer()
if not file_importer:
return
# END-DOC-get_instance
# BEGIN-DOC-show_window
file_importer.show_window(
title="Import File",
import_handler=self.import_handler,
#filename_url="omniverse://ov-rc/NVIDIA/Samples/Marbles/Marbles_Assets.usd",
)
# END-DOC-show_window
# BEGIN-DOC-add_tagging_options
self._tagging_options = MyTaggingOptionsDelegate()
file_importer.add_import_options_frame("Tagging Options", self._tagging_options)
# END-DOC-add_tagging_options
# BEGIN-DOC-add_import_options
self._import_options = MyImportOptionsDelegate()
file_importer.add_import_options_frame("Import Options", self._import_options)
# END-DOC-add_import_options
def _hide_dialog(self):
# Get the File Importer extension.
file_importer = get_file_importer()
if file_importer:
file_importer.hide()
# BEGIN-DOC-import_handler
def import_handler(self, filename: str, dirname: str, selections: List[str] = []):
# NOTE: Get user inputs from self._import_options, if needed.
print(f"> Import '{filename}' from '{dirname}' or selected files '{selections}'")
# END-DOC-import_handler
async def _dock_window(self, window_title: str, position: ui.DockPosition, ratio: float = 1.0):
frames = 3
while frames > 0:
if ui.Workspace.get_window(window_title):
break
frames = frames - 1
await omni.kit.app.get_app().next_update_async()
window = ui.Workspace.get_window(window_title)
dockspace = ui.Workspace.get_window("DockSpace")
if window and dockspace:
window.dock_in(dockspace, position, ratio=ratio)
window.dock_tab_bar_visible = False
def destroy(self):
if self._app_window:
self._app_window.destroy()
self._app_window = None
if __name__ == "__main__":
view = DemoFileImporterDialog()
| 5,583 | Python | 34.119497 | 99 | 0.615081 |
omniverse-code/kit/exts/omni.kit.window.file_importer/omni/kit/window/file_importer/__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.
#
"""A standardized dialog for importing files"""
__all__ = ['FileImporterExtension', 'get_file_importer']
from carb import log_warn
from omni.kit.window.filepicker import DetailFrameController as ImportOptionsDelegate
from .extension import FileImporterExtension, get_instance
def get_file_importer() -> FileImporterExtension:
"""Returns the singleton file_importer extension instance"""
instance = get_instance()
if instance is None:
log_warn("File importer extension is no longer alive.")
return instance | 965 | Python | 42.909089 | 85 | 0.780311 |
omniverse-code/kit/exts/omni.kit.window.file_importer/omni/kit/window/file_importer/tests/test_extension.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.test
import asyncio
import omni.kit.ui_test as ui_test
import omni.appwindow
from unittest.mock import Mock, patch, ANY
from carb.settings import ISettings
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.test_suite.helpers import get_test_data_path
from .. import get_file_importer
from ..extension import FileImporterExtension
from ..test_helper import FileImporterTestHelper
class TestFileImporter(omni.kit.test.AsyncTestCase):
"""
Testing omni.kit.window.file_importer extension. NOTE that since the dialog is a singleton, we use an async
lock to ensure that only one test runs at a time. In practice, this is not a issue because only one extension
is accessing the dialog at any given time.
"""
__lock = asyncio.Lock()
async def setUp(self):
self._settings_path = "my_settings"
self._test_settings = {
"/exts/omni.kit.window.file_importer/appSettings": self._settings_path,
f"{self._settings_path}/directory": "C:/temp/folder",
}
async def tearDown(self):
pass
def _mock_settings_get_string_impl(self, name: str) -> str:
return self._test_settings.get(name)
def _mock_settings_set_string_impl(self, name: str, value: str):
self._test_settings[name] = value
async def test_show_window_destroys_previous(self):
"""Testing show_window destroys previously allocated dialog"""
async with self.__lock:
under_test = get_file_importer()
with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog,\
patch("carb.windowing.IWindowing.hide_window"):
under_test.show_window(title="first")
under_test.show_window(title="second")
mock_destroy_dialog.assert_called()
dialog = mock_destroy_dialog.call_args[0][0]
self.assertEqual(str(dialog._window), "first")
async def test_hide_window_destroys_it(self):
"""Testing that hiding the window destroys it"""
async with self.__lock:
under_test = get_file_importer()
with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog:
under_test.show_window(title="test")
under_test._dialog.hide()
# Dialog is destroyed after a couple frames
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
mock_destroy_dialog.assert_called()
dialog = mock_destroy_dialog.call_args[0][0]
self.assertEqual(str(dialog._window), "test")
async def test_hide_window_destroys_detached_window(self):
"""Testing that hiding the window destroys detached window."""
async with self.__lock:
under_test = get_file_importer()
with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog:
under_test.show_window(title="test_detached")
await omni.kit.app.get_app().next_update_async()
under_test.detach_from_main_window()
main_window = omni.appwindow.get_default_app_window().get_window()
self.assertFalse(main_window is under_test._dialog._window.app_window.get_window())
under_test.hide_window()
# Dialog is destroyed after a couple frames
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
mock_destroy_dialog.assert_called()
dialog = mock_destroy_dialog.call_args[0][0]
self.assertEqual(str(dialog._window), "test_detached")
async def test_load_default_settings(self):
"""Testing that dialog applies saved settings"""
async with self.__lock:
under_test = get_file_importer()
with patch('omni.kit.window.file_importer.extension.FilePickerDialog') as mock_dialog,\
patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl):
under_test.show_window(title="test_dialog")
# Retrieve keyword args for the constructor (first call), and confirm called with expected values
constructor_kwargs = mock_dialog.call_args_list[0][1]
self.assertEqual(constructor_kwargs['current_directory'], self._test_settings[f"{self._settings_path}/directory"])
async def test_override_default_settings(self):
"""Testing that user values override default settings"""
async with self.__lock:
test_url = "Omniverse://ov-test/my-folder/my-file.usd"
under_test = get_file_importer()
with patch('omni.kit.window.file_importer.extension.FilePickerDialog') as mock_dialog,\
patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl),\
patch("carb.windowing.IWindowing.hide_window"):
under_test.show_window(title="test_dialog", filename_url=test_url)
# Retrieve keyword args for the constructor (first call), and confirm called with expected values
constructor_kwargs = mock_dialog.call_args_list[0][1]
dirname, filename = os.path.split(test_url)
self.assertEqual(constructor_kwargs['current_directory'], dirname)
self.assertEqual(constructor_kwargs['current_filename'], filename)
async def test_save_settings_on_import(self):
"""Testing that settings are saved on import"""
from ..extension import on_import
my_settings = {
'filename': "my-file.anim.usd",
'directory': "Omniverse://ov-test/my-folder",
}
mock_dialog = Mock()
with patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl),\
patch.object(ISettings, "set_string", side_effect=self._mock_settings_set_string_impl):
on_import(None, mock_dialog, my_settings['filename'], my_settings['directory'])
# Retrieve keyword args for the constructor (first call), and confirm called with expected values
self.assertEqual(my_settings['directory'], self._test_settings[f"{self._settings_path}/directory"])
async def test_show_only_folders(self):
"""Testing show only folders option."""
mock_handler = Mock()
async with self.__lock:
under_test = get_file_importer()
test_path = get_test_data_path(__name__).replace("\\", '/')
async with FileImporterTestHelper() as helper:
with patch("carb.windowing.IWindowing.hide_window"):
# under normal circumstance, files will be shown and could be selected.
under_test.show_window(title="test", filename_url=test_path + "/")
await ui_test.human_delay(10)
item = await helper.get_item_async(None, "dummy.usd")
self.assertIsNotNone(item)
# apply button should be disabled
self.assertFalse(under_test._dialog._widget.file_bar._apply_button.enabled)
await helper.click_cancel_async()
# if shown with show_only_folders, files will not be shown
under_test.show_window(title="test", show_only_folders=True, import_handler=mock_handler)
await ui_test.human_delay(10)
item = await helper.get_item_async(None, "dummy.usd")
self.assertIsNone(item)
# try selecting a folder
selections = await under_test.select_items_async(test_path, filenames=['folder'])
self.assertEqual(len(selections), 1)
selected = selections[0]
# apply button should not be disabled
self.assertTrue(under_test._dialog._widget.file_bar._apply_button.enabled)
await ui_test.human_delay()
await helper.click_apply_async()
mock_handler.assert_called_once_with('', selected.path + "/", selections=[selected.path])
async def test_cancel_handler(self):
"""Testing cancel handler."""
mock_handler = Mock()
async with self.__lock:
under_test = get_file_importer()
async with FileImporterTestHelper() as helper:
under_test.show_window("test_cancel_handler")
await helper.wait_for_popup()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await helper.click_cancel_async(cancel_handler=mock_handler)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
mock_handler.assert_called_once()
class TestFileFilterHandler(omni.kit.test.AsyncTestCase):
async def setUp(self):
ext_type = {
'usd': "*.usd",
'usda': "*.usda",
'usdc': "*.usdc",
'usdz': "*.usdz",
'multiusd': "*.usd, *.usda, *.usdc, *.usdz",
'all': "*.*",
'bad_formatting_type': "*.usd, .usda, *.usdc,*.usdz, , ,"
}
self.test_filenames = [
("test.anim.usd", "anim", ext_type['all'], True),
("test.anim.usd", "anim", ext_type['usd'], True),
("test.anim.usdz", "anim", ext_type['usdz'], True),
("test.anim.usdc", "anim", ext_type['usdz'], False),
("test.anim.usda", None, ext_type['usda'], True),
("test.material.", None, ext_type['usda'], False),
("test.materials.usd", "material", ext_type['usd'], False),
("test.material.", None, ext_type['all'], True),
("test.material.", "anim", ext_type['all'], False),
("test.material.", "material", ext_type['all'], True),
]
for t in ["multiusd", 'bad_formatting_type']:
self.test_filenames.extend([
("test.anim.usd", "anim", ext_type[t], True),
("test.anim.usdz", "anim", ext_type[t], True),
("test.anim.usdc", "anim", ext_type[t], True),
("test.anim.usda", None, ext_type[t], True),
("test.anim.bbb", None, ext_type[t], False),
("test.material.", None, ext_type[t], False),
("test.anim.usdc", "cache", ext_type[t], False),
("test.anim.usdc", None, ext_type[t], True),
])
async def tearDown(self):
pass
async def test_file_filter_handler(self):
"""Testing default file filter handler"""
from ..extension import default_filter_handler
for test_filename in self.test_filenames:
filename, postfix, ext, expected = test_filename
result = default_filter_handler(filename, postfix, ext)
self.assertEqual(result, expected)
| 11,636 | Python | 48.519149 | 126 | 0.601152 |
omniverse-code/kit/exts/omni.kit.window.console/omni/kit/window/console/__init__.py | from ._console import *
from .scripts import * | 47 | Python | 14.999995 | 23 | 0.723404 |
omniverse-code/kit/exts/omni.kit.window.console/omni/kit/window/console/scripts/console_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__ = ["ConsoleWindow"]
import omni.kit
import omni.ui as ui
from .._console import ConsoleWidget
class ConsoleWindow(ui.Window):
"""The Console window"""
def __init__(self):
self._title = "Console"
super().__init__(
self._title,
width=1000,
height=600,
dockPreference=ui.DockPreference.LEFT_BOTTOM,
raster_policy=ui.RasterPolicy.NEVER
)
# Dock it to the same space where Content is docked, make it the second tab and the active tab.
self.deferred_dock_in("Content", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
self.dock_order = 1
self.set_visibility_changed_fn(self._visibility_changed_fn)
with self.frame:
self._console_widget = ConsoleWidget()
def _visibility_changed_fn(self, visible):
if self._visiblity_changed_listener:
self._visiblity_changed_listener(visible)
def set_visibility_changed_listener(self, listener):
self._visiblity_changed_listener = listener
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
if self._console_widget:
self._console_widget.destroy()
self._console_widget = None
self._visiblity_changed_listener = None
super().destroy()
| 1,868 | Python | 32.374999 | 103 | 0.663812 |
omniverse-code/kit/exts/omni.kit.window.console/omni/kit/window/console/scripts/__init__.py | from .console_extension import ConsoleExtension | 47 | Python | 46.999953 | 47 | 0.893617 |
omniverse-code/kit/exts/omni.kit.window.console/omni/kit/window/console/tests/__init__.py | from .console_tests import *
| 29 | Python | 13.999993 | 28 | 0.758621 |
omniverse-code/kit/exts/omni.kit.window.console/omni/kit/window/console/tests/console_tests.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.window.console import ConsoleWidget
from pathlib import Path
import omni.kit.app
import omni.kit.ui_test as ui_test
class TestConsoleWindow(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_console(self):
window = await self.create_test_window(1000, 600)
with window.frame:
console_widget = ConsoleWidget()
console_widget.exec_command("clear")
console_window = ui_test.find("Console")
console_window._widget._console_widget.exec_command("clear")
for i in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_console.png", use_log=False)
console_widget.visible =False
console_widget.destroy()
console_window._widget.visible =False
console_window._widget.destroy()
| 1,768 | Python | 36.638297 | 120 | 0.701357 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Sdf/__init__.py | #
# Copyright 2016 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.
#
from pxr import Tf
Tf.PreparePythonModule()
del Tf
def Find(layerFileName, scenePath=None):
'''Find(layerFileName, scenePath) -> object
layerFileName: string
scenePath: Path
If given a single string argument, returns the menv layer with
the given filename. If given two arguments (a string and a Path), finds
the menv layer with the given filename and returns the scene object
within it at the given path.'''
layer = Layer.Find(layerFileName)
if (scenePath is None): return layer
return layer.GetObjectAtPath(scenePath)
# Test utilities
def _PathElemsToPrefixes(absolute, elements):
if absolute:
string = "/"
else:
string = ""
lastElemWasDotDot = False
didFirst = False
for elem in elements:
if elem == Path.parentPathElement:
# dotdot
if didFirst:
string = string + "/"
else:
didFirst = True
string = string + elem
lastElemWasDotDot = True
elif elem[0] == ".":
# property
if lastElemWasDotDot:
string = string + "/"
string = string + elem
lastElemWasDotDot = False
elif elem[0] == "[":
# rel attr or sub-attr indices, don't care which
string = string + elem
lastElemWasDotDot = False
else:
if didFirst:
string = string + "/"
else:
didFirst = True
string = string + elem
lastElemWasDotDot = False
if not string:
return []
path = Path(string)
return path.GetPrefixes()
| 2,722 | Python | 31.807229 | 74 | 0.646583 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Sdf/__DOC.py | def Execute(result):
result["AssetPath"].__doc__ = """
Contains an asset path and an optional resolved path. Asset paths may
contain non-control UTF-8 encoded characters. Specifically,
U+0000\\.\\.U+001F (C0 controls), U+007F (delete), and
U+0080\\.\\.U+009F (C1 controls) are disallowed. Attempts to construct
asset paths with such characters will issue a TfError and produce the
default-constructed empty asset path.
"""
result["AssetPath"].__init__.func_doc = """__init__()
Construct an empty asset path.
----------------------------------------------------------------------
__init__(path)
Construct an asset path with ``path`` and no associated resolved path.
If the passed ``path`` is not valid UTF-8 or contains C0 or C1 control
characters, raise a TfError and return the default-constructed empty
asset path.
Parameters
----------
path : str
----------------------------------------------------------------------
__init__(path, resolvedPath)
Construct an asset path with ``path`` and an associated
``resolvedPath`` .
If either the passed \path or ``resolvedPath`` are not valid UTF-8 or
either contain C0 or C1 control characters, raise a TfError and return
the default-constructed empty asset path.
Parameters
----------
path : str
resolvedPath : str
"""
result["AttributeSpec"].__doc__ = """
A subclass of SdfPropertySpec that holds typed data.
Attributes are typed data containers that can optionally hold any and
all of the following:
- A single default value.
- An array of knot values describing how the value varies over
time.
- A dictionary of posed values, indexed by name.
The values contained in an attribute must all be of the same type. In
the Python API the ``typeName`` property holds the attribute type. In
the C++ API, you can get the attribute type using the GetTypeName()
method. In addition, all values, including all knot values, must be
the same shape. For information on shapes, see the VtShape class
reference in the C++ documentation.
"""
result["AttributeSpec"].HasColorSpace.func_doc = """HasColorSpace() -> bool
Returns true if this attribute has a colorSpace value authored.
"""
result["AttributeSpec"].ClearColorSpace.func_doc = """ClearColorSpace() -> None
Clears the colorSpace metadata value set on this attribute.
"""
result["BatchNamespaceEdit"].__doc__ = """
A description of an arbitrarily complex namespace edit.
A ``SdfBatchNamespaceEdit`` object describes zero or more namespace
edits. Various types providing a namespace will allow the edits to be
applied in a single operation and also allow testing if this will
work.
Clients are encouraged to group several edits into one object because
that may allow more efficient processing of the edits. If, for
example, you need to reparent several prims it may be faster to add
all of the reparents to a single ``SdfBatchNamespaceEdit`` and apply
them at once than to apply each separately.
Objects that allow applying edits are free to apply the edits in any
way and any order they see fit but they should guarantee that the
resulting namespace will be as if each edit was applied one at a time
in the order they were added.
Note that the above rule permits skipping edits that have no effect or
generate a non-final state. For example, if renaming A to B then to C
we could just rename A to C. This means notices may be elided.
However, implementations must not elide notices that contain
information about any edit that clients must be able to know but
otherwise cannot determine.
"""
result["BatchNamespaceEdit"].__init__.func_doc = """__init__()
Create an empty sequence of edits.
----------------------------------------------------------------------
__init__(arg1)
Parameters
----------
arg1 : BatchNamespaceEdit
----------------------------------------------------------------------
__init__(arg1)
Parameters
----------
arg1 : list[SdfNamespaceEdit]
"""
result["BatchNamespaceEdit"].Add.func_doc = """Add(edit) -> None
Add a namespace edit.
Parameters
----------
edit : NamespaceEdit
----------------------------------------------------------------------
Add(currentPath, newPath, index) -> None
Add a namespace edit.
Parameters
----------
currentPath : NamespaceEdit.Path
newPath : NamespaceEdit.Path
index : NamespaceEdit.Index
"""
result["BatchNamespaceEdit"].Process.func_doc = """Process(processedEdits, hasObjectAtPath, canEdit, details, fixBackpointers) -> bool
Validate the edits and generate a possibly more efficient edit
sequence.
Edits are treated as if they were performed one at time in sequence,
therefore each edit occurs in the namespace resulting from all
previous edits.
Editing the descendants of the object in each edit is implied. If an
object is removed then the new path will be empty. If an object is
removed after being otherwise edited, the other edits will be
processed and included in ``processedEdits`` followed by the removal.
This allows clients to fixup references to point to the object's final
location prior to removal.
This function needs help to determine if edits are allowed. The
callbacks provide that help. ``hasObjectAtPath`` returns ``true`` iff
there's an object at the given path. This path will be in the original
namespace not any intermediate or final namespace. ``canEdit`` returns
``true`` iff the object at the current path can be namespace edited to
the new path, ignoring whether an object already exists at the new
path. Both paths are in the original namespace. If it returns
``false`` it should set the string to the reason why the edit isn't
allowed. It should not write either path to the string.
If ``hasObjectAtPath`` is invalid then this assumes objects exist
where they should and don't exist where they shouldn't. Use this with
care. If ``canEdit`` in invalid then it's assumed all edits are valid.
If ``fixBackpointers`` is ``true`` then target/connection paths are
expected to be in the intermediate namespace resulting from all
previous edits. If ``false`` and any current or new path contains a
target or connection path that has been edited then this will generate
an error.
This method returns ``true`` if the edits are allowed and sets
``processedEdits`` to a new edit sequence at least as efficient as the
input sequence. If not allowed it returns ``false`` and appends
reasons why not to ``details`` .
Parameters
----------
processedEdits : list[SdfNamespaceEdit]
hasObjectAtPath : HasObjectAtPath
canEdit : CanEdit
details : list[SdfNamespaceEditDetail]
fixBackpointers : bool
"""
result["ChangeBlock"].__doc__ = """
**DANGER DANGER DANGER**
Please make sure you have read and fully understand the issues below
before using a changeblock! They are very easy to use in an unsafe way
that could make the system crash or corrupt data. If you have any
questions, please contact the USD team, who would be happy to help!
SdfChangeBlock provides a way to group a round of related changes to
scene description in order to process them more efficiently.
Normally, Sdf sends notification immediately as changes are made so
that downstream representations like UsdStage can update accordingly.
However, sometimes it can be advantageous to group a series of Sdf
changes into a batch so that they can be processed more efficiently,
with a single round of change processing. An example might be when
setting many avar values on a model at the same time.
Opening a changeblock tells Sdf to delay sending notification about
changes until the outermost changeblock is exited. Until then, Sdf
internally queues up the notification it needs to send.
It is *not* safe to use Usd or other downstream API while a
changeblock is open!! This is because those derived representations
will not have had a chance to update while the changeblock is open.
Not only will their view of the world be stale, it could be unsafe to
even make queries from, since they may be holding onto expired handles
to Sdf objects that no longer exist. If you need to make a bunch of
changes to scene description, the best approach is to build a list of
necessary changes that can be performed directly via the Sdf API, then
submit those all inside a changeblock without talking to any
downstream modules. For example, this is how many mutators in Usd
that operate on more than one field or Spec work.
"""
result["ChangeBlock"].__init__.func_doc = """__init__()
"""
result["CleanupEnabler"].__doc__ = """
An RAII class which, when an instance is alive, enables scheduling of
automatic cleanup of SdfLayers.
Any affected specs which no longer contribute to the scene will be
removed when the last SdfCleanupEnabler instance goes out of scope.
Note that for this purpose, SdfPropertySpecs are removed if they have
only required fields (see SdfPropertySpecs::HasOnlyRequiredFields),
but only if the property spec itself was affected by an edit that left
it with only required fields. This will have the effect of
uninstantiating on-demand attributes. For example, if its parent prim
was affected by an edit that left it otherwise inert, it will not be
removed if it contains an SdfPropertySpec with only required fields,
but if the property spec itself is edited leaving it with only
required fields, it will be removed, potentially uninstantiating it if
it's an on-demand property.
SdfCleanupEnablers are accessible in both C++ and Python.
/// SdfCleanupEnabler can be used in the following manner:
.. code-block:: text
{
SdfCleanupEnabler enabler;
// Perform any action that might otherwise leave inert specs around,
// such as removing info from properties or prims, or removing name
// children. i.e:
primSpec->ClearInfo(SdfFieldKeys->Default);
// When enabler goes out of scope on the next line, primSpec will
// be removed if it has been left as an empty over.
}
"""
result["CleanupEnabler"].__init__.func_doc = """__init__()
"""
result["FastUpdateList"].__doc__ = """"""
result["FileFormat"].__doc__ = """
Base class for file format implementations.
"""
result["FileFormat"].GetFileExtensions.func_doc = """GetFileExtensions() -> list[str]
Returns a list of extensions that this format supports.
"""
result["FileFormat"].IsSupportedExtension.func_doc = """IsSupportedExtension(extension) -> bool
Returns true if ``extension`` matches one of the extensions returned
by GetFileExtensions.
Parameters
----------
extension : str
"""
result["FileFormat"].IsPackage.func_doc = """IsPackage() -> bool
Returns true if this file format is a package containing other assets.
"""
result["FileFormat"].CanRead.func_doc = """CanRead(file) -> bool
Returns true if ``file`` can be read by this format.
Parameters
----------
file : str
"""
result["FileFormat"].GetFileExtension.func_doc = """**classmethod** GetFileExtension(s) -> str
Returns the file extension for path or file name ``s`` , without the
leading dot character.
Parameters
----------
s : str
"""
result["FileFormat"].FindAllFileFormatExtensions.func_doc = """**classmethod** FindAllFileFormatExtensions() -> set[str]
Returns a set containing the extension(s) corresponding to all
registered file formats.
"""
result["FileFormat"].FindById.func_doc = """**classmethod** FindById(formatId) -> FileFormat
Returns the file format instance with the specified ``formatId``
identifier.
If a format with a matching identifier is not found, this returns a
null file format pointer.
Parameters
----------
formatId : str
"""
result["FileFormat"].FindByExtension.func_doc = """**classmethod** FindByExtension(path, target) -> FileFormat
Returns the file format instance that supports the extension for
``path`` .
If a format with a matching extension is not found, this returns a
null file format pointer.
An extension may be handled by multiple file formats, but each with a
different target. In such cases, if no ``target`` is specified, the
file format that is registered as the primary plugin will be returned.
Otherwise, the file format whose target matches ``target`` will be
returned.
Parameters
----------
path : str
target : str
----------------------------------------------------------------------
FindByExtension(path, args) -> FileFormat
Returns a file format instance that supports the extension for
``path`` and whose target matches one of those specified by the given
``args`` .
If the ``args`` specify no target, then the file format that is
registered as the primary plugin will be returned. If a format with a
matching extension is not found, this returns a null file format
pointer.
Parameters
----------
path : str
args : FileFormatArguments
"""
result["Layer"].__doc__ = """
A scene description container that can combine with other such
containers to form simple component assets, and successively larger
aggregates. The contents of an SdfLayer adhere to the SdfData data
model. A layer can be ephemeral, or be an asset accessed and
serialized through the ArAsset and ArResolver interfaces.
The SdfLayer class provides a consistent API for accesing and
serializing scene description, using any data store provided by Ar
plugins. Sdf itself provides a UTF-8 text format for layers identified
by the".sdf"identifier extension, but via the SdfFileFormat
abstraction, allows downstream modules and plugins to adapt arbitrary
data formats to the SdfData/SdfLayer model.
The FindOrOpen() method returns a new SdfLayer object with scene
description from any supported asset format. Once read, a layer
remembers which asset it was read from. The Save() method saves the
layer back out to the original asset. You can use the Export() method
to write the layer to a different location. You can use the
GetIdentifier() method to get the layer's Id or GetRealPath() to get
the resolved, full URI.
Layers can have a timeCode range (startTimeCode and endTimeCode). This
range represents the suggested playback range, but has no impact on
the extent of the animation data that may be stored in the layer. The
metadatum"timeCodesPerSecond"is used to annotate how the time ordinate
for samples contained in the file scales to seconds. For example, if
timeCodesPerSecond is 24, then a sample at time ordinate 24 should be
viewed exactly one second after the sample at time ordinate 0.
"""
result["Layer"].GetFileFormat.func_doc = """GetFileFormat() -> FileFormat
Returns the file format used by this layer.
"""
result["Layer"].GetFileFormatArguments.func_doc = """GetFileFormatArguments() -> FileFormatArguments
Returns the file format-specific arguments used during the
construction of this layer.
"""
result["Layer"].StreamsData.func_doc = """StreamsData() -> bool
Returns true if this layer streams data from its serialized data store
on demand, false otherwise.
Layers with streaming data are treated differently to avoid pulling in
data unnecessarily. For example, reloading a streaming layer will not
perform fine-grained change notification, since doing so would require
the full contents of the layer to be loaded.
"""
result["Layer"].IsDetached.func_doc = """IsDetached() -> bool
Returns true if this layer is detached from its serialized data store,
false otherwise.
Detached layers are isolated from external changes to their serialized
data.
"""
result["Layer"].TransferContent.func_doc = """TransferContent(layer) -> None
Copies the content of the given layer into this layer.
Source layer is unmodified.
Parameters
----------
layer : Layer
"""
result["Layer"].CreateNew.func_doc = """**classmethod** CreateNew(identifier, args) -> Layer
Creates a new empty layer with the given identifier.
Additional arguments may be supplied via the ``args`` parameter. These
arguments may control behavior specific to the layer's file format.
Parameters
----------
identifier : str
args : FileFormatArguments
----------------------------------------------------------------------
CreateNew(fileFormat, identifier, args) -> Layer
Creates a new empty layer with the given identifier for a given file
format class.
This function has the same behavior as the other CreateNew function,
but uses the explicitly-specified ``fileFormat`` instead of attempting
to discern the format from ``identifier`` .
Parameters
----------
fileFormat : FileFormat
identifier : str
args : FileFormatArguments
"""
result["Layer"].New.func_doc = """**classmethod** New(fileFormat, identifier, args) -> Layer
Creates a new empty layer with the given identifier for a given file
format class.
The new layer will not be dirty and will not be saved.
Additional arguments may be supplied via the ``args`` parameter. These
arguments may control behavior specific to the layer's file format.
Parameters
----------
fileFormat : FileFormat
identifier : str
args : FileFormatArguments
"""
result["Layer"].FindOrOpen.func_doc = """**classmethod** FindOrOpen(identifier, args) -> Layer
Return an existing layer with the given ``identifier`` and ``args`` ,
or else load it.
If the layer can't be found or loaded, an error is posted and a null
layer is returned.
Arguments in ``args`` will override any arguments specified in
``identifier`` .
Parameters
----------
identifier : str
args : FileFormatArguments
"""
result["Layer"].FindOrOpenRelativeToLayer.func_doc = """**classmethod** FindOrOpenRelativeToLayer(anchor, identifier, args) -> Layer
Return an existing layer with the given ``identifier`` and ``args`` ,
or else load it.
The given ``identifier`` will be resolved relative to the ``anchor``
layer. If the layer can't be found or loaded, an error is posted and a
null layer is returned.
If the ``anchor`` layer is invalid, issues a coding error and returns
a null handle.
Arguments in ``args`` will override any arguments specified in
``identifier`` .
Parameters
----------
anchor : Layer
identifier : str
args : FileFormatArguments
"""
result["Layer"].OpenAsAnonymous.func_doc = """**classmethod** OpenAsAnonymous(layerPath, metadataOnly, tag) -> Layer
Load the given layer from disk as a new anonymous layer.
If the layer can't be found or loaded, an error is posted and a null
layer is returned.
The anonymous layer does not retain any knowledge of the backing file
on the filesystem.
``metadataOnly`` is a flag that asks for only the layer metadata to be
read in, which can be much faster if that is all that is required.
Note that this is just a hint: some FileFormat readers may disregard
this flag and still fully populate the layer contents.
An optional ``tag`` may be specified. See CreateAnonymous for details.
Parameters
----------
layerPath : str
metadataOnly : bool
tag : str
"""
result["Layer"].CreateAnonymous.func_doc = """**classmethod** CreateAnonymous(tag, args) -> Layer
Creates a new *anonymous* layer with an optional ``tag`` .
An anonymous layer is a layer with a system assigned identifier, that
cannot be saved to disk via Save() . Anonymous layers have an
identifier, but no real path or other asset information fields.
Anonymous layers may be tagged, which can be done to aid debugging
subsystems that make use of anonymous layers. The tag becomes the
display name of an anonymous layer, and is also included in the
generated identifier. Untagged anonymous layers have an empty display
name.
Additional arguments may be supplied via the ``args`` parameter. These
arguments may control behavior specific to the layer's file format.
Parameters
----------
tag : str
args : FileFormatArguments
----------------------------------------------------------------------
CreateAnonymous(tag, format, args) -> Layer
Create an anonymous layer with a specific ``format`` .
Parameters
----------
tag : str
format : FileFormat
args : FileFormatArguments
"""
result["Layer"].IsAnonymousLayerIdentifier.func_doc = """**classmethod** IsAnonymousLayerIdentifier(identifier) -> bool
Returns true if the ``identifier`` is an anonymous layer unique
identifier.
Parameters
----------
identifier : str
"""
result["Layer"].GetDisplayNameFromIdentifier.func_doc = """**classmethod** GetDisplayNameFromIdentifier(identifier) -> str
Returns the display name for the given ``identifier`` , using the same
rules as GetDisplayName.
Parameters
----------
identifier : str
"""
result["Layer"].Save.func_doc = """Save(force) -> bool
Returns ``true`` if successful, ``false`` if an error occurred.
Returns ``false`` if the layer has no remembered file name or the
layer type cannot be saved. The layer will not be overwritten if the
file exists and the layer is not dirty unless ``force`` is true.
Parameters
----------
force : bool
"""
result["Layer"].Export.func_doc = """Export(filename, comment, args) -> bool
Exports this layer to a file.
Returns ``true`` if successful, ``false`` if an error occurred.
If ``comment`` is not empty, the layer gets exported with the given
comment. Additional arguments may be supplied via the ``args``
parameter. These arguments may control behavior specific to the
exported layer's file format.
Note that the file name or comment of the original layer is not
updated. This only saves a copy of the layer to the given filename.
Subsequent calls to Save() will still save the layer to it's
previously remembered file name.
Parameters
----------
filename : str
comment : str
args : FileFormatArguments
"""
result["Layer"].ImportFromString.func_doc = """ImportFromString(string) -> bool
Reads this layer from the given string.
Returns ``true`` if successful, otherwise returns ``false`` .
Parameters
----------
string : str
"""
result["Layer"].Clear.func_doc = """Clear() -> None
Clears the layer of all content.
This restores the layer to a state as if it had just been created with
CreateNew() . This operation is Undo-able.
The fileName and whether journaling is enabled are not affected by
this method.
"""
result["Layer"].Reload.func_doc = """Reload(force) -> bool
Reloads the layer from its persistent representation.
This restores the layer to a state as if it had just been created with
FindOrOpen() . This operation is Undo-able.
The fileName and whether journaling is enabled are not affected by
this method.
When called with force = false (the default), Reload attempts to avoid
reloading layers that have not changed on disk. It does so by
comparing the file's modification time (mtime) to when the file was
loaded. If the layer has unsaved modifications, this mechanism is not
used, and the layer is reloaded from disk. If the layer has any
external asset dependencies their modification state will also be
consulted when determining if the layer needs to be reloaded.
Passing true to the ``force`` parameter overrides this behavior,
forcing the layer to be reloaded from disk regardless of whether it
has changed.
Parameters
----------
force : bool
"""
result["Layer"].Import.func_doc = """Import(layerPath) -> bool
Imports the content of the given layer path, replacing the content of
the current layer.
Note: If the layer path is the same as the current layer's real path,
no action is taken (and a warning occurs). For this case use Reload()
.
Parameters
----------
layerPath : str
"""
result["Layer"].ReloadLayers.func_doc = """**classmethod** ReloadLayers(layers, force) -> bool
Reloads the specified layers.
Returns ``false`` if one or more layers failed to reload.
See ``Reload()`` for a description of the ``force`` flag.
Parameters
----------
layers : set[Layer]
force : bool
"""
result["Layer"].UpdateExternalReference.func_doc = """UpdateExternalReference(oldAssetPath, newAssetPath) -> bool
Deprecated
Use UpdateCompositionAssetDependency instead.
Parameters
----------
oldAssetPath : str
newAssetPath : str
"""
result["Layer"].GetCompositionAssetDependencies.func_doc = """GetCompositionAssetDependencies() -> set[str]
Return paths of all assets this layer depends on due to composition
fields.
This includes the paths of all layers referred to by reference,
payload, and sublayer fields in this layer. This function only returns
direct composition dependencies of this layer, i.e. it does not
recurse to find composition dependencies from its dependent layer
assets.
"""
result["Layer"].UpdateCompositionAssetDependency.func_doc = """UpdateCompositionAssetDependency(oldAssetPath, newAssetPath) -> bool
Updates the asset path of a composation dependency in this layer.
If ``newAssetPath`` is supplied, the update works as"rename", updating
any occurrence of ``oldAssetPath`` to ``newAssetPath`` in all
reference, payload, and sublayer fields.
If ``newAssetPath`` is not given, this update behaves as a"delete",
removing all occurrences of ``oldAssetPath`` from all reference,
payload, and sublayer fields.
Parameters
----------
oldAssetPath : str
newAssetPath : str
"""
result["Layer"].GetExternalAssetDependencies.func_doc = """GetExternalAssetDependencies() -> set[str]
Returns a set of resolved paths to all external asset dependencies the
layer needs to generate its contents.
These are additional asset dependencies that are determined by the
layer's file format and will be consulted during Reload() when
determining if the layer needs to be reloaded. This specifically does
not include dependencies related to composition, i.e. this will not
include assets from references, payloads, and sublayers.
"""
result["Layer"].UpdateAssetInfo.func_doc = """UpdateAssetInfo() -> None
Update layer asset information.
Calling this method re-resolves the layer identifier, which updates
asset information such as the layer's resolved path and other asset
info. This may be used to update the layer after external changes to
the underlying asset system.
"""
result["Layer"].GetDisplayName.func_doc = """GetDisplayName() -> str
Returns the layer's display name.
The display name is the base filename of the identifier.
"""
result["Layer"].GetAssetName.func_doc = """GetAssetName() -> str
Returns the asset name associated with this layer.
"""
result["Layer"].GetAssetInfo.func_doc = """GetAssetInfo() -> VtValue
Returns resolve information from the last time the layer identifier
was resolved.
"""
result["Layer"].ComputeAbsolutePath.func_doc = """ComputeAbsolutePath(assetPath) -> str
Returns the path to the asset specified by ``assetPath`` using this
layer to anchor the path if necessary.
Returns ``assetPath`` if it's empty or an anonymous layer identifier.
This method can be used on asset paths that are authored in this layer
to create new asset paths that can be copied to other layers. These
new asset paths should refer to the same assets as the original asset
paths. For example, if the underlying ArResolver is filesystem-based
and ``assetPath`` is a relative filesystem path, this method might
return the absolute filesystem path using this layer's location as the
anchor.
The returned path should in general not be assumed to be an absolute
filesystem path or any other specific form. It is"absolute"in that it
should resolve to the same asset regardless of what layer it's
authored in.
Parameters
----------
assetPath : str
"""
result["Layer"].SplitIdentifier.func_doc = """**classmethod** SplitIdentifier(identifier, layerPath, arguments) -> bool
Splits the given layer identifier into its constituent layer path and
arguments.
Parameters
----------
identifier : str
layerPath : str
arguments : FileFormatArguments
"""
result["Layer"].CreateIdentifier.func_doc = """**classmethod** CreateIdentifier(layerPath, arguments) -> str
Joins the given layer path and arguments into an identifier.
Parameters
----------
layerPath : str
arguments : FileFormatArguments
"""
result["Layer"].Traverse.func_doc = """Traverse(path, func) -> None
Parameters
----------
path : Path
func : TraversalFunction
"""
result["Layer"].HasColorConfiguration.func_doc = """HasColorConfiguration() -> bool
Returns true if color configuration metadata is set in this layer.
GetColorConfiguration() , SetColorConfiguration()
"""
result["Layer"].ClearColorConfiguration.func_doc = """ClearColorConfiguration() -> None
Clears the color configuration metadata authored in this layer.
HasColorConfiguration() , SetColorConfiguration()
"""
result["Layer"].HasColorManagementSystem.func_doc = """HasColorManagementSystem() -> bool
Returns true if colorManagementSystem metadata is set in this layer.
GetColorManagementSystem() , SetColorManagementSystem()
"""
result["Layer"].ClearColorManagementSystem.func_doc = """ClearColorManagementSystem() -> None
Clears the'colorManagementSystem'metadata authored in this layer.
HascolorManagementSystem(), SetColorManagementSystem()
"""
result["Layer"].ClearDefaultPrim.func_doc = """ClearDefaultPrim() -> None
Clear the default prim metadata for this layer.
See GetDefaultPrim() and SetDefaultPrim() .
"""
result["Layer"].HasDefaultPrim.func_doc = """HasDefaultPrim() -> bool
Return true if the default prim metadata is set in this layer.
See GetDefaultPrim() and SetDefaultPrim() .
"""
result["Layer"].HasStartTimeCode.func_doc = """HasStartTimeCode() -> bool
Returns true if the layer has a startTimeCode opinion.
"""
result["Layer"].ClearStartTimeCode.func_doc = """ClearStartTimeCode() -> None
Clear the startTimeCode opinion.
"""
result["Layer"].HasEndTimeCode.func_doc = """HasEndTimeCode() -> bool
Returns true if the layer has an endTimeCode opinion.
"""
result["Layer"].ClearEndTimeCode.func_doc = """ClearEndTimeCode() -> None
Clear the endTimeCode opinion.
"""
result["Layer"].HasTimeCodesPerSecond.func_doc = """HasTimeCodesPerSecond() -> bool
Returns true if the layer has a timeCodesPerSecond opinion.
"""
result["Layer"].ClearTimeCodesPerSecond.func_doc = """ClearTimeCodesPerSecond() -> None
Clear the timeCodesPerSecond opinion.
"""
result["Layer"].HasFramesPerSecond.func_doc = """HasFramesPerSecond() -> bool
Returns true if the layer has a frames per second opinion.
"""
result["Layer"].ClearFramesPerSecond.func_doc = """ClearFramesPerSecond() -> None
Clear the framesPerSecond opinion.
"""
result["Layer"].HasFramePrecision.func_doc = """HasFramePrecision() -> bool
Returns true if the layer has a frames precision opinion.
"""
result["Layer"].ClearFramePrecision.func_doc = """ClearFramePrecision() -> None
Clear the framePrecision opinion.
"""
result["Layer"].HasOwner.func_doc = """HasOwner() -> bool
Returns true if the layer has an owner opinion.
"""
result["Layer"].ClearOwner.func_doc = """ClearOwner() -> None
Clear the owner opinion.
"""
result["Layer"].HasSessionOwner.func_doc = """HasSessionOwner() -> bool
Returns true if the layer has a session owner opinion.
"""
result["Layer"].ClearSessionOwner.func_doc = """ClearSessionOwner() -> None
"""
result["Layer"].HasCustomLayerData.func_doc = """HasCustomLayerData() -> bool
Returns true if CustomLayerData is authored on the layer.
"""
result["Layer"].ClearCustomLayerData.func_doc = """ClearCustomLayerData() -> None
Clears out the CustomLayerData dictionary associated with this layer.
"""
result["Layer"].ScheduleRemoveIfInert.func_doc = """ScheduleRemoveIfInert(spec) -> None
Cause ``spec`` to be removed if it no longer affects the scene when
the last change block is closed, or now if there are no change blocks.
Parameters
----------
spec : Spec
"""
result["Layer"].RemoveInertSceneDescription.func_doc = """RemoveInertSceneDescription() -> None
Removes all scene description in this layer that does not affect the
scene.
This method walks the layer namespace hierarchy and removes any prims
and that are not contributing any opinions.
"""
result["Layer"].ApplyRootPrimOrder.func_doc = """ApplyRootPrimOrder(vec) -> None
Reorders the given list of prim names according to the reorder
rootPrims statement for this layer.
This routine employs the standard list editing operations for ordered
items in a ListEditor.
Parameters
----------
vec : list[str]
"""
result["Layer"].SetDetachedLayerRules.func_doc = """**classmethod** SetDetachedLayerRules(mask) -> None
Sets the rules specifying detached layers.
Newly-created or opened layers whose identifiers are included in
``rules`` will be opened as detached layers. Existing layers that are
now included or no longer included will be reloaded. Any unsaved
modifications to those layers will be lost.
This function is not thread-safe. It may not be run concurrently with
any other functions that open, close, or read from any layers.
The detached layer rules are initially set to exclude all layers. This
may be overridden by setting the environment variables
SDF_LAYER_INCLUDE_DETACHED and SDF_LAYER_EXCLUDE_DETACHED to specify
the initial set of include and exclude patterns in the rules. These
variables can be set to a comma-delimited list of patterns.
SDF_LAYER_INCLUDE_DETACHED may also be set to"\\*"to include all
layers. Note that these environment variables only set the initial
state of the detached layer rules; these values may be overwritten by
subsequent calls to this function.
See SdfLayer::DetachedLayerRules::IsIncluded for details on how the
rules are applied to layer identifiers.
Parameters
----------
mask : DetachedLayerRules
"""
result["Layer"].GetDetachedLayerRules.func_doc = """**classmethod** GetDetachedLayerRules() -> DetachedLayerRules
Returns the current rules for the detached layer set.
"""
result["Layer"].IsIncludedByDetachedLayerRules.func_doc = """**classmethod** IsIncludedByDetachedLayerRules(identifier) -> bool
Returns whether the given layer identifier is included in the current
rules for the detached layer set.
This is equivalent to GetDetachedLayerRules() .IsIncluded(identifier).
Parameters
----------
identifier : str
"""
result["Layer"].IsMuted.func_doc = """**classmethod** IsMuted() -> bool
Returns ``true`` if the current layer is muted.
----------------------------------------------------------------------
IsMuted(path) -> bool
Returns ``true`` if the specified layer path is muted.
Parameters
----------
path : str
"""
result["Layer"].SetMuted.func_doc = """SetMuted(muted) -> None
Mutes the current layer if ``muted`` is ``true`` , and unmutes it
otherwise.
Parameters
----------
muted : bool
"""
result["Layer"].AddToMutedLayers.func_doc = """**classmethod** AddToMutedLayers(mutedPath) -> None
Add the specified path to the muted layers set.
Parameters
----------
mutedPath : str
"""
result["Layer"].RemoveFromMutedLayers.func_doc = """**classmethod** RemoveFromMutedLayers(mutedPath) -> None
Remove the specified path from the muted layers set.
Parameters
----------
mutedPath : str
"""
result["Layer"].GetObjectAtPath.func_doc = """GetObjectAtPath(path) -> Spec
Returns the object at the given ``path`` .
There is no distinction between an absolute and relative path at the
SdLayer level.
Returns ``None`` if there is no object at ``path`` .
Parameters
----------
path : Path
"""
result["Layer"].GetPrimAtPath.func_doc = """GetPrimAtPath(path) -> PrimSpec
Returns the prim at the given ``path`` .
Returns ``None`` if there is no prim at ``path`` . This is simply a
more specifically typed version of ``GetObjectAtPath()`` .
Parameters
----------
path : Path
"""
result["Layer"].GetPropertyAtPath.func_doc = """GetPropertyAtPath(path) -> PropertySpec
Returns a property at the given ``path`` .
Returns ``None`` if there is no property at ``path`` . This is simply
a more specifically typed version of ``GetObjectAtPath()`` .
Parameters
----------
path : Path
"""
result["Layer"].GetAttributeAtPath.func_doc = """GetAttributeAtPath(path) -> AttributeSpec
Returns an attribute at the given ``path`` .
Returns ``None`` if there is no attribute at ``path`` . This is simply
a more specifically typed version of ``GetObjectAtPath()`` .
Parameters
----------
path : Path
"""
result["Layer"].GetRelationshipAtPath.func_doc = """GetRelationshipAtPath(path) -> RelationshipSpec
Returns a relationship at the given ``path`` .
Returns ``None`` if there is no relationship at ``path`` . This is
simply a more specifically typed version of ``GetObjectAtPath()`` .
Parameters
----------
path : Path
"""
result["Layer"].SetPermissionToEdit.func_doc = """SetPermissionToEdit(allow) -> None
Sets permission to edit.
Parameters
----------
allow : bool
"""
result["Layer"].SetPermissionToSave.func_doc = """SetPermissionToSave(allow) -> None
Sets permission to save.
Parameters
----------
allow : bool
"""
result["Layer"].CanApply.func_doc = """CanApply(arg1, details) -> NamespaceEditDetail.Result
Check if a batch of namespace edits will succeed.
This returns ``SdfNamespaceEditDetail::Okay`` if they will succeed as
a batch, ``SdfNamespaceEditDetail::Unbatched`` if the edits will
succeed but will be applied unbatched, and
``SdfNamespaceEditDetail::Error`` if they will not succeed. No edits
will be performed in any case.
If ``details`` is not ``None`` and the method does not return ``Okay``
then details about the problems will be appended to ``details`` . A
problem may cause the method to return early, so ``details`` may not
list every problem.
Note that Sdf does not track backpointers so it's unable to fix up
targets/connections to namespace edited objects. Clients must fix
those to prevent them from falling off. In addition, this method will
report failure if any relational attribute with a target to a
namespace edited object is subsequently edited (in the same batch).
Clients should perform edits on relational attributes first.
Clients may wish to report unbatch details to the user to confirm that
the edits should be applied unbatched. This will give the user a
chance to correct any problems that cause batching to fail and try
again.
Parameters
----------
arg1 : BatchNamespaceEdit
details : list[SdfNamespaceEditDetail]
"""
result["Layer"].Apply.func_doc = """Apply(arg1) -> bool
Performs a batch of namespace edits.
Returns ``true`` on success and ``false`` on failure. On failure, no
namespace edits will have occurred.
Parameters
----------
arg1 : BatchNamespaceEdit
"""
result["Layer"].ListAllTimeSamples.func_doc = """ListAllTimeSamples() -> set[float]
"""
result["Layer"].ListTimeSamplesForPath.func_doc = """ListTimeSamplesForPath(path) -> set[float]
Parameters
----------
path : Path
"""
result["Layer"].GetBracketingTimeSamples.func_doc = """GetBracketingTimeSamples(time, tLower, tUpper) -> bool
Parameters
----------
time : float
tLower : float
tUpper : float
"""
result["Layer"].GetNumTimeSamplesForPath.func_doc = """GetNumTimeSamplesForPath(path) -> int
Parameters
----------
path : Path
"""
result["Layer"].GetBracketingTimeSamplesForPath.func_doc = """GetBracketingTimeSamplesForPath(path, time, tLower, tUpper) -> bool
Parameters
----------
path : Path
time : float
tLower : float
tUpper : float
"""
result["Layer"].QueryTimeSample.func_doc = """QueryTimeSample(path, time, value) -> bool
Parameters
----------
path : Path
time : float
value : VtValue
----------------------------------------------------------------------
QueryTimeSample(path, time, value) -> bool
Parameters
----------
path : Path
time : float
value : SdfAbstractDataValue
----------------------------------------------------------------------
QueryTimeSample(path, time, data) -> bool
Parameters
----------
path : Path
time : float
data : T
"""
result["Layer"].SetTimeSample.func_doc = """SetTimeSample(path, time, value) -> None
Parameters
----------
path : Path
time : float
value : VtValue
----------------------------------------------------------------------
SetTimeSample(path, time, value) -> None
Parameters
----------
path : Path
time : float
value : SdfAbstractDataConstValue
----------------------------------------------------------------------
SetTimeSample(path, time, value) -> None
Parameters
----------
path : Path
time : float
value : T
"""
result["Layer"].EraseTimeSample.func_doc = """EraseTimeSample(path, time) -> None
Parameters
----------
path : Path
time : float
"""
result["LayerOffset"].__doc__ = """
Represents a time offset and scale between layers.
The SdfLayerOffset class is an affine transform, providing both a
scale and a translate. It supports vector algebra semantics for
composing SdfLayerOffsets together via multiplication. The
SdfLayerOffset class is unitless: it does not refer to seconds or
frames.
For example, suppose layer A uses layer B, with an offset of X: when
bringing animation from B into A, you first apply the scale of X, and
then the offset. Suppose you have a scale of 2 and an offset of 24:
first multiply B's frame numbers by 2, and then add 24. The animation
from B as seen in A will take twice as long and start 24 frames later.
Offsets are typically used in either sublayers or prim references. For
more information, see the SetSubLayerOffset() method of the SdfLayer
class (the subLayerOffsets property in Python), as well as the
SetReference() and GetReferenceLayerOffset() methods (the latter is
the referenceLayerOffset property in Python) of the SdfPrimSpec class.
"""
result["LayerOffset"].__init__.func_doc = """__init__(offset, scale)
Constructs a new SdfLayerOffset instance.
Parameters
----------
offset : float
scale : float
"""
result["LayerOffset"].IsIdentity.func_doc = """IsIdentity() -> bool
Returns ``true`` if this is an identity transformation, with an offset
of 0.0 and a scale of 1.0.
"""
result["LayerOffset"].GetInverse.func_doc = """GetInverse() -> LayerOffset
Gets the inverse offset, which performs the opposite transformation.
"""
result["LayerTree"].__doc__ = """
A SdfLayerTree is an immutable tree structure representing a sublayer
stack and its recursive structure.
Layers can have sublayers, which can in turn have sublayers of their
own. Clients that want to represent that hierarchical structure in
memory can build a SdfLayerTree for that purpose.
We use TfRefPtr<SdfLayerTree> as handles to LayerTrees, as a simple
way to pass them around as immutable trees without worrying about
lifetime.
"""
result["LayerTree"].__init__.func_doc = """__init__(layer, childTrees, cumulativeOffset)
Parameters
----------
layer : Layer
childTrees : list[SdfLayerTreeHandle]
cumulativeOffset : LayerOffset
"""
result["NamespaceEdit"].__doc__ = """
A single namespace edit. It supports renaming, reparenting,
reparenting with a rename, reordering, and removal.
"""
result["NamespaceEdit"].__init__.func_doc = """__init__()
The default edit maps the empty path to the empty path.
----------------------------------------------------------------------
__init__(currentPath_, newPath_, index_)
The fully general edit.
Parameters
----------
currentPath_ : Path
newPath_ : Path
index_ : Index
"""
result["NamespaceEdit"].Remove.func_doc = """**classmethod** Remove(currentPath) -> This
Returns a namespace edit that removes the object at ``currentPath`` .
Parameters
----------
currentPath : Path
"""
result["NamespaceEdit"].Rename.func_doc = """**classmethod** Rename(currentPath, name) -> This
Returns a namespace edit that renames the prim or property at
``currentPath`` to ``name`` .
Parameters
----------
currentPath : Path
name : str
"""
result["NamespaceEdit"].Reorder.func_doc = """**classmethod** Reorder(currentPath, index) -> This
Returns a namespace edit to reorder the prim or property at
``currentPath`` to index ``index`` .
Parameters
----------
currentPath : Path
index : Index
"""
result["NamespaceEdit"].Reparent.func_doc = """**classmethod** Reparent(currentPath, newParentPath, index) -> This
Returns a namespace edit to reparent the prim or property at
``currentPath`` to be under ``newParentPath`` at index ``index`` .
Parameters
----------
currentPath : Path
newParentPath : Path
index : Index
"""
result["NamespaceEdit"].ReparentAndRename.func_doc = """**classmethod** ReparentAndRename(currentPath, newParentPath, name, index) -> This
Returns a namespace edit to reparent the prim or property at
``currentPath`` to be under ``newParentPath`` at index ``index`` with
the name ``name`` .
Parameters
----------
currentPath : Path
newParentPath : Path
name : str
index : Index
"""
result["NamespaceEditDetail"].__doc__ = """
Detailed information about a namespace edit.
"""
result["NamespaceEditDetail"].Result.__doc__ = """
Validity of an edit.
"""
result["NamespaceEditDetail"].__init__.func_doc = """__init__()
----------------------------------------------------------------------
__init__(arg1, edit, reason)
Parameters
----------
arg1 : Result
edit : NamespaceEdit
reason : str
"""
result["Notice"].__doc__ = """
Wrapper class for Sdf notices.
"""
result["Path"].__doc__ = """
A path value used to locate objects in layers or scenegraphs.
Overview
========
SdfPath is used in several ways:
- As a storage key for addressing and accessing values held in a
SdfLayer
- As a namespace identity for scenegraph objects
- As a way to refer to other scenegraph objects through relative
paths
The paths represented by an SdfPath class may be either relative or
absolute. Relative paths are relative to the prim object that contains
them (that is, if an SdfRelationshipSpec target is relative, it is
relative to the SdfPrimSpec object that owns the SdfRelationshipSpec
object).
SdfPath objects can be readily created from and converted back to
strings, but as SdfPath objects, they have behaviors that make it easy
and efficient to work with them. The SdfPath class provides a full
range of methods for manipulating scene paths by appending a namespace
child, appending a relationship target, getting the parent path, and
so on. Since the SdfPath class uses a node-based representation
internally, you should use the editing functions rather than
converting to and from strings if possible.
Path Syntax
===========
Like a filesystem path, an SdfPath is conceptually just a sequence of
path components. Unlike a filesystem path, each component has a type,
and the type is indicated by the syntax.
Two separators are used between parts of a path. A slash ("/")
following an identifier is used to introduce a namespace child. A
period (".") following an identifier is used to introduce a property.
A property may also have several non-sequential colons (':') in its
name to provide a rudimentary namespace within properties but may not
end or begin with a colon.
A leading slash in the string representation of an SdfPath object
indicates an absolute path. Two adjacent periods indicate the parent
namespace.
Brackets ("["and"]") are used to indicate relationship target paths
for relational attributes.
The first part in a path is assumed to be a namespace child unless it
is preceded by a period. That means:
- ``/Foo`` is an absolute path specifying the root prim Foo.
- ``/Foo/Bar`` is an absolute path specifying namespace child Bar
of root prim Foo.
- ``/Foo/Bar.baz`` is an absolute path specifying property ``baz``
of namespace child Bar of root prim Foo.
- ``Foo`` is a relative path specifying namespace child Foo of the
current prim.
- ``Foo/Bar`` is a relative path specifying namespace child Bar of
namespace child Foo of the current prim.
- ``Foo/Bar.baz`` is a relative path specifying property ``baz`` of
namespace child Bar of namespace child Foo of the current prim.
- ``.foo`` is a relative path specifying the property ``foo`` of
the current prim.
- ``/Foo.bar[/Foo.baz].attrib`` is a relational attribute path. The
relationship ``/Foo.bar`` has a target ``/Foo.baz`` . There is a
relational attribute ``attrib`` on that relationship->target pair.
A Note on Thread-Safety
=======================
SdfPath is strongly thread-safe, in the sense that zero additional
synchronization is required between threads creating or using SdfPath
values. Just like TfToken, SdfPath values are immutable. Internally,
SdfPath uses a global prefix tree to efficiently share representations
of paths, and provide fast equality/hashing operations, but
modifications to this table are internally synchronized. Consequently,
as with TfToken, for best performance it is important to minimize the
number of values created (since it requires synchronized access to
this table) or copied (since it requires atomic ref-counting
operations).
"""
result["Path"].__init__.func_doc = """__init__()
Constructs the default, empty path.
----------------------------------------------------------------------
__init__(path)
Creates a path from the given string.
If the given string is not a well-formed path, this will raise a Tf
error. Note that passing an empty std::string() will also raise an
error; the correct way to get the empty path is SdfPath() .
Internal dot-dots will be resolved by removing the first dot-dot, the
element preceding it, and repeating until no internal dot-dots remain.
Note that most often new paths are expected to be created by asking
existing paths to return modified versions of themselves.
Parameters
----------
path : str
----------------------------------------------------------------------
__init__(primNode)
Parameters
----------
primNode : Sdf_PathPrimNode
----------------------------------------------------------------------
__init__(primPart, propPart)
Parameters
----------
primPart : Sdf_PathPrimNode
propPart : Sdf_PathPropNode
----------------------------------------------------------------------
__init__(primPart, propPart)
Parameters
----------
primPart : Sdf_PathNode
propPart : Sdf_PathNode
"""
result["Path"].IsAbsolutePath.func_doc = """IsAbsolutePath() -> bool
Returns whether the path is absolute.
"""
result["Path"].IsAbsoluteRootPath.func_doc = """IsAbsoluteRootPath() -> bool
Return true if this path is the AbsoluteRootPath() .
"""
result["Path"].IsPrimPath.func_doc = """IsPrimPath() -> bool
Returns whether the path identifies a prim.
"""
result["Path"].IsAbsoluteRootOrPrimPath.func_doc = """IsAbsoluteRootOrPrimPath() -> bool
Returns whether the path identifies a prim or the absolute root.
"""
result["Path"].IsRootPrimPath.func_doc = """IsRootPrimPath() -> bool
Returns whether the path identifies a root prim.
the path must be absolute and have a single element (for example
``/foo`` ).
"""
result["Path"].IsPropertyPath.func_doc = """IsPropertyPath() -> bool
Returns whether the path identifies a property.
A relational attribute is considered to be a property, so this method
will return true for relational attributes as well as properties of
prims.
"""
result["Path"].IsPrimPropertyPath.func_doc = """IsPrimPropertyPath() -> bool
Returns whether the path identifies a prim's property.
A relational attribute is not a prim property.
"""
result["Path"].IsNamespacedPropertyPath.func_doc = """IsNamespacedPropertyPath() -> bool
Returns whether the path identifies a namespaced property.
A namespaced property has colon embedded in its name.
"""
result["Path"].IsPrimVariantSelectionPath.func_doc = """IsPrimVariantSelectionPath() -> bool
Returns whether the path identifies a variant selection for a prim.
"""
result["Path"].ContainsPrimVariantSelection.func_doc = """ContainsPrimVariantSelection() -> bool
Returns whether the path or any of its parent paths identifies a
variant selection for a prim.
"""
result["Path"].ContainsPropertyElements.func_doc = """ContainsPropertyElements() -> bool
Return true if this path contains any property elements, false
otherwise.
A false return indicates a prim-like path, specifically a root path, a
prim path, or a prim variant selection path. A true return indicates a
property-like path: a prim property path, a target path, a relational
attribute path, etc.
"""
result["Path"].ContainsTargetPath.func_doc = """ContainsTargetPath() -> bool
Return true if this path is or has a prefix that's a target path or a
mapper path.
"""
result["Path"].IsRelationalAttributePath.func_doc = """IsRelationalAttributePath() -> bool
Returns whether the path identifies a relational attribute.
If this is true, IsPropertyPath() will also be true.
"""
result["Path"].IsTargetPath.func_doc = """IsTargetPath() -> bool
Returns whether the path identifies a relationship or connection
target.
"""
result["Path"].IsMapperPath.func_doc = """IsMapperPath() -> bool
Returns whether the path identifies a connection mapper.
"""
result["Path"].IsMapperArgPath.func_doc = """IsMapperArgPath() -> bool
Returns whether the path identifies a connection mapper arg.
"""
result["Path"].IsExpressionPath.func_doc = """IsExpressionPath() -> bool
Returns whether the path identifies a connection expression.
"""
result["Path"].GetAncestorsRange.func_doc = """GetAncestorsRange() -> SdfPathAncestorsRange
Return a range for iterating over the ancestors of this path.
The range provides iteration over the prefixes of a path, ordered from
longest to shortest (the opposite of the order of the prefixes
returned by GetPrefixes).
"""
result["Path"].ReplaceName.func_doc = """ReplaceName(newName) -> Path
Return a copy of this path with its final component changed to
*newName*.
This path must be a prim or property path.
This method is shorthand for path.GetParentPath().AppendChild(newName)
for prim paths, path.GetParentPath().AppendProperty(newName) for prim
property paths, and
path.GetParentPath().AppendRelationalAttribute(newName) for relational
attribute paths.
Note that only the final path component is ever changed. If the name
of the final path component appears elsewhere in the path, it will not
be modified.
Some examples:
ReplaceName('/chars/MeridaGroup','AngusGroup')
\\->'/chars/AngusGroup'ReplaceName('/Merida.tx','ty')
\\->'/Merida.ty'ReplaceName('/Merida.tx[targ].tx','ty')
\\->'/Merida.tx[targ].ty'
Parameters
----------
newName : str
"""
result["Path"].GetAllTargetPathsRecursively.func_doc = """GetAllTargetPathsRecursively(result) -> None
Returns all the relationship target or connection target paths
contained in this path, and recursively all the target paths contained
in those target paths in reverse depth-first order.
For example, given the
path:'/A/B.a[/C/D.a[/E/F.a]].a[/A/B.a[/C/D.a]]'this method
produces:'/A/B.a[/C/D.a]','/C/D.a','/C/D.a[/E/F.a]','/E/F.a'
Parameters
----------
result : list[SdfPath]
"""
result["Path"].GetVariantSelection.func_doc = """GetVariantSelection() -> tuple[str, str]
Returns the variant selection for this path, if this is a variant
selection path.
Returns a pair of empty strings if this path is not a variant
selection path.
"""
result["Path"].HasPrefix.func_doc = """HasPrefix(prefix) -> bool
Return true if both this path and *prefix* are not the empty path and
this path has *prefix* as a prefix.
Return false otherwise.
Parameters
----------
prefix : Path
"""
result["Path"].GetParentPath.func_doc = """GetParentPath() -> Path
Return the path that identifies this path's namespace parent.
For a prim path (like'/foo/bar'), return the prim's parent's path
('/foo'). For a prim property path (like'/foo/bar.property'), return
the prim's path ('/foo/bar'). For a target path
(like'/foo/bar.property[/target]') return the property path
('/foo/bar.property'). For a mapper path
(like'/foo/bar.property.mapper[/target]') return the property path
('/foo/bar.property). For a relational attribute path
(like'/foo/bar.property[/target].relAttr') return the relationship
target's path ('/foo/bar.property[/target]'). For a prim variant
selection path (like'/foo/bar{var=sel}') return the prim path
('/foo/bar'). For a root prim path (like'/rootPrim'), return
AbsoluteRootPath() ('/'). For a single element relative prim path
(like'relativePrim'), return ReflexiveRelativePath() ('.'). For
ReflexiveRelativePath() , return the relative parent path ('\\.\\.').
Note that the parent path of a relative parent path ('\\.\\.') is a
relative grandparent path ('\\.\\./\\.\\.'). Use caution writing loops
that walk to parent paths since relative paths have infinitely many
ancestors. To more safely traverse ancestor paths, consider iterating
over an SdfPathAncestorsRange instead, as returend by
GetAncestorsRange() .
"""
result["Path"].GetPrimPath.func_doc = """GetPrimPath() -> Path
Creates a path by stripping all relational attributes, targets,
properties, and variant selections from the leafmost prim path,
leaving the nearest path for which *IsPrimPath()* returns true.
See *GetPrimOrPrimVariantSelectionPath* also.
If the path is already a prim path, the same path is returned.
"""
result["Path"].GetPrimOrPrimVariantSelectionPath.func_doc = """GetPrimOrPrimVariantSelectionPath() -> Path
Creates a path by stripping all relational attributes, targets, and
properties, leaving the nearest path for which
*IsPrimOrPrimVariantSelectionPath()* returns true.
See *GetPrimPath* also.
If the path is already a prim or a prim variant selection path, the
same path is returned.
"""
result["Path"].GetAbsoluteRootOrPrimPath.func_doc = """GetAbsoluteRootOrPrimPath() -> Path
Creates a path by stripping all properties and relational attributes
from this path, leaving the path to the containing prim.
If the path is already a prim or absolute root path, the same path is
returned.
"""
result["Path"].StripAllVariantSelections.func_doc = """StripAllVariantSelections() -> Path
Create a path by stripping all variant selections from all components
of this path, leaving a path with no embedded variant selections.
"""
result["Path"].AppendPath.func_doc = """AppendPath(newSuffix) -> Path
Creates a path by appending a given relative path to this path.
If the newSuffix is a prim path, then this path must be a prim path or
a root path.
If the newSuffix is a prim property path, then this path must be a
prim path or the ReflexiveRelativePath.
Parameters
----------
newSuffix : Path
"""
result["Path"].AppendChild.func_doc = """AppendChild(childName) -> Path
Creates a path by appending an element for ``childName`` to this path.
This path must be a prim path, the AbsoluteRootPath or the
ReflexiveRelativePath.
Parameters
----------
childName : str
"""
result["Path"].AppendProperty.func_doc = """AppendProperty(propName) -> Path
Creates a path by appending an element for ``propName`` to this path.
This path must be a prim path or the ReflexiveRelativePath.
Parameters
----------
propName : str
"""
result["Path"].AppendVariantSelection.func_doc = """AppendVariantSelection(variantSet, variant) -> Path
Creates a path by appending an element for ``variantSet`` and
``variant`` to this path.
This path must be a prim path.
Parameters
----------
variantSet : str
variant : str
"""
result["Path"].AppendTarget.func_doc = """AppendTarget(targetPath) -> Path
Creates a path by appending an element for ``targetPath`` .
This path must be a prim property or relational attribute path.
Parameters
----------
targetPath : Path
"""
result["Path"].AppendRelationalAttribute.func_doc = """AppendRelationalAttribute(attrName) -> Path
Creates a path by appending an element for ``attrName`` to this path.
This path must be a target path.
Parameters
----------
attrName : str
"""
result["Path"].ReplaceTargetPath.func_doc = """ReplaceTargetPath(newTargetPath) -> Path
Replaces the relational attribute's target path.
The path must be a relational attribute path.
Parameters
----------
newTargetPath : Path
"""
result["Path"].AppendMapper.func_doc = """AppendMapper(targetPath) -> Path
Creates a path by appending a mapper element for ``targetPath`` .
This path must be a prim property or relational attribute path.
Parameters
----------
targetPath : Path
"""
result["Path"].AppendMapperArg.func_doc = """AppendMapperArg(argName) -> Path
Creates a path by appending an element for ``argName`` .
This path must be a mapper path.
Parameters
----------
argName : str
"""
result["Path"].AppendExpression.func_doc = """AppendExpression() -> Path
Creates a path by appending an expression element.
This path must be a prim property or relational attribute path.
"""
result["Path"].AppendElementString.func_doc = """AppendElementString(element) -> Path
Creates a path by extracting and appending an element from the given
ascii element encoding.
Attempting to append a root or empty path (or malformed path) or
attempting to append *to* the EmptyPath will raise an error and return
the EmptyPath.
May also fail and return EmptyPath if this path's type cannot possess
a child of the type encoded in ``element`` .
Parameters
----------
element : str
"""
result["Path"].ReplacePrefix.func_doc = """ReplacePrefix(oldPrefix, newPrefix, fixTargetPaths) -> Path
Returns a path with all occurrences of the prefix path ``oldPrefix``
replaced with the prefix path ``newPrefix`` .
If fixTargetPaths is true, any embedded target paths will also have
their paths replaced. This is the default.
If this is not a target, relational attribute or mapper path this will
do zero or one path prefix replacements, if not the number of
replacements can be greater than one.
Parameters
----------
oldPrefix : Path
newPrefix : Path
fixTargetPaths : bool
"""
result["Path"].GetCommonPrefix.func_doc = """GetCommonPrefix(path) -> Path
Returns a path with maximal length that is a prefix path of both this
path and ``path`` .
Parameters
----------
path : Path
"""
result["Path"].RemoveCommonSuffix.func_doc = """RemoveCommonSuffix(otherPath, stopAtRootPrim) -> tuple[Path, Path]
Find and remove the longest common suffix from two paths.
Returns this path and ``otherPath`` with the longest common suffix
removed (first and second, respectively). If the two paths have no
common suffix then the paths are returned as-is. If the paths are
equal then this returns empty paths for relative paths and absolute
roots for absolute paths. The paths need not be the same length.
If ``stopAtRootPrim`` is ``true`` then neither returned path will be
the root path. That, in turn, means that some common suffixes will not
be removed. For example, if ``stopAtRootPrim`` is ``true`` then the
paths /A/B and /B will be returned as is. Were it ``false`` then the
result would be /A and /. Similarly paths /A/B/C and /B/C would return
/A/B and /B if ``stopAtRootPrim`` is ``true`` but /A and / if it's
``false`` .
Parameters
----------
otherPath : Path
stopAtRootPrim : bool
"""
result["Path"].MakeAbsolutePath.func_doc = """MakeAbsolutePath(anchor) -> Path
Returns the absolute form of this path using ``anchor`` as the
relative basis.
``anchor`` must be an absolute prim path.
If this path is a relative path, resolve it using ``anchor`` as the
relative basis.
If this path is already an absolute path, just return a copy.
Parameters
----------
anchor : Path
"""
result["Path"].MakeRelativePath.func_doc = """MakeRelativePath(anchor) -> Path
Returns the relative form of this path using ``anchor`` as the
relative basis.
``anchor`` must be an absolute prim path.
If this path is an absolute path, return the corresponding relative
path that is relative to the absolute path given by ``anchor`` .
If this path is a relative path, return the optimal relative path to
the absolute path given by ``anchor`` . (The optimal relative path
from a given prim path is the relative path with the least leading
dot-dots.
Parameters
----------
anchor : Path
"""
result["Path"].IsValidIdentifier.func_doc = """**classmethod** IsValidIdentifier(name) -> bool
Returns whether ``name`` is a legal identifier for any path component.
Parameters
----------
name : str
"""
result["Path"].IsValidNamespacedIdentifier.func_doc = """**classmethod** IsValidNamespacedIdentifier(name) -> bool
Returns whether ``name`` is a legal namespaced identifier.
This returns ``true`` if IsValidIdentifier() does.
Parameters
----------
name : str
"""
result["Path"].TokenizeIdentifier.func_doc = """**classmethod** TokenizeIdentifier(name) -> list[str]
Tokenizes ``name`` by the namespace delimiter.
Returns the empty vector if ``name`` is not a valid namespaced
identifier.
Parameters
----------
name : str
"""
result["Path"].JoinIdentifier.func_doc = """**classmethod** JoinIdentifier(names) -> str
Join ``names`` into a single identifier using the namespace delimiter.
Any empty strings present in ``names`` are ignored when joining.
Parameters
----------
names : list[str]
----------------------------------------------------------------------
JoinIdentifier(names) -> str
Join ``names`` into a single identifier using the namespace delimiter.
Any empty strings present in ``names`` are ignored when joining.
Parameters
----------
names : list[TfToken]
----------------------------------------------------------------------
JoinIdentifier(lhs, rhs) -> str
Join ``lhs`` and ``rhs`` into a single identifier using the namespace
delimiter.
Returns ``lhs`` if ``rhs`` is empty and vice verse. Returns an empty
string if both ``lhs`` and ``rhs`` are empty.
Parameters
----------
lhs : str
rhs : str
----------------------------------------------------------------------
JoinIdentifier(lhs, rhs) -> str
Join ``lhs`` and ``rhs`` into a single identifier using the namespace
delimiter.
Returns ``lhs`` if ``rhs`` is empty and vice verse. Returns an empty
string if both ``lhs`` and ``rhs`` are empty.
Parameters
----------
lhs : str
rhs : str
"""
result["Path"].StripNamespace.func_doc = """**classmethod** StripNamespace(name) -> str
Returns ``name`` stripped of any namespaces.
This does not check the validity of the name; it just attempts to
remove anything that looks like a namespace.
Parameters
----------
name : str
----------------------------------------------------------------------
StripNamespace(name) -> str
Returns ``name`` stripped of any namespaces.
This does not check the validity of the name; it just attempts to
remove anything that looks like a namespace.
Parameters
----------
name : str
"""
result["Path"].StripPrefixNamespace.func_doc = """**classmethod** StripPrefixNamespace(name, matchNamespace) -> tuple[str, bool]
Returns ( ``name`` , ``true`` ) where ``name`` is stripped of the
prefix specified by ``matchNamespace`` if ``name`` indeed starts with
``matchNamespace`` .
Returns ( ``name`` , ``false`` ) otherwise, with ``name`` unmodified.
This function deals with both the case where ``matchNamespace``
contains the trailing namespace delimiter':'or not.
Parameters
----------
name : str
matchNamespace : str
"""
result["Path"].IsValidPathString.func_doc = """**classmethod** IsValidPathString(pathString, errMsg) -> bool
Return true if ``pathString`` is a valid path string, meaning that
passing the string to the *SdfPath* constructor will result in a
valid, non-empty SdfPath.
Otherwise, return false and if ``errMsg`` is not None, set the
pointed-to string to the parse error.
Parameters
----------
pathString : str
errMsg : str
"""
result["Path"].GetConciseRelativePaths.func_doc = """**classmethod** GetConciseRelativePaths(paths) -> list[SdfPath]
Given some vector of paths, get a vector of concise unambiguous
relative paths.
GetConciseRelativePaths requires a vector of absolute paths. It finds
a set of relative paths such that each relative path is unique.
Parameters
----------
paths : list[SdfPath]
"""
result["Path"].RemoveDescendentPaths.func_doc = """**classmethod** RemoveDescendentPaths(paths) -> None
Remove all elements of *paths* that are prefixed by other elements in
*paths*.
As a side-effect, the result is left in sorted order.
Parameters
----------
paths : list[SdfPath]
"""
result["Path"].RemoveAncestorPaths.func_doc = """**classmethod** RemoveAncestorPaths(paths) -> None
Remove all elements of *paths* that prefix other elements in *paths*.
As a side-effect, the result is left in sorted order.
Parameters
----------
paths : list[SdfPath]
"""
result["Payload"].__doc__ = """
Represents a payload and all its meta data.
A payload represents a prim reference to an external layer. A payload
is similar to a prim reference (see SdfReference) with the major
difference that payloads are explicitly loaded by the user.
Unloaded payloads represent a boundary that lazy composition and
system behaviors will not traverse across, providing a user-visible
way to manage the working set of the scene.
"""
result["Payload"].__init__.func_doc = """__init__(assetPath, primPath, layerOffset)
Create a payload.
See SdfAssetPath for what characters are valid in ``assetPath`` . If
``assetPath`` contains invalid characters, issue an error and set this
payload's asset path to the empty asset path.
Parameters
----------
assetPath : str
primPath : Path
layerOffset : LayerOffset
"""
result["PrimSpec"].__doc__ = """
Represents a prim description in an SdfLayer object.
Every SdfPrimSpec object is defined in a layer. It is identified by
its path (SdfPath class) in the namespace hierarchy of its layer.
SdfPrimSpecs can be created using the New() method as children of
either the containing SdfLayer itself (for"root level"prims), or as
children of other SdfPrimSpec objects to extend a hierarchy. The
helper function SdfCreatePrimInLayer() can be used to quickly create a
hierarchy of primSpecs.
SdfPrimSpec objects have properties of two general types: attributes
(containing values) and relationships (different types of connections
to other prims and attributes). Attributes are represented by the
SdfAttributeSpec class and relationships by the SdfRelationshipSpec
class. Each prim has its own namespace of properties. Properties are
stored and accessed by their name.
SdfPrimSpec objects have a typeName, permission restriction, and they
reference and inherit prim paths. Permission restrictions control
which other layers may refer to, or express opinions about a prim. See
the SdfPermission class for more information.
- Insert doc about references and inherits here.
- Should have validate\\.\\.\\. methods for name, children,
properties
"""
result["PrimSpec"].CanSetName.func_doc = """CanSetName(newName, whyNot) -> bool
Returns true if setting the prim spec's name to ``newName`` will
succeed.
Returns false if it won't, and sets ``whyNot`` with a string
describing why not.
Parameters
----------
newName : str
whyNot : str
"""
result["PrimSpec"].ApplyNameChildrenOrder.func_doc = """ApplyNameChildrenOrder(vec) -> None
Reorders the given list of child names according to the reorder
nameChildren statement for this prim.
This routine employs the standard list editing operation for ordered
items in a ListEditor.
Parameters
----------
vec : list[str]
"""
result["PrimSpec"].RemoveProperty.func_doc = """RemoveProperty(property) -> None
Removes the property.
Parameters
----------
property : PropertySpec
"""
result["PrimSpec"].ApplyPropertyOrder.func_doc = """ApplyPropertyOrder(vec) -> None
Reorders the given list of property names according to the reorder
properties statement for this prim.
This routine employs the standard list editing operation for ordered
items in a ListEditor.
Parameters
----------
vec : list[str]
"""
result["PrimSpec"].GetPrimAtPath.func_doc = """GetPrimAtPath(path) -> PrimSpec
Returns a prim given its ``path`` .
Returns invalid handle if there is no prim at ``path`` . This is
simply a more specifically typed version of GetObjectAtPath.
Parameters
----------
path : Path
"""
result["PrimSpec"].GetPropertyAtPath.func_doc = """GetPropertyAtPath(path) -> PropertySpec
Returns a property given its ``path`` .
Returns invalid handle if there is no property at ``path`` . This is
simply a more specifically typed version of GetObjectAtPath.
Parameters
----------
path : Path
"""
result["PrimSpec"].GetAttributeAtPath.func_doc = """GetAttributeAtPath(path) -> AttributeSpec
Returns an attribute given its ``path`` .
Returns invalid handle if there is no attribute at ``path`` . This is
simply a more specifically typed version of GetObjectAtPath.
Parameters
----------
path : Path
"""
result["PrimSpec"].GetRelationshipAtPath.func_doc = """GetRelationshipAtPath(path) -> RelationshipSpec
Returns a relationship given its ``path`` .
Returns invalid handle if there is no relationship at ``path`` . This
is simply a more specifically typed version of GetObjectAtPath.
Parameters
----------
path : Path
"""
result["PrimSpec"].HasActive.func_doc = """HasActive() -> bool
Returns true if this prim spec has an opinion about active.
"""
result["PrimSpec"].ClearActive.func_doc = """ClearActive() -> None
Removes the active opinion in this prim spec if there is one.
"""
result["PrimSpec"].HasKind.func_doc = """HasKind() -> bool
Returns true if this prim spec has an opinion about kind.
"""
result["PrimSpec"].ClearKind.func_doc = """ClearKind() -> None
Remove the kind opinion from this prim spec if there is one.
"""
result["PrimSpec"].HasInstanceable.func_doc = """HasInstanceable() -> bool
Returns true if this prim spec has a value authored for its
instanceable flag, false otherwise.
"""
result["PrimSpec"].ClearInstanceable.func_doc = """ClearInstanceable() -> None
Clears the value for the prim's instanceable flag.
"""
result["PrimSpec"].GetVariantNames.func_doc = """GetVariantNames(name) -> list[str]
Returns list of variant names for the given variant set.
Parameters
----------
name : str
"""
result["PrimSpec"].BlockVariantSelection.func_doc = """BlockVariantSelection(variantSetName) -> None
Blocks the variant selected for the given variant set by setting the
variant selection to empty.
Parameters
----------
variantSetName : str
"""
result["PropertySpec"].__doc__ = """
Base class for SdfAttributeSpec and SdfRelationshipSpec.
Scene Spec Attributes (SdfAttributeSpec) and Relationships
(SdfRelationshipSpec) are the basic properties that make up Scene Spec
Prims (SdfPrimSpec). They share many qualities and can sometimes be
treated uniformly. The common qualities are provided by this base
class.
NOTE: Do not use Python reserved words and keywords as attribute
names. This will cause attribute resolution to fail.
"""
result["PropertySpec"].HasDefaultValue.func_doc = """HasDefaultValue() -> bool
Returns true if a default value is set for this attribute.
"""
result["PropertySpec"].ClearDefaultValue.func_doc = """ClearDefaultValue() -> None
Clear the attribute's default value.
"""
result["PseudoRootSpec"].__doc__ = """"""
result["Reference"].__doc__ = """
Represents a reference and all its meta data.
A reference is expressed on a prim in a given layer and it identifies
a prim in a layer stack. All opinions in the namespace hierarchy under
the referenced prim will be composed with the opinions in the
namespace hierarchy under the referencing prim.
The asset path specifies the layer stack being referenced. If this
asset path is non-empty, this reference is considered
an'external'reference to the layer stack rooted at the specified
layer. If this is empty, this reference is considered
an'internal'reference to the layer stack containing (but not
necessarily rooted at) the layer where the reference is authored.
The prim path specifies the prim in the referenced layer stack from
which opinions will be composed. If this prim path is empty, it will
be considered a reference to the default prim specified in the root
layer of the referenced layer stack see SdfLayer::GetDefaultPrim.
The meta data for a reference is its layer offset and custom data. The
layer offset is an affine transformation applied to all anim splines
in the referenced prim's namespace hierarchy, see SdfLayerOffset for
details. Custom data is for use by plugins or other non-tools supplied
extensions that need to be able to store data associated with
references.
"""
result["Reference"].__init__.func_doc = """__init__(assetPath, primPath, layerOffset, customData)
Creates a reference with all its meta data.
The default reference is an internal reference to the default prim.
See SdfAssetPath for what characters are valid in ``assetPath`` . If
``assetPath`` contains invalid characters, issue an error and set this
reference's asset path to the empty asset path.
Parameters
----------
assetPath : str
primPath : Path
layerOffset : LayerOffset
customData : VtDictionary
"""
result["Reference"].IsInternal.func_doc = """IsInternal() -> bool
Returns ``true`` in the case of an internal reference.
An internal reference is a reference with an empty asset path.
"""
result["RelationshipSpec"].__doc__ = """
A property that contains a reference to one or more SdfPrimSpec
instances.
A relationship may refer to one or more target prims or attributes.
All targets of a single relationship are considered to be playing the
same role. Note that ``role`` does not imply that the target prims or
attributes are of the same ``type`` .
Relationships may be annotated with relational attributes. Relational
attributes are named SdfAttributeSpec objects containing values that
describe the relationship. For example, point weights are commonly
expressed as relational attributes.
"""
result["RelationshipSpec"].ReplaceTargetPath.func_doc = """ReplaceTargetPath(oldPath, newPath) -> None
Updates the specified target path.
Replaces the path given by ``oldPath`` with the one specified by
``newPath`` . Relational attributes are updated if necessary.
Parameters
----------
oldPath : Path
newPath : Path
"""
result["RelationshipSpec"].RemoveTargetPath.func_doc = """RemoveTargetPath(path, preserveTargetOrder) -> None
Removes the specified target path.
Removes the given target path and any relational attributes for the
given target path. If ``preserveTargetOrder`` is ``true`` , Erase() is
called on the list editor instead of RemoveItemEdits(). This preserves
the ordered items list.
Parameters
----------
path : Path
preserveTargetOrder : bool
"""
result["Spec"].__doc__ = """
Base class for all Sdf spec classes.
"""
result["Spec"].ListInfoKeys.func_doc = """ListInfoKeys() -> list[str]
Returns the full list of info keys currently set on this object.
This does not include fields that represent names of children.
"""
result["Spec"].GetMetaDataInfoKeys.func_doc = """GetMetaDataInfoKeys() -> list[str]
Returns the list of metadata info keys for this object.
This is not the complete list of keys, it is only those that should be
considered to be metadata by inspectors or other presentation UI.
This is interim API which is likely to change. Only editors with an
immediate specific need (like the Inspector) should use this API.
"""
result["Spec"].GetMetaDataDisplayGroup.func_doc = """GetMetaDataDisplayGroup(key) -> str
Returns this metadata key's displayGroup.
Parameters
----------
key : str
"""
result["Spec"].GetInfo.func_doc = """GetInfo(key) -> VtValue
Gets the value for the given metadata key.
This is interim API which is likely to change. Only editors with an
immediate specific need (like the Inspector) should use this API.
Parameters
----------
key : str
"""
result["Spec"].SetInfo.func_doc = """SetInfo(key, value) -> None
Sets the value for the given metadata key.
It is an error to pass a value that is not the correct type for that
given key.
This is interim API which is likely to change. Only editors with an
immediate specific need (like the Inspector) should use this API.
Parameters
----------
key : str
value : VtValue
"""
result["Spec"].SetInfoDictionaryValue.func_doc = """SetInfoDictionaryValue(dictionaryKey, entryKey, value) -> None
Sets the value for ``entryKey`` to ``value`` within the dictionary
with the given metadata key ``dictionaryKey`` .
Parameters
----------
dictionaryKey : str
entryKey : str
value : VtValue
"""
result["TimeCode"].__doc__ = """
Value type that represents a time code. It's equivalent to a double
type value but is used to indicate that this value should be resolved
by any time based value resolution.
"""
result["TimeCode"].__init__.func_doc = """__init__(time)
Construct a time code with the given time.
A default constructed SdfTimeCode has a time of 0.0. A double value
can implicitly cast to SdfTimeCode.
Parameters
----------
time : float
"""
result["TimeCode"].GetValue.func_doc = """GetValue() -> float
Return the time value.
"""
result["UnregisteredValue"].__doc__ = """
Stores a representation of the value for an unregistered metadata
field encountered during text layer parsing.
This provides the ability to serialize this data to a layer, as well
as limited inspection and editing capabilities (e.g., moving this data
to a different spec or field) even when the data type of the value
isn't known.
"""
result["UnregisteredValue"].__init__.func_doc = """__init__()
Wraps an empty VtValue.
----------------------------------------------------------------------
__init__(value)
Wraps a std::string.
Parameters
----------
value : str
----------------------------------------------------------------------
__init__(value)
Wraps a VtDictionary.
Parameters
----------
value : VtDictionary
----------------------------------------------------------------------
__init__(value)
Wraps a SdfUnregisteredValueListOp.
Parameters
----------
value : UnregisteredValueListOp
"""
result["ValueBlock"].__doc__ = """
A special value type that can be used to explicitly author an opinion
for an attribute's default value or time sample value that represents
having no value. Note that this is different from not having a value
authored.
One could author such a value in two ways.
.. code-block:: text
attribute->SetDefaultValue(VtValue(SdfValueBlock());
\\.\\.\\.
layer->SetTimeSample(attribute->GetPath(), 101, VtValue(SdfValueBlock()));
"""
result["ValueTypeName"].__doc__ = """
Represents a value type name, i.e. an attribute's type name. Usually,
a value type name associates a string with a ``TfType`` and an
optional role, along with additional metadata. A schema registers all
known value type names and may register multiple names for the same
TfType and role pair. All name strings for a given pair are
collectively called its aliases.
A value type name may also represent just a name string, without a
``TfType`` , role or other metadata. This is currently used
exclusively to unserialize and re-serialize an attribute's type name
where that name is not known to the schema.
Because value type names can have aliases and those aliases may change
in the future, clients should avoid using the value type name's string
representation except to report human readable messages and when
serializing. Clients can look up a value type name by string using
``SdfSchemaBase::FindType()`` and shouldn't otherwise need the string.
Aliases compare equal, even if registered by different schemas.
"""
result["ValueTypeName"].__init__.func_doc = """__init__()
Constructs an invalid type name.
----------------------------------------------------------------------
__init__(arg1)
Parameters
----------
arg1 : Sdf_ValueTypeImpl
"""
result["VariantSetSpec"].__doc__ = """
Represents a coherent set of alternate representations for part of a
scene.
An SdfPrimSpec object may contain one or more named SdfVariantSetSpec
objects that define variations on the prim.
An SdfVariantSetSpec object contains one or more named SdfVariantSpec
objects. It may also define the name of one of its variants to be used
by default.
When a prim references another prim, the referencing prim may specify
one of the variants from each of the variant sets of the target prim.
The chosen variant from each set (or the default variant from those
sets that the referencing prim does not explicitly specify) is
composited over the target prim, and then the referencing prim is
composited over the result.
"""
result["VariantSetSpec"].RemoveVariant.func_doc = """RemoveVariant(variant) -> None
Removes ``variant`` from the list of variants.
If the variant set does not currently own ``variant`` , no action is
taken.
Parameters
----------
variant : VariantSpec
"""
result["VariantSpec"].__doc__ = """
Represents a single variant in a variant set.
A variant contains a prim. This prim is the root prim of the variant.
SdfVariantSpecs are value objects. This means they are immutable once
created and they are passed by copy-in APIs. To change a variant spec,
you make a new one and replace the existing one.
"""
result["VariantSpec"].GetVariantNames.func_doc = """GetVariantNames(name) -> list[str]
Returns list of variant names for the given variant set.
Parameters
----------
name : str
"""
result["AssetPath"].resolvedPath = property(result["AssetPath"].resolvedPath.fget, result["AssetPath"].resolvedPath.fset, result["AssetPath"].resolvedPath.fdel, """type : str
Return the resolved asset path, if any.
Note that SdfAssetPath carries a resolved path only if its creator
passed one to the constructor. SdfAssetPath never performs resolution
itself.
----------------------------------------------------------------------
type : str
Overload for rvalues, move out the asset path.
""")
result["BatchNamespaceEdit"].edits = property(result["BatchNamespaceEdit"].edits.fget, result["BatchNamespaceEdit"].edits.fset, result["BatchNamespaceEdit"].edits.fdel, """type : list[SdfNamespaceEdit]
Returns the edits.
""")
result["FileFormat"].formatId = property(result["FileFormat"].formatId.fget, result["FileFormat"].formatId.fset, result["FileFormat"].formatId.fdel, """type : str
Returns the format identifier.
""")
result["FileFormat"].target = property(result["FileFormat"].target.fget, result["FileFormat"].target.fset, result["FileFormat"].target.fdel, """type : str
Returns the target for this file format.
""")
result["FileFormat"].fileCookie = property(result["FileFormat"].fileCookie.fget, result["FileFormat"].fileCookie.fset, result["FileFormat"].fileCookie.fdel, """type : str
Returns the cookie to be used when writing files with this format.
""")
result["FileFormat"].primaryFileExtension = property(result["FileFormat"].primaryFileExtension.fget, result["FileFormat"].primaryFileExtension.fset, result["FileFormat"].primaryFileExtension.fdel, """type : str
Returns the primary file extension for this format.
This is the extension that is reported for layers using this file
format.
""")
result["Layer"].empty = property(result["Layer"].empty.fget, result["Layer"].empty.fset, result["Layer"].empty.fdel, """type : bool
Returns whether this layer has no significant data.
""")
result["Layer"].anonymous = property(result["Layer"].anonymous.fget, result["Layer"].anonymous.fset, result["Layer"].anonymous.fdel, """type : bool
Returns true if this layer is an anonymous layer.
""")
result["Layer"].dirty = property(result["Layer"].dirty.fget, result["Layer"].dirty.fset, result["Layer"].dirty.fdel, """type : bool
Returns ``true`` if the layer is dirty, i.e.
has changed from its persistent representation.
""")
result["LayerOffset"].offset = property(result["LayerOffset"].offset.fget, result["LayerOffset"].offset.fset, result["LayerOffset"].offset.fdel, """type : None
Sets the time offset.
----------------------------------------------------------------------
type : float
Returns the time offset.
""")
result["LayerOffset"].scale = property(result["LayerOffset"].scale.fget, result["LayerOffset"].scale.fset, result["LayerOffset"].scale.fdel, """type : None
Sets the time scale factor.
----------------------------------------------------------------------
type : float
Returns the time scale factor.
""")
result["LayerTree"].layer = property(result["LayerTree"].layer.fget, result["LayerTree"].layer.fset, result["LayerTree"].layer.fdel, """type : Layer
Returns the layer handle this tree node represents.
""")
result["LayerTree"].offset = property(result["LayerTree"].offset.fget, result["LayerTree"].offset.fset, result["LayerTree"].offset.fdel, """type : LayerOffset
Returns the cumulative layer offset from the root of the tree.
""")
result["LayerTree"].childTrees = property(result["LayerTree"].childTrees.fget, result["LayerTree"].childTrees.fset, result["LayerTree"].childTrees.fdel, """type : list[SdfLayerTreeHandle]
Returns the children of this tree node.
""")
result["Path"].isEmpty = property(result["Path"].isEmpty.fget, result["Path"].isEmpty.fset, result["Path"].isEmpty.fdel, """type : bool
Returns true if this is the empty path ( SdfPath::EmptyPath() ).
""")
result["Payload"].assetPath = property(result["Payload"].assetPath.fget, result["Payload"].assetPath.fset, result["Payload"].assetPath.fdel, """type : None
Sets a new asset path for the layer the payload uses.
See SdfAssetPath for what characters are valid in ``assetPath`` . If
``assetPath`` contains invalid characters, issue an error and set this
payload's asset path to the empty asset path.
----------------------------------------------------------------------
type : str
Returns the asset path of the layer that the payload uses.
""")
result["Payload"].primPath = property(result["Payload"].primPath.fget, result["Payload"].primPath.fset, result["Payload"].primPath.fdel, """type : None
Sets a new prim path for the prim that the payload uses.
----------------------------------------------------------------------
type : Path
Returns the scene path of the prim for the payload.
""")
result["Payload"].layerOffset = property(result["Payload"].layerOffset.fget, result["Payload"].layerOffset.fset, result["Payload"].layerOffset.fdel, """type : None
Sets a new layer offset.
----------------------------------------------------------------------
type : LayerOffset
Returns the layer offset associated with the payload.
""")
result["Reference"].assetPath = property(result["Reference"].assetPath.fget, result["Reference"].assetPath.fset, result["Reference"].assetPath.fdel, """type : None
Sets the asset path for the root layer of the referenced layer stack.
This may be set to an empty string to specify an internal reference.
See SdfAssetPath for what characters are valid in ``assetPath`` . If
``assetPath`` contains invalid characters, issue an error and set this
reference's asset path to the empty asset path.
----------------------------------------------------------------------
type : str
Returns the asset path to the root layer of the referenced layer
stack.
This will be empty in the case of an internal reference.
""")
result["Reference"].primPath = property(result["Reference"].primPath.fget, result["Reference"].primPath.fset, result["Reference"].primPath.fdel, """type : None
Sets the path of the referenced prim.
This may be set to an empty path to specify a reference to the default
prim in the referenced layer stack.
----------------------------------------------------------------------
type : Path
Returns the path of the referenced prim.
This will be empty if the referenced prim is the default prim
specified in the referenced layer stack.
""")
result["Reference"].layerOffset = property(result["Reference"].layerOffset.fget, result["Reference"].layerOffset.fset, result["Reference"].layerOffset.fdel, """type : None
Sets a new layer offset.
----------------------------------------------------------------------
type : LayerOffset
Returns the layer offset associated with the reference.
""")
result["Reference"].customData = property(result["Reference"].customData.fget, result["Reference"].customData.fset, result["Reference"].customData.fdel, """type : None
Sets the custom data associated with the reference.
----------------------------------------------------------------------
type : None
Sets a custom data entry for the reference.
If *value* is empty, then this removes the given custom data entry.
----------------------------------------------------------------------
type : VtDictionary
Returns the custom data associated with the reference.
""")
result["UnregisteredValue"].value = property(result["UnregisteredValue"].value.fget, result["UnregisteredValue"].value.fset, result["UnregisteredValue"].value.fdel, """type : VtValue
Returns the wrapped VtValue specified in the constructor.
""")
result["ValueTypeName"].type = property(result["ValueTypeName"].type.fget, result["ValueTypeName"].type.fset, result["ValueTypeName"].type.fdel, """type : Type
Returns the ``TfType`` of the type.
""")
result["ValueTypeName"].role = property(result["ValueTypeName"].role.fget, result["ValueTypeName"].role.fset, result["ValueTypeName"].role.fdel, """type : str
Returns the type's role.
""")
result["ValueTypeName"].defaultValue = property(result["ValueTypeName"].defaultValue.fget, result["ValueTypeName"].defaultValue.fset, result["ValueTypeName"].defaultValue.fdel, """type : VtValue
Returns the default value for the type.
""")
result["ValueTypeName"].defaultUnit = property(result["ValueTypeName"].defaultUnit.fget, result["ValueTypeName"].defaultUnit.fset, result["ValueTypeName"].defaultUnit.fdel, """type : Enum
Returns the default unit enum for the type.
""")
result["ValueTypeName"].scalarType = property(result["ValueTypeName"].scalarType.fget, result["ValueTypeName"].scalarType.fset, result["ValueTypeName"].scalarType.fdel, """type : ValueTypeName
Returns the scalar version of this type name if it's an array type
name, otherwise returns this type name.
If there is no scalar type name then this returns the invalid type
name.
""")
result["ValueTypeName"].arrayType = property(result["ValueTypeName"].arrayType.fget, result["ValueTypeName"].arrayType.fset, result["ValueTypeName"].arrayType.fdel, """type : ValueTypeName
Returns the array version of this type name if it's an scalar type
name, otherwise returns this type name.
If there is no array type name then this returns the invalid type
name.
""")
result["ValueTypeName"].isScalar = property(result["ValueTypeName"].isScalar.fget, result["ValueTypeName"].isScalar.fset, result["ValueTypeName"].isScalar.fdel, """type : bool
Returns ``true`` iff this type is a scalar.
The invalid type is considered neither scalar nor array.
""")
result["ValueTypeName"].isArray = property(result["ValueTypeName"].isArray.fget, result["ValueTypeName"].isArray.fset, result["ValueTypeName"].isArray.fdel, """type : bool
Returns ``true`` iff this type is an array.
The invalid type is considered neither scalar nor array.
""")
result["VariantSpec"].variantSets = property(result["VariantSpec"].variantSets.fget, result["VariantSpec"].variantSets.fset, result["VariantSpec"].variantSets.fdel, """type : SdfVariantSetsProxy
Returns the nested variant sets.
The result maps variant set names to variant sets. Variant sets may be
removed through the proxy.
""") | 95,823 | Python | 22.654406 | 213 | 0.711291 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdUI/__DOC.py | def Execute(result):
result["Backdrop"].__doc__ = """
Provides a'group-box'for the purpose of node graph organization.
Unlike containers, backdrops do not store the Shader nodes inside of
them. Backdrops are an organizational tool that allows Shader nodes to
be visually grouped together in a node-graph UI, but there is no
direct relationship between a Shader node and a Backdrop.
The guideline for a node-graph UI is that a Shader node is considered
part of a Backdrop when the Backdrop is the smallest Backdrop a Shader
node's bounding-box fits inside.
Backdrop objects are contained inside a NodeGraph, similar to how
Shader objects are contained inside a NodeGraph.
Backdrops have no shading inputs or outputs that influence the
rendered results of a NodeGraph. Therefore they can be safely ignored
during import.
Like Shaders and NodeGraphs, Backdrops subscribe to the
NodeGraphNodeAPI to specify position and size.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdUITokens. So to set an attribute to the value"rightHanded", use
UsdUITokens->rightHanded as the value.
"""
result["Backdrop"].__init__.func_doc = """__init__(prim)
Construct a UsdUIBackdrop on UsdPrim ``prim`` .
Equivalent to UsdUIBackdrop::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdUIBackdrop on the prim held by ``schemaObj`` .
Should be preferred over UsdUIBackdrop (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Backdrop"].GetDescriptionAttr.func_doc = """GetDescriptionAttr() -> Attribute
The text label that is displayed on the backdrop in the node graph.
This help-description explains what the nodes in a backdrop do.
Declaration
``uniform token ui:description``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["Backdrop"].CreateDescriptionAttr.func_doc = """CreateDescriptionAttr(defaultValue, writeSparsely) -> Attribute
See GetDescriptionAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Backdrop"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Backdrop"].Get.func_doc = """**classmethod** Get(stage, path) -> Backdrop
Return a UsdUIBackdrop holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdUIBackdrop(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Backdrop"].Define.func_doc = """**classmethod** Define(stage, path) -> Backdrop
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Backdrop"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["NodeGraphNodeAPI"].__doc__ = """
This api helps storing information about nodes in node graphs.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdUITokens. So to set an attribute to the value"rightHanded", use
UsdUITokens->rightHanded as the value.
"""
result["NodeGraphNodeAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdUINodeGraphNodeAPI on UsdPrim ``prim`` .
Equivalent to UsdUINodeGraphNodeAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdUINodeGraphNodeAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdUINodeGraphNodeAPI (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["NodeGraphNodeAPI"].GetPosAttr.func_doc = """GetPosAttr() -> Attribute
Declared relative position to the parent in a node graph.
X is the horizontal position. Y is the vertical position. Higher
numbers correspond to lower positions (coordinates are Qt style, not
cartesian).
These positions are not explicitly meant in pixel space, but rather
assume that the size of a node is approximately 1.0x1.0. Where size-x
is the node width and size-y height of the node. Depending on graph UI
implementation, the size of a node may vary in each direction.
Example: If a node's width is 300 and it is position is at 1000, we
store for x-position: 1000 \\* (1.0/300)
Declaration
``uniform float2 ui:nodegraph:node:pos``
C++ Type
GfVec2f
Usd Type
SdfValueTypeNames->Float2
Variability
SdfVariabilityUniform
"""
result["NodeGraphNodeAPI"].CreatePosAttr.func_doc = """CreatePosAttr(defaultValue, writeSparsely) -> Attribute
See GetPosAttr() , and also Create vs Get Property Methods for when to
use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NodeGraphNodeAPI"].GetStackingOrderAttr.func_doc = """GetStackingOrderAttr() -> Attribute
This optional value is a useful hint when an application cares about
the visibility of a node and whether each node overlaps another.
Nodes with lower stacking order values are meant to be drawn below
higher ones. Negative values are meant as background. Positive values
are meant as foreground. Undefined values should be treated as 0.
There are no set limits in these values.
Declaration
``uniform int ui:nodegraph:node:stackingOrder``
C++ Type
int
Usd Type
SdfValueTypeNames->Int
Variability
SdfVariabilityUniform
"""
result["NodeGraphNodeAPI"].CreateStackingOrderAttr.func_doc = """CreateStackingOrderAttr(defaultValue, writeSparsely) -> Attribute
See GetStackingOrderAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NodeGraphNodeAPI"].GetDisplayColorAttr.func_doc = """GetDisplayColorAttr() -> Attribute
This hint defines what tint the node should have in the node graph.
Declaration
``uniform color3f ui:nodegraph:node:displayColor``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Color3f
Variability
SdfVariabilityUniform
"""
result["NodeGraphNodeAPI"].CreateDisplayColorAttr.func_doc = """CreateDisplayColorAttr(defaultValue, writeSparsely) -> Attribute
See GetDisplayColorAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NodeGraphNodeAPI"].GetIconAttr.func_doc = """GetIconAttr() -> Attribute
This points to an image that should be displayed on the node.
It is intended to be useful for summary visual classification of
nodes, rather than a thumbnail preview of the computed result of the
node in some computational system.
Declaration
``uniform asset ui:nodegraph:node:icon``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
Variability
SdfVariabilityUniform
"""
result["NodeGraphNodeAPI"].CreateIconAttr.func_doc = """CreateIconAttr(defaultValue, writeSparsely) -> Attribute
See GetIconAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NodeGraphNodeAPI"].GetExpansionStateAttr.func_doc = """GetExpansionStateAttr() -> Attribute
The current expansionState of the node in the ui.
'open'= fully expanded'closed'= fully collapsed'minimized'= should
take the least space possible
Declaration
``uniform token ui:nodegraph:node:expansionState``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
open, closed, minimized
"""
result["NodeGraphNodeAPI"].CreateExpansionStateAttr.func_doc = """CreateExpansionStateAttr(defaultValue, writeSparsely) -> Attribute
See GetExpansionStateAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NodeGraphNodeAPI"].GetSizeAttr.func_doc = """GetSizeAttr() -> Attribute
Optional size hint for a node in a node graph.
X is the width. Y is the height.
This value is optional, because node size is often determined based on
the number of in- and outputs of a node.
Declaration
``uniform float2 ui:nodegraph:node:size``
C++ Type
GfVec2f
Usd Type
SdfValueTypeNames->Float2
Variability
SdfVariabilityUniform
"""
result["NodeGraphNodeAPI"].CreateSizeAttr.func_doc = """CreateSizeAttr(defaultValue, writeSparsely) -> Attribute
See GetSizeAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NodeGraphNodeAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["NodeGraphNodeAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> NodeGraphNodeAPI
Return a UsdUINodeGraphNodeAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdUINodeGraphNodeAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["NodeGraphNodeAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["NodeGraphNodeAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> NodeGraphNodeAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"NodeGraphNodeAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdUINodeGraphNodeAPI object is returned upon success. An
invalid (or empty) UsdUINodeGraphNodeAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["NodeGraphNodeAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["SceneGraphPrimAPI"].__doc__ = """
Utility schema for display properties of a prim
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdUITokens. So to set an attribute to the value"rightHanded", use
UsdUITokens->rightHanded as the value.
"""
result["SceneGraphPrimAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdUISceneGraphPrimAPI on UsdPrim ``prim`` .
Equivalent to UsdUISceneGraphPrimAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdUISceneGraphPrimAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdUISceneGraphPrimAPI (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["SceneGraphPrimAPI"].GetDisplayNameAttr.func_doc = """GetDisplayNameAttr() -> Attribute
When publishing a nodegraph or a material, it can be useful to provide
an optional display name, for readability.
Declaration
``uniform token ui:displayName``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["SceneGraphPrimAPI"].CreateDisplayNameAttr.func_doc = """CreateDisplayNameAttr(defaultValue, writeSparsely) -> Attribute
See GetDisplayNameAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SceneGraphPrimAPI"].GetDisplayGroupAttr.func_doc = """GetDisplayGroupAttr() -> Attribute
When publishing a nodegraph or a material, it can be useful to provide
an optional display group, for organizational purposes and
readability.
This is because often the usd shading hierarchy is rather flat while
we want to display it in organized groups.
Declaration
``uniform token ui:displayGroup``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["SceneGraphPrimAPI"].CreateDisplayGroupAttr.func_doc = """CreateDisplayGroupAttr(defaultValue, writeSparsely) -> Attribute
See GetDisplayGroupAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SceneGraphPrimAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["SceneGraphPrimAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> SceneGraphPrimAPI
Return a UsdUISceneGraphPrimAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdUISceneGraphPrimAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["SceneGraphPrimAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["SceneGraphPrimAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> SceneGraphPrimAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"SceneGraphPrimAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdUISceneGraphPrimAPI object is returned upon success. An
invalid (or empty) UsdUISceneGraphPrimAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["SceneGraphPrimAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
""" | 19,636 | Python | 20.626652 | 143 | 0.733245 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdPhysics/__DOC.py | def Execute(result):
result["ArticulationRootAPI"].__doc__ = """
PhysicsArticulationRootAPI can be applied to a scene graph node, and
marks the subtree rooted here for inclusion in one or more reduced
coordinate articulations. For floating articulations, this should be
on the root body. For fixed articulations (robotics jargon for e.g. a
robot arm for welding that is bolted to the floor), this API can be on
a direct or indirect parent of the root joint which is connected to
the world, or on the joint itself\\.\\.
"""
result["ArticulationRootAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsArticulationRootAPI on UsdPrim ``prim`` .
Equivalent to UsdPhysicsArticulationRootAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsArticulationRootAPI on the prim held by
``schemaObj`` .
Should be preferred over UsdPhysicsArticulationRootAPI
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["ArticulationRootAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["ArticulationRootAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> ArticulationRootAPI
Return a UsdPhysicsArticulationRootAPI holding the prim adhering to
this schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsArticulationRootAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["ArticulationRootAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["ArticulationRootAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> ArticulationRootAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"PhysicsArticulationRootAPI"to the
token-valued, listOp metadata *apiSchemas* on the prim.
A valid UsdPhysicsArticulationRootAPI object is returned upon success.
An invalid (or empty) UsdPhysicsArticulationRootAPI object is returned
upon failure. See UsdPrim::ApplyAPI() for conditions resulting in
failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["ArticulationRootAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["CollisionAPI"].__doc__ = """
Applies collision attributes to a UsdGeomXformable prim. If a
simulation is running, this geometry will collide with other
geometries that have PhysicsCollisionAPI applied. If a prim in the
parent hierarchy has the RigidBodyAPI applied, this collider is a part
of that body. If there is no body in the parent hierarchy, this
collider is considered to be static.
"""
result["CollisionAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsCollisionAPI on UsdPrim ``prim`` .
Equivalent to UsdPhysicsCollisionAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsCollisionAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdPhysicsCollisionAPI (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["CollisionAPI"].GetCollisionEnabledAttr.func_doc = """GetCollisionEnabledAttr() -> Attribute
Determines if the PhysicsCollisionAPI is enabled.
Declaration
``bool physics:collisionEnabled = 1``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["CollisionAPI"].CreateCollisionEnabledAttr.func_doc = """CreateCollisionEnabledAttr(defaultValue, writeSparsely) -> Attribute
See GetCollisionEnabledAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["CollisionAPI"].GetSimulationOwnerRel.func_doc = """GetSimulationOwnerRel() -> Relationship
Single PhysicsScene that will simulate this collider.
By default this object belongs to the first PhysicsScene. Note that if
a RigidBodyAPI in the hierarchy above has a different simulationOwner
then it has a precedence over this relationship.
"""
result["CollisionAPI"].CreateSimulationOwnerRel.func_doc = """CreateSimulationOwnerRel() -> Relationship
See GetSimulationOwnerRel() , and also Create vs Get Property Methods
for when to use Get vs Create.
"""
result["CollisionAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["CollisionAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> CollisionAPI
Return a UsdPhysicsCollisionAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsCollisionAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["CollisionAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["CollisionAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> CollisionAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"PhysicsCollisionAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdPhysicsCollisionAPI object is returned upon success. An
invalid (or empty) UsdPhysicsCollisionAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["CollisionAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["CollisionGroup"].__doc__ = """
Defines a collision group for coarse filtering. When a collision
occurs between two objects that have a PhysicsCollisionGroup assigned,
they will collide with each other unless this PhysicsCollisionGroup
pair is filtered. See filteredGroups attribute.
A CollectionAPI:colliders maintains a list of PhysicsCollisionAPI
rel-s that defines the members of this Collisiongroup.
"""
result["CollisionGroup"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsCollisionGroup on UsdPrim ``prim`` .
Equivalent to UsdPhysicsCollisionGroup::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsCollisionGroup on the prim held by ``schemaObj``
.
Should be preferred over UsdPhysicsCollisionGroup
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["CollisionGroup"].GetMergeGroupNameAttr.func_doc = """GetMergeGroupNameAttr() -> Attribute
If non-empty, any collision groups in a stage with a matching
mergeGroup should be considered to refer to the same collection.
Matching collision groups should behave as if there were a single
group containing referenced colliders and filter groups from both
collections.
Declaration
``string physics:mergeGroup``
C++ Type
std::string
Usd Type
SdfValueTypeNames->String
"""
result["CollisionGroup"].CreateMergeGroupNameAttr.func_doc = """CreateMergeGroupNameAttr(defaultValue, writeSparsely) -> Attribute
See GetMergeGroupNameAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["CollisionGroup"].GetInvertFilteredGroupsAttr.func_doc = """GetInvertFilteredGroupsAttr() -> Attribute
Normally, the filter will disable collisions against the selected
filter groups.
However, if this option is set, the filter will disable collisions
against all colliders except for those in the selected filter groups.
Declaration
``bool physics:invertFilteredGroups``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["CollisionGroup"].CreateInvertFilteredGroupsAttr.func_doc = """CreateInvertFilteredGroupsAttr(defaultValue, writeSparsely) -> Attribute
See GetInvertFilteredGroupsAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["CollisionGroup"].GetFilteredGroupsRel.func_doc = """GetFilteredGroupsRel() -> Relationship
References a list of PhysicsCollisionGroups with which collisions
should be ignored.
"""
result["CollisionGroup"].CreateFilteredGroupsRel.func_doc = """CreateFilteredGroupsRel() -> Relationship
See GetFilteredGroupsRel() , and also Create vs Get Property Methods
for when to use Get vs Create.
"""
result["CollisionGroup"].GetCollidersCollectionAPI.func_doc = """GetCollidersCollectionAPI() -> CollectionAPI
Return the UsdCollectionAPI interface used for defining what colliders
belong to the CollisionGroup.
"""
result["CollisionGroup"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["CollisionGroup"].Get.func_doc = """**classmethod** Get(stage, path) -> CollisionGroup
Return a UsdPhysicsCollisionGroup holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsCollisionGroup(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["CollisionGroup"].Define.func_doc = """**classmethod** Define(stage, path) -> CollisionGroup
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["CollisionGroup"].ComputeCollisionGroupTable.func_doc = """**classmethod** ComputeCollisionGroupTable(stage) -> CollisionGroupTable
Compute a table encoding all the collision groups filter rules for a
stage.
This can be used as a reference to validate an implementation of the
collision groups filters. The returned table is diagonally symmetric.
Parameters
----------
stage : Stage
"""
result["CollisionGroup"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["DistanceJoint"].__doc__ = """
Predefined distance joint type (Distance between rigid bodies may be
limited to given minimum or maximum distance.)
"""
result["DistanceJoint"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsDistanceJoint on UsdPrim ``prim`` .
Equivalent to UsdPhysicsDistanceJoint::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsDistanceJoint on the prim held by ``schemaObj``
.
Should be preferred over UsdPhysicsDistanceJoint
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["DistanceJoint"].GetMinDistanceAttr.func_doc = """GetMinDistanceAttr() -> Attribute
Minimum distance.
If attribute is negative, the joint is not limited. Units: distance.
Declaration
``float physics:minDistance = -1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DistanceJoint"].CreateMinDistanceAttr.func_doc = """CreateMinDistanceAttr(defaultValue, writeSparsely) -> Attribute
See GetMinDistanceAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DistanceJoint"].GetMaxDistanceAttr.func_doc = """GetMaxDistanceAttr() -> Attribute
Maximum distance.
If attribute is negative, the joint is not limited. Units: distance.
Declaration
``float physics:maxDistance = -1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DistanceJoint"].CreateMaxDistanceAttr.func_doc = """CreateMaxDistanceAttr(defaultValue, writeSparsely) -> Attribute
See GetMaxDistanceAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DistanceJoint"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["DistanceJoint"].Get.func_doc = """**classmethod** Get(stage, path) -> DistanceJoint
Return a UsdPhysicsDistanceJoint holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsDistanceJoint(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["DistanceJoint"].Define.func_doc = """**classmethod** Define(stage, path) -> DistanceJoint
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["DistanceJoint"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["DriveAPI"].__doc__ = """
The PhysicsDriveAPI when applied to any joint primitive will drive the
joint towards a given target. The PhysicsDriveAPI is a multipleApply
schema: drive can be set per
axis"transX","transY","transZ","rotX","rotY","rotZ"or its"linear"for
prismatic joint or"angular"for revolute joints. Setting these as a
multipleApply schema TfToken name will define the degree of freedom
the DriveAPI is applied to. Each drive is an implicit force-limited
damped spring: Force or acceleration = stiffness \\* (targetPosition -
position)
- damping \\* (targetVelocity - velocity)
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdPhysicsTokens. So to set an attribute to the value"rightHanded",
use UsdPhysicsTokens->rightHanded as the value.
"""
result["DriveAPI"].__init__.func_doc = """__init__(prim, name)
Construct a UsdPhysicsDriveAPI on UsdPrim ``prim`` with name ``name``
.
Equivalent to UsdPhysicsDriveAPI::Get ( prim.GetStage(),
prim.GetPath().AppendProperty("drive:name"));
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
name : str
----------------------------------------------------------------------
__init__(schemaObj, name)
Construct a UsdPhysicsDriveAPI on the prim held by ``schemaObj`` with
name ``name`` .
Should be preferred over UsdPhysicsDriveAPI (schemaObj.GetPrim(),
name), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
name : str
"""
result["DriveAPI"].GetTypeAttr.func_doc = """GetTypeAttr() -> Attribute
Drive spring is for the acceleration at the joint (rather than the
force).
Declaration
``uniform token physics:type ="force"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
force, acceleration
"""
result["DriveAPI"].CreateTypeAttr.func_doc = """CreateTypeAttr(defaultValue, writeSparsely) -> Attribute
See GetTypeAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DriveAPI"].GetMaxForceAttr.func_doc = """GetMaxForceAttr() -> Attribute
Maximum force that can be applied to drive.
Units: if linear drive: mass\\*DIST_UNITS/second/second if angular
drive: mass\\*DIST_UNITS\\*DIST_UNITS/second/second inf means not
limited. Must be non-negative.
Declaration
``float physics:maxForce = inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DriveAPI"].CreateMaxForceAttr.func_doc = """CreateMaxForceAttr(defaultValue, writeSparsely) -> Attribute
See GetMaxForceAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DriveAPI"].GetTargetPositionAttr.func_doc = """GetTargetPositionAttr() -> Attribute
Target value for position.
Units: if linear drive: distance if angular drive: degrees.
Declaration
``float physics:targetPosition = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DriveAPI"].CreateTargetPositionAttr.func_doc = """CreateTargetPositionAttr(defaultValue, writeSparsely) -> Attribute
See GetTargetPositionAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DriveAPI"].GetTargetVelocityAttr.func_doc = """GetTargetVelocityAttr() -> Attribute
Target value for velocity.
Units: if linear drive: distance/second if angular drive:
degrees/second.
Declaration
``float physics:targetVelocity = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DriveAPI"].CreateTargetVelocityAttr.func_doc = """CreateTargetVelocityAttr(defaultValue, writeSparsely) -> Attribute
See GetTargetVelocityAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DriveAPI"].GetDampingAttr.func_doc = """GetDampingAttr() -> Attribute
Damping of the drive.
Units: if linear drive: mass/second If angular drive:
mass\\*DIST_UNITS\\*DIST_UNITS/second/second/degrees.
Declaration
``float physics:damping = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DriveAPI"].CreateDampingAttr.func_doc = """CreateDampingAttr(defaultValue, writeSparsely) -> Attribute
See GetDampingAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DriveAPI"].GetStiffnessAttr.func_doc = """GetStiffnessAttr() -> Attribute
Stiffness of the drive.
Units: if linear drive: mass/second/second if angular drive:
mass\\*DIST_UNITS\\*DIST_UNITS/degree/second/second.
Declaration
``float physics:stiffness = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DriveAPI"].CreateStiffnessAttr.func_doc = """CreateStiffnessAttr(defaultValue, writeSparsely) -> Attribute
See GetStiffnessAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DriveAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
----------------------------------------------------------------------
GetSchemaAttributeNames(includeInherited, instanceName) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes for a given instance name.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved. The names returned will have the
proper namespace prefix.
Parameters
----------
includeInherited : bool
instanceName : str
"""
result["DriveAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> DriveAPI
Return a UsdPhysicsDriveAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
``path`` must be of the format<path>.drive:name.
This is shorthand for the following:
.. code-block:: text
TfToken name = SdfPath::StripNamespace(path.GetToken());
UsdPhysicsDriveAPI(
stage->GetPrimAtPath(path.GetPrimPath()), name);
Parameters
----------
stage : Stage
path : Path
----------------------------------------------------------------------
Get(prim, name) -> DriveAPI
Return a UsdPhysicsDriveAPI with name ``name`` holding the prim
``prim`` .
Shorthand for UsdPhysicsDriveAPI(prim, name);
Parameters
----------
prim : Prim
name : str
"""
result["DriveAPI"].GetAll.func_doc = """**classmethod** GetAll(prim) -> list[DriveAPI]
Return a vector of all named instances of UsdPhysicsDriveAPI on the
given ``prim`` .
Parameters
----------
prim : Prim
"""
result["DriveAPI"].IsPhysicsDriveAPIPath.func_doc = """**classmethod** IsPhysicsDriveAPIPath(path, name) -> bool
Checks if the given path ``path`` is of an API schema of type
PhysicsDriveAPI.
If so, it stores the instance name of the schema in ``name`` and
returns true. Otherwise, it returns false.
Parameters
----------
path : Path
name : str
"""
result["DriveAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, name, whyNot) -> bool
Returns true if this **multiple-apply** API schema can be applied,
with the given instance name, ``name`` , to the given ``prim`` .
If this schema can not be a applied the prim, this returns false and,
if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
name : str
whyNot : str
"""
result["DriveAPI"].Apply.func_doc = """**classmethod** Apply(prim, name) -> DriveAPI
Applies this **multiple-apply** API schema to the given ``prim`` along
with the given instance name, ``name`` .
This information is stored by adding"PhysicsDriveAPI:<i>name</i>"to
the token-valued, listOp metadata *apiSchemas* on the prim. For
example, if ``name`` is'instance1', the
token'PhysicsDriveAPI:instance1'is added to'apiSchemas'.
A valid UsdPhysicsDriveAPI object is returned upon success. An invalid
(or empty) UsdPhysicsDriveAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
name : str
"""
result["DriveAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["FilteredPairsAPI"].__doc__ = """
API to describe fine-grained filtering. If a collision between two
objects occurs, this pair might be filtered if the pair is defined
through this API. This API can be applied either to a body or
collision or even articulation. The"filteredPairs"defines what objects
it should not collide against. Note that FilteredPairsAPI filtering
has precedence over CollisionGroup filtering.
"""
result["FilteredPairsAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsFilteredPairsAPI on UsdPrim ``prim`` .
Equivalent to UsdPhysicsFilteredPairsAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsFilteredPairsAPI on the prim held by
``schemaObj`` .
Should be preferred over UsdPhysicsFilteredPairsAPI
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["FilteredPairsAPI"].GetFilteredPairsRel.func_doc = """GetFilteredPairsRel() -> Relationship
Relationship to objects that should be filtered.
"""
result["FilteredPairsAPI"].CreateFilteredPairsRel.func_doc = """CreateFilteredPairsRel() -> Relationship
See GetFilteredPairsRel() , and also Create vs Get Property Methods
for when to use Get vs Create.
"""
result["FilteredPairsAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["FilteredPairsAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> FilteredPairsAPI
Return a UsdPhysicsFilteredPairsAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsFilteredPairsAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["FilteredPairsAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["FilteredPairsAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> FilteredPairsAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"PhysicsFilteredPairsAPI"to the
token-valued, listOp metadata *apiSchemas* on the prim.
A valid UsdPhysicsFilteredPairsAPI object is returned upon success. An
invalid (or empty) UsdPhysicsFilteredPairsAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["FilteredPairsAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["FixedJoint"].__doc__ = """
Predefined fixed joint type (All degrees of freedom are removed.)
"""
result["FixedJoint"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsFixedJoint on UsdPrim ``prim`` .
Equivalent to UsdPhysicsFixedJoint::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsFixedJoint on the prim held by ``schemaObj`` .
Should be preferred over UsdPhysicsFixedJoint (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["FixedJoint"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["FixedJoint"].Get.func_doc = """**classmethod** Get(stage, path) -> FixedJoint
Return a UsdPhysicsFixedJoint holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsFixedJoint(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["FixedJoint"].Define.func_doc = """**classmethod** Define(stage, path) -> FixedJoint
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["FixedJoint"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Joint"].__doc__ = """
A joint constrains the movement of rigid bodies. Joint can be created
between two rigid bodies or between one rigid body and world. By
default joint primitive defines a D6 joint where all degrees of
freedom are free. Three linear and three angular degrees of freedom.
Note that default behavior is to disable collision between jointed
bodies.
"""
result["Joint"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsJoint on UsdPrim ``prim`` .
Equivalent to UsdPhysicsJoint::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsJoint on the prim held by ``schemaObj`` .
Should be preferred over UsdPhysicsJoint (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Joint"].GetLocalPos0Attr.func_doc = """GetLocalPos0Attr() -> Attribute
Relative position of the joint frame to body0's frame.
Declaration
``point3f physics:localPos0 = (0, 0, 0)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Point3f
"""
result["Joint"].CreateLocalPos0Attr.func_doc = """CreateLocalPos0Attr(defaultValue, writeSparsely) -> Attribute
See GetLocalPos0Attr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Joint"].GetLocalRot0Attr.func_doc = """GetLocalRot0Attr() -> Attribute
Relative orientation of the joint frame to body0's frame.
Declaration
``quatf physics:localRot0 = (1, 0, 0, 0)``
C++ Type
GfQuatf
Usd Type
SdfValueTypeNames->Quatf
"""
result["Joint"].CreateLocalRot0Attr.func_doc = """CreateLocalRot0Attr(defaultValue, writeSparsely) -> Attribute
See GetLocalRot0Attr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Joint"].GetLocalPos1Attr.func_doc = """GetLocalPos1Attr() -> Attribute
Relative position of the joint frame to body1's frame.
Declaration
``point3f physics:localPos1 = (0, 0, 0)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Point3f
"""
result["Joint"].CreateLocalPos1Attr.func_doc = """CreateLocalPos1Attr(defaultValue, writeSparsely) -> Attribute
See GetLocalPos1Attr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Joint"].GetLocalRot1Attr.func_doc = """GetLocalRot1Attr() -> Attribute
Relative orientation of the joint frame to body1's frame.
Declaration
``quatf physics:localRot1 = (1, 0, 0, 0)``
C++ Type
GfQuatf
Usd Type
SdfValueTypeNames->Quatf
"""
result["Joint"].CreateLocalRot1Attr.func_doc = """CreateLocalRot1Attr(defaultValue, writeSparsely) -> Attribute
See GetLocalRot1Attr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Joint"].GetJointEnabledAttr.func_doc = """GetJointEnabledAttr() -> Attribute
Determines if the joint is enabled.
Declaration
``bool physics:jointEnabled = 1``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["Joint"].CreateJointEnabledAttr.func_doc = """CreateJointEnabledAttr(defaultValue, writeSparsely) -> Attribute
See GetJointEnabledAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Joint"].GetCollisionEnabledAttr.func_doc = """GetCollisionEnabledAttr() -> Attribute
Determines if the jointed subtrees should collide or not.
Declaration
``bool physics:collisionEnabled = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["Joint"].CreateCollisionEnabledAttr.func_doc = """CreateCollisionEnabledAttr(defaultValue, writeSparsely) -> Attribute
See GetCollisionEnabledAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Joint"].GetExcludeFromArticulationAttr.func_doc = """GetExcludeFromArticulationAttr() -> Attribute
Determines if the joint can be included in an Articulation.
Declaration
``uniform bool physics:excludeFromArticulation = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
Variability
SdfVariabilityUniform
"""
result["Joint"].CreateExcludeFromArticulationAttr.func_doc = """CreateExcludeFromArticulationAttr(defaultValue, writeSparsely) -> Attribute
See GetExcludeFromArticulationAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Joint"].GetBreakForceAttr.func_doc = """GetBreakForceAttr() -> Attribute
Joint break force.
If set, joint is to break when this force limit is reached. (Used for
linear DOFs.) Units: mass \\* distance / second / second
Declaration
``float physics:breakForce = inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Joint"].CreateBreakForceAttr.func_doc = """CreateBreakForceAttr(defaultValue, writeSparsely) -> Attribute
See GetBreakForceAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Joint"].GetBreakTorqueAttr.func_doc = """GetBreakTorqueAttr() -> Attribute
Joint break torque.
If set, joint is to break when this torque limit is reached. (Used for
angular DOFs.) Units: mass \\* distance \\* distance / second / second
Declaration
``float physics:breakTorque = inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Joint"].CreateBreakTorqueAttr.func_doc = """CreateBreakTorqueAttr(defaultValue, writeSparsely) -> Attribute
See GetBreakTorqueAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Joint"].GetBody0Rel.func_doc = """GetBody0Rel() -> Relationship
Relationship to any UsdGeomXformable.
"""
result["Joint"].CreateBody0Rel.func_doc = """CreateBody0Rel() -> Relationship
See GetBody0Rel() , and also Create vs Get Property Methods for when
to use Get vs Create.
"""
result["Joint"].GetBody1Rel.func_doc = """GetBody1Rel() -> Relationship
Relationship to any UsdGeomXformable.
"""
result["Joint"].CreateBody1Rel.func_doc = """CreateBody1Rel() -> Relationship
See GetBody1Rel() , and also Create vs Get Property Methods for when
to use Get vs Create.
"""
result["Joint"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Joint"].Get.func_doc = """**classmethod** Get(stage, path) -> Joint
Return a UsdPhysicsJoint holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsJoint(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Joint"].Define.func_doc = """**classmethod** Define(stage, path) -> Joint
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Joint"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["LimitAPI"].__doc__ = """
The PhysicsLimitAPI can be applied to a PhysicsJoint and will restrict
the movement along an axis. PhysicsLimitAPI is a multipleApply schema:
The PhysicsJoint can be restricted
along"transX","transY","transZ","rotX","rotY","rotZ","distance".
Setting these as a multipleApply schema TfToken name will define the
degree of freedom the PhysicsLimitAPI is applied to. Note that if the
low limit is higher than the high limit, motion along this axis is
considered locked.
"""
result["LimitAPI"].__init__.func_doc = """__init__(prim, name)
Construct a UsdPhysicsLimitAPI on UsdPrim ``prim`` with name ``name``
.
Equivalent to UsdPhysicsLimitAPI::Get ( prim.GetStage(),
prim.GetPath().AppendProperty("limit:name"));
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
name : str
----------------------------------------------------------------------
__init__(schemaObj, name)
Construct a UsdPhysicsLimitAPI on the prim held by ``schemaObj`` with
name ``name`` .
Should be preferred over UsdPhysicsLimitAPI (schemaObj.GetPrim(),
name), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
name : str
"""
result["LimitAPI"].GetLowAttr.func_doc = """GetLowAttr() -> Attribute
Lower limit.
Units: degrees or distance depending on trans or rot axis applied to.
\\-inf means not limited in negative direction.
Declaration
``float physics:low = -inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["LimitAPI"].CreateLowAttr.func_doc = """CreateLowAttr(defaultValue, writeSparsely) -> Attribute
See GetLowAttr() , and also Create vs Get Property Methods for when to
use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LimitAPI"].GetHighAttr.func_doc = """GetHighAttr() -> Attribute
Upper limit.
Units: degrees or distance depending on trans or rot axis applied to.
inf means not limited in positive direction.
Declaration
``float physics:high = inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["LimitAPI"].CreateHighAttr.func_doc = """CreateHighAttr(defaultValue, writeSparsely) -> Attribute
See GetHighAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LimitAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
----------------------------------------------------------------------
GetSchemaAttributeNames(includeInherited, instanceName) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes for a given instance name.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved. The names returned will have the
proper namespace prefix.
Parameters
----------
includeInherited : bool
instanceName : str
"""
result["LimitAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> LimitAPI
Return a UsdPhysicsLimitAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
``path`` must be of the format<path>.limit:name.
This is shorthand for the following:
.. code-block:: text
TfToken name = SdfPath::StripNamespace(path.GetToken());
UsdPhysicsLimitAPI(
stage->GetPrimAtPath(path.GetPrimPath()), name);
Parameters
----------
stage : Stage
path : Path
----------------------------------------------------------------------
Get(prim, name) -> LimitAPI
Return a UsdPhysicsLimitAPI with name ``name`` holding the prim
``prim`` .
Shorthand for UsdPhysicsLimitAPI(prim, name);
Parameters
----------
prim : Prim
name : str
"""
result["LimitAPI"].GetAll.func_doc = """**classmethod** GetAll(prim) -> list[LimitAPI]
Return a vector of all named instances of UsdPhysicsLimitAPI on the
given ``prim`` .
Parameters
----------
prim : Prim
"""
result["LimitAPI"].IsPhysicsLimitAPIPath.func_doc = """**classmethod** IsPhysicsLimitAPIPath(path, name) -> bool
Checks if the given path ``path`` is of an API schema of type
PhysicsLimitAPI.
If so, it stores the instance name of the schema in ``name`` and
returns true. Otherwise, it returns false.
Parameters
----------
path : Path
name : str
"""
result["LimitAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, name, whyNot) -> bool
Returns true if this **multiple-apply** API schema can be applied,
with the given instance name, ``name`` , to the given ``prim`` .
If this schema can not be a applied the prim, this returns false and,
if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
name : str
whyNot : str
"""
result["LimitAPI"].Apply.func_doc = """**classmethod** Apply(prim, name) -> LimitAPI
Applies this **multiple-apply** API schema to the given ``prim`` along
with the given instance name, ``name`` .
This information is stored by adding"PhysicsLimitAPI:<i>name</i>"to
the token-valued, listOp metadata *apiSchemas* on the prim. For
example, if ``name`` is'instance1', the
token'PhysicsLimitAPI:instance1'is added to'apiSchemas'.
A valid UsdPhysicsLimitAPI object is returned upon success. An invalid
(or empty) UsdPhysicsLimitAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
name : str
"""
result["LimitAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["MassAPI"].__doc__ = """
Defines explicit mass properties (mass, density, inertia etc.).
MassAPI can be applied to any object that has a PhysicsCollisionAPI or
a PhysicsRigidBodyAPI.
"""
result["MassAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsMassAPI on UsdPrim ``prim`` .
Equivalent to UsdPhysicsMassAPI::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsMassAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdPhysicsMassAPI (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["MassAPI"].GetMassAttr.func_doc = """GetMassAttr() -> Attribute
If non-zero, directly specifies the mass of the object.
Note that any child prim can also have a mass when they apply massAPI.
In this case, the precedence rule is'parent mass overrides the
child's'. This may come as counter-intuitive, but mass is a computed
quantity and in general not accumulative. For example, if a parent has
mass of 10, and one of two children has mass of 20, allowing child's
mass to override its parent results in a mass of -10 for the other
child. Note if mass is 0.0 it is ignored. Units: mass.
Declaration
``float physics:mass = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["MassAPI"].CreateMassAttr.func_doc = """CreateMassAttr(defaultValue, writeSparsely) -> Attribute
See GetMassAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MassAPI"].GetDensityAttr.func_doc = """GetDensityAttr() -> Attribute
If non-zero, specifies the density of the object.
In the context of rigid body physics, density indirectly results in
setting mass via (mass = density x volume of the object). How the
volume is computed is up to implementation of the physics system. It
is generally computed from the collision approximation rather than the
graphical mesh. In the case where both density and mass are specified
for the same object, mass has precedence over density. Unlike mass,
child's prim's density overrides parent prim's density as it is
accumulative. Note that density of a collisionAPI can be also
alternatively set through a PhysicsMaterialAPI. The material density
has the weakest precedence in density definition. Note if density is
0.0 it is ignored. Units: mass/distance/distance/distance.
Declaration
``float physics:density = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["MassAPI"].CreateDensityAttr.func_doc = """CreateDensityAttr(defaultValue, writeSparsely) -> Attribute
See GetDensityAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MassAPI"].GetCenterOfMassAttr.func_doc = """GetCenterOfMassAttr() -> Attribute
Center of mass in the prim's local space.
Units: distance.
Declaration
``point3f physics:centerOfMass = (-inf, -inf, -inf)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Point3f
"""
result["MassAPI"].CreateCenterOfMassAttr.func_doc = """CreateCenterOfMassAttr(defaultValue, writeSparsely) -> Attribute
See GetCenterOfMassAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MassAPI"].GetDiagonalInertiaAttr.func_doc = """GetDiagonalInertiaAttr() -> Attribute
If non-zero, specifies diagonalized inertia tensor along the principal
axes.
Note if diagonalInertial is (0.0, 0.0, 0.0) it is ignored. Units:
mass\\*distance\\*distance.
Declaration
``float3 physics:diagonalInertia = (0, 0, 0)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Float3
"""
result["MassAPI"].CreateDiagonalInertiaAttr.func_doc = """CreateDiagonalInertiaAttr(defaultValue, writeSparsely) -> Attribute
See GetDiagonalInertiaAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MassAPI"].GetPrincipalAxesAttr.func_doc = """GetPrincipalAxesAttr() -> Attribute
Orientation of the inertia tensor's principal axes in the prim's local
space.
Declaration
``quatf physics:principalAxes = (0, 0, 0, 0)``
C++ Type
GfQuatf
Usd Type
SdfValueTypeNames->Quatf
"""
result["MassAPI"].CreatePrincipalAxesAttr.func_doc = """CreatePrincipalAxesAttr(defaultValue, writeSparsely) -> Attribute
See GetPrincipalAxesAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MassAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["MassAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> MassAPI
Return a UsdPhysicsMassAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsMassAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["MassAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["MassAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> MassAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"PhysicsMassAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdPhysicsMassAPI object is returned upon success. An invalid
(or empty) UsdPhysicsMassAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["MassAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["MassUnits"].__doc__ = """
Container class for static double-precision symbols representing
common mass units of measure expressed in kilograms.
"""
result["MaterialAPI"].__doc__ = """
Adds simulation material properties to a Material. All collisions that
have a relationship to this material will have their collision
response defined through this material.
"""
result["MaterialAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsMaterialAPI on UsdPrim ``prim`` .
Equivalent to UsdPhysicsMaterialAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsMaterialAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdPhysicsMaterialAPI (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["MaterialAPI"].GetDynamicFrictionAttr.func_doc = """GetDynamicFrictionAttr() -> Attribute
Dynamic friction coefficient.
Unitless.
Declaration
``float physics:dynamicFriction = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["MaterialAPI"].CreateDynamicFrictionAttr.func_doc = """CreateDynamicFrictionAttr(defaultValue, writeSparsely) -> Attribute
See GetDynamicFrictionAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MaterialAPI"].GetStaticFrictionAttr.func_doc = """GetStaticFrictionAttr() -> Attribute
Static friction coefficient.
Unitless.
Declaration
``float physics:staticFriction = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["MaterialAPI"].CreateStaticFrictionAttr.func_doc = """CreateStaticFrictionAttr(defaultValue, writeSparsely) -> Attribute
See GetStaticFrictionAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MaterialAPI"].GetRestitutionAttr.func_doc = """GetRestitutionAttr() -> Attribute
Restitution coefficient.
Unitless.
Declaration
``float physics:restitution = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["MaterialAPI"].CreateRestitutionAttr.func_doc = """CreateRestitutionAttr(defaultValue, writeSparsely) -> Attribute
See GetRestitutionAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MaterialAPI"].GetDensityAttr.func_doc = """GetDensityAttr() -> Attribute
If non-zero, defines the density of the material.
This can be used for body mass computation, see PhysicsMassAPI. Note
that if the density is 0.0 it is ignored. Units:
mass/distance/distance/distance.
Declaration
``float physics:density = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["MaterialAPI"].CreateDensityAttr.func_doc = """CreateDensityAttr(defaultValue, writeSparsely) -> Attribute
See GetDensityAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MaterialAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["MaterialAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> MaterialAPI
Return a UsdPhysicsMaterialAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsMaterialAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["MaterialAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["MaterialAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> MaterialAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"PhysicsMaterialAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdPhysicsMaterialAPI object is returned upon success. An
invalid (or empty) UsdPhysicsMaterialAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["MaterialAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["MeshCollisionAPI"].__doc__ = """
Attributes to control how a Mesh is made into a collider. Can be
applied to only a USDGeomMesh in addition to its PhysicsCollisionAPI.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdPhysicsTokens. So to set an attribute to the value"rightHanded",
use UsdPhysicsTokens->rightHanded as the value.
"""
result["MeshCollisionAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsMeshCollisionAPI on UsdPrim ``prim`` .
Equivalent to UsdPhysicsMeshCollisionAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsMeshCollisionAPI on the prim held by
``schemaObj`` .
Should be preferred over UsdPhysicsMeshCollisionAPI
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["MeshCollisionAPI"].GetApproximationAttr.func_doc = """GetApproximationAttr() -> Attribute
Determines the mesh's collision approximation:"none"- The mesh
geometry is used directly as a collider without any approximation.
"convexDecomposition"- A convex mesh decomposition is performed. This
results in a set of convex mesh colliders."convexHull"- A convex hull
of the mesh is generated and used as the collider."boundingSphere"- A
bounding sphere is computed around the mesh and used as a
collider."boundingCube"- An optimally fitting box collider is computed
around the mesh."meshSimplification"- A mesh simplification step is
performed, resulting in a simplified triangle mesh collider.
Declaration
``uniform token physics:approximation ="none"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
none, convexDecomposition, convexHull, boundingSphere, boundingCube,
meshSimplification
"""
result["MeshCollisionAPI"].CreateApproximationAttr.func_doc = """CreateApproximationAttr(defaultValue, writeSparsely) -> Attribute
See GetApproximationAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MeshCollisionAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["MeshCollisionAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> MeshCollisionAPI
Return a UsdPhysicsMeshCollisionAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsMeshCollisionAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["MeshCollisionAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["MeshCollisionAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> MeshCollisionAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"PhysicsMeshCollisionAPI"to the
token-valued, listOp metadata *apiSchemas* on the prim.
A valid UsdPhysicsMeshCollisionAPI object is returned upon success. An
invalid (or empty) UsdPhysicsMeshCollisionAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["MeshCollisionAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["PrismaticJoint"].__doc__ = """
Predefined prismatic joint type (translation along prismatic joint
axis is permitted.)
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdPhysicsTokens. So to set an attribute to the value"rightHanded",
use UsdPhysicsTokens->rightHanded as the value.
"""
result["PrismaticJoint"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsPrismaticJoint on UsdPrim ``prim`` .
Equivalent to UsdPhysicsPrismaticJoint::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsPrismaticJoint on the prim held by ``schemaObj``
.
Should be preferred over UsdPhysicsPrismaticJoint
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["PrismaticJoint"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute
Joint axis.
Declaration
``uniform token physics:axis ="X"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
X, Y, Z
"""
result["PrismaticJoint"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute
See GetAxisAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PrismaticJoint"].GetLowerLimitAttr.func_doc = """GetLowerLimitAttr() -> Attribute
Lower limit.
Units: distance. -inf means not limited in negative direction.
Declaration
``float physics:lowerLimit = -inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["PrismaticJoint"].CreateLowerLimitAttr.func_doc = """CreateLowerLimitAttr(defaultValue, writeSparsely) -> Attribute
See GetLowerLimitAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PrismaticJoint"].GetUpperLimitAttr.func_doc = """GetUpperLimitAttr() -> Attribute
Upper limit.
Units: distance. inf means not limited in positive direction.
Declaration
``float physics:upperLimit = inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["PrismaticJoint"].CreateUpperLimitAttr.func_doc = """CreateUpperLimitAttr(defaultValue, writeSparsely) -> Attribute
See GetUpperLimitAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PrismaticJoint"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["PrismaticJoint"].Get.func_doc = """**classmethod** Get(stage, path) -> PrismaticJoint
Return a UsdPhysicsPrismaticJoint holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsPrismaticJoint(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["PrismaticJoint"].Define.func_doc = """**classmethod** Define(stage, path) -> PrismaticJoint
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["PrismaticJoint"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["RevoluteJoint"].__doc__ = """
Predefined revolute joint type (rotation along revolute joint axis is
permitted.)
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdPhysicsTokens. So to set an attribute to the value"rightHanded",
use UsdPhysicsTokens->rightHanded as the value.
"""
result["RevoluteJoint"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsRevoluteJoint on UsdPrim ``prim`` .
Equivalent to UsdPhysicsRevoluteJoint::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsRevoluteJoint on the prim held by ``schemaObj``
.
Should be preferred over UsdPhysicsRevoluteJoint
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["RevoluteJoint"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute
Joint axis.
Declaration
``uniform token physics:axis ="X"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
X, Y, Z
"""
result["RevoluteJoint"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute
See GetAxisAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RevoluteJoint"].GetLowerLimitAttr.func_doc = """GetLowerLimitAttr() -> Attribute
Lower limit.
Units: degrees. -inf means not limited in negative direction.
Declaration
``float physics:lowerLimit = -inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["RevoluteJoint"].CreateLowerLimitAttr.func_doc = """CreateLowerLimitAttr(defaultValue, writeSparsely) -> Attribute
See GetLowerLimitAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RevoluteJoint"].GetUpperLimitAttr.func_doc = """GetUpperLimitAttr() -> Attribute
Upper limit.
Units: degrees. inf means not limited in positive direction.
Declaration
``float physics:upperLimit = inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["RevoluteJoint"].CreateUpperLimitAttr.func_doc = """CreateUpperLimitAttr(defaultValue, writeSparsely) -> Attribute
See GetUpperLimitAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RevoluteJoint"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["RevoluteJoint"].Get.func_doc = """**classmethod** Get(stage, path) -> RevoluteJoint
Return a UsdPhysicsRevoluteJoint holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsRevoluteJoint(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["RevoluteJoint"].Define.func_doc = """**classmethod** Define(stage, path) -> RevoluteJoint
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["RevoluteJoint"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["RigidBodyAPI"].__doc__ = """
Applies physics body attributes to any UsdGeomXformable prim and marks
that prim to be driven by a simulation. If a simulation is running it
will update this prim's pose. All prims in the hierarchy below this
prim should move accordingly.
"""
result["RigidBodyAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsRigidBodyAPI on UsdPrim ``prim`` .
Equivalent to UsdPhysicsRigidBodyAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsRigidBodyAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdPhysicsRigidBodyAPI (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["RigidBodyAPI"].GetRigidBodyEnabledAttr.func_doc = """GetRigidBodyEnabledAttr() -> Attribute
Determines if this PhysicsRigidBodyAPI is enabled.
Declaration
``bool physics:rigidBodyEnabled = 1``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["RigidBodyAPI"].CreateRigidBodyEnabledAttr.func_doc = """CreateRigidBodyEnabledAttr(defaultValue, writeSparsely) -> Attribute
See GetRigidBodyEnabledAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RigidBodyAPI"].GetKinematicEnabledAttr.func_doc = """GetKinematicEnabledAttr() -> Attribute
Determines whether the body is kinematic or not.
A kinematic body is a body that is moved through animated poses or
through user defined poses. The simulation derives velocities for the
kinematic body based on the external motion. When a continuous motion
is not desired, this kinematic flag should be set to false.
Declaration
``bool physics:kinematicEnabled = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["RigidBodyAPI"].CreateKinematicEnabledAttr.func_doc = """CreateKinematicEnabledAttr(defaultValue, writeSparsely) -> Attribute
See GetKinematicEnabledAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RigidBodyAPI"].GetStartsAsleepAttr.func_doc = """GetStartsAsleepAttr() -> Attribute
Determines if the body is asleep when the simulation starts.
Declaration
``uniform bool physics:startsAsleep = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
Variability
SdfVariabilityUniform
"""
result["RigidBodyAPI"].CreateStartsAsleepAttr.func_doc = """CreateStartsAsleepAttr(defaultValue, writeSparsely) -> Attribute
See GetStartsAsleepAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RigidBodyAPI"].GetVelocityAttr.func_doc = """GetVelocityAttr() -> Attribute
Linear velocity in the same space as the node's xform.
Units: distance/second.
Declaration
``vector3f physics:velocity = (0, 0, 0)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Vector3f
"""
result["RigidBodyAPI"].CreateVelocityAttr.func_doc = """CreateVelocityAttr(defaultValue, writeSparsely) -> Attribute
See GetVelocityAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RigidBodyAPI"].GetAngularVelocityAttr.func_doc = """GetAngularVelocityAttr() -> Attribute
Angular velocity in the same space as the node's xform.
Units: degrees/second.
Declaration
``vector3f physics:angularVelocity = (0, 0, 0)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Vector3f
"""
result["RigidBodyAPI"].CreateAngularVelocityAttr.func_doc = """CreateAngularVelocityAttr(defaultValue, writeSparsely) -> Attribute
See GetAngularVelocityAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RigidBodyAPI"].GetSimulationOwnerRel.func_doc = """GetSimulationOwnerRel() -> Relationship
Single PhysicsScene that will simulate this body.
By default this is the first PhysicsScene found in the stage using
UsdStage::Traverse() .
"""
result["RigidBodyAPI"].CreateSimulationOwnerRel.func_doc = """CreateSimulationOwnerRel() -> Relationship
See GetSimulationOwnerRel() , and also Create vs Get Property Methods
for when to use Get vs Create.
"""
result["RigidBodyAPI"].ComputeMassProperties.func_doc = """ComputeMassProperties(diagonalInertia, com, principalAxes, massInfoFn) -> float
Compute mass properties of the rigid body ``diagonalInertia`` Computed
diagonal of the inertial tensor for the rigid body.
``com`` Computed center of mass for the rigid body. ``principalAxes``
Inertia tensor's principal axes orienttion for the rigid body.
``massInfoFn`` Callback function to get collision mass information.
Computed mass of the rigid body
Parameters
----------
diagonalInertia : Vec3f
com : Vec3f
principalAxes : Quatf
massInfoFn : MassInformationFn
"""
result["RigidBodyAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["RigidBodyAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> RigidBodyAPI
Return a UsdPhysicsRigidBodyAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsRigidBodyAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["RigidBodyAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["RigidBodyAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> RigidBodyAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"PhysicsRigidBodyAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdPhysicsRigidBodyAPI object is returned upon success. An
invalid (or empty) UsdPhysicsRigidBodyAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["RigidBodyAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Scene"].__doc__ = """
General physics simulation properties, required for simulation.
"""
result["Scene"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsScene on UsdPrim ``prim`` .
Equivalent to UsdPhysicsScene::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsScene on the prim held by ``schemaObj`` .
Should be preferred over UsdPhysicsScene (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Scene"].GetGravityDirectionAttr.func_doc = """GetGravityDirectionAttr() -> Attribute
Gravity direction vector in simulation world space.
Will be normalized before use. A zero vector is a request to use the
negative upAxis. Unitless.
Declaration
``vector3f physics:gravityDirection = (0, 0, 0)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Vector3f
"""
result["Scene"].CreateGravityDirectionAttr.func_doc = """CreateGravityDirectionAttr(defaultValue, writeSparsely) -> Attribute
See GetGravityDirectionAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Scene"].GetGravityMagnitudeAttr.func_doc = """GetGravityMagnitudeAttr() -> Attribute
Gravity acceleration magnitude in simulation world space.
A negative value is a request to use a value equivalent to earth
gravity regardless of the metersPerUnit scaling used by this scene.
Units: distance/second/second.
Declaration
``float physics:gravityMagnitude = -inf``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Scene"].CreateGravityMagnitudeAttr.func_doc = """CreateGravityMagnitudeAttr(defaultValue, writeSparsely) -> Attribute
See GetGravityMagnitudeAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Scene"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Scene"].Get.func_doc = """**classmethod** Get(stage, path) -> Scene
Return a UsdPhysicsScene holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsScene(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Scene"].Define.func_doc = """**classmethod** Define(stage, path) -> Scene
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Scene"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["SphericalJoint"].__doc__ = """
Predefined spherical joint type (Removes linear degrees of freedom,
cone limit may restrict the motion in a given range.) It allows two
limit values, which when equal create a circular, else an elliptic
cone limit around the limit axis.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdPhysicsTokens. So to set an attribute to the value"rightHanded",
use UsdPhysicsTokens->rightHanded as the value.
"""
result["SphericalJoint"].__init__.func_doc = """__init__(prim)
Construct a UsdPhysicsSphericalJoint on UsdPrim ``prim`` .
Equivalent to UsdPhysicsSphericalJoint::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdPhysicsSphericalJoint on the prim held by ``schemaObj``
.
Should be preferred over UsdPhysicsSphericalJoint
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["SphericalJoint"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute
Cone limit axis.
Declaration
``uniform token physics:axis ="X"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
X, Y, Z
"""
result["SphericalJoint"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute
See GetAxisAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SphericalJoint"].GetConeAngle0LimitAttr.func_doc = """GetConeAngle0LimitAttr() -> Attribute
Cone limit from the primary joint axis in the local0 frame toward the
next axis.
(Next axis of X is Y, and of Z is X.) A negative value means not
limited. Units: degrees.
Declaration
``float physics:coneAngle0Limit = -1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["SphericalJoint"].CreateConeAngle0LimitAttr.func_doc = """CreateConeAngle0LimitAttr(defaultValue, writeSparsely) -> Attribute
See GetConeAngle0LimitAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SphericalJoint"].GetConeAngle1LimitAttr.func_doc = """GetConeAngle1LimitAttr() -> Attribute
Cone limit from the primary joint axis in the local0 frame toward the
second to next axis.
A negative value means not limited. Units: degrees.
Declaration
``float physics:coneAngle1Limit = -1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["SphericalJoint"].CreateConeAngle1LimitAttr.func_doc = """CreateConeAngle1LimitAttr(defaultValue, writeSparsely) -> Attribute
See GetConeAngle1LimitAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SphericalJoint"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["SphericalJoint"].Get.func_doc = """**classmethod** Get(stage, path) -> SphericalJoint
Return a UsdPhysicsSphericalJoint holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdPhysicsSphericalJoint(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["SphericalJoint"].Define.func_doc = """**classmethod** Define(stage, path) -> SphericalJoint
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["SphericalJoint"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
""" | 104,653 | Python | 20.249543 | 145 | 0.721862 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Work/__DOC.py | def Execute(result):
pass | 29 | Python | 13.999993 | 20 | 0.689655 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Ar/__DOC.py | def Execute(result):
result["DefaultResolver"].__doc__ = """
Default asset resolution implementation used when no plugin
implementation is provided.
In order to resolve assets specified by relative paths, this resolver
implements a simple"search path"scheme. The resolver will anchor the
relative path to a series of directories and return the first absolute
path where the asset exists.
The first directory will always be the current working directory. The
resolver will then examine the directories specified via the following
mechanisms (in order):
- The currently-bound ArDefaultResolverContext for the calling
thread
- ArDefaultResolver::SetDefaultSearchPath
- The environment variable PXR_AR_DEFAULT_SEARCH_PATH. This is
expected to be a list of directories delimited by the platform's
standard path separator.
ArDefaultResolver supports creating an ArDefaultResolverContext via
ArResolver::CreateContextFromString by passing a list of directories
delimited by the platform's standard path separator.
"""
result["DefaultResolver"].SetDefaultSearchPath.func_doc = """**classmethod** SetDefaultSearchPath(searchPath) -> None
Set the default search path that will be used during asset resolution.
This must be called before the first call to ArGetResolver. The
specified paths will be searched *in addition to, and before* paths
specified via the environment variable PXR_AR_DEFAULT_SEARCH_PATH
Parameters
----------
searchPath : list[str]
"""
result["DefaultResolverContext"].__doc__ = """
Resolver context object that specifies a search path to use during
asset resolution. This object is intended for use with the default
ArDefaultResolver asset resolution implementation; see documentation
for that class for more details on the search path resolution
algorithm.
Example usage:
.. code-block:: text
ArDefaultResolverContext ctx({"/Local/Models", "/Installed/Models"});
{
// Bind the context object:
ArResolverContextBinder binder(ctx);
// While the context is bound, all calls to ArResolver::Resolve
// (assuming ArDefaultResolver is the underlying implementation being
// used) will include the specified paths during resolution.
std::string resolvedPath = resolver.Resolve("ModelName/File.txt")
}
// Once the context is no longer bound (due to the ArResolverContextBinder
// going out of scope), its search path no longer factors into asset
// resolution.
"""
result["DefaultResolverContext"].__init__.func_doc = """__init__()
Default construct a context with no search path.
----------------------------------------------------------------------
__init__(searchPath)
Construct a context with the given ``searchPath`` .
Elements in ``searchPath`` should be absolute paths. If they are not,
they will be anchored to the current working directory.
Parameters
----------
searchPath : list[str]
"""
result["DefaultResolverContext"].GetSearchPath.func_doc = """GetSearchPath() -> list[str]
Return this context's search path.
"""
result["Notice"].__doc__ = """"""
result["ResolvedPath"].__doc__ = """
Represents a resolved asset path.
"""
result["ResolvedPath"].__init__.func_doc = """__init__(resolvedPath)
Construct an ArResolvedPath holding the given ``resolvedPath`` .
Parameters
----------
resolvedPath : str
----------------------------------------------------------------------
__init__(resolvedPath)
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
resolvedPath : str
----------------------------------------------------------------------
__init__()
----------------------------------------------------------------------
__init__(rhs)
Parameters
----------
rhs : ResolvedPath
----------------------------------------------------------------------
__init__(rhs)
Parameters
----------
rhs : ResolvedPath
"""
result["ResolvedPath"].GetPathString.func_doc = """GetPathString() -> str
Return the resolved path held by this object as a string.
"""
result["Resolver"].__doc__ = """
Interface for the asset resolution system. An asset resolver is
responsible for resolving asset information (including the asset's
physical path) from a logical path.
See ar_implementing_resolver for information on how to customize asset
resolution behavior by implementing a subclass of ArResolver. Clients
may use ArGetResolver to access the configured asset resolver.
"""
result["Resolver"].CreateIdentifier.func_doc = """CreateIdentifier(assetPath, anchorAssetPath) -> str
Returns an identifier for the asset specified by ``assetPath`` .
If ``anchorAssetPath`` is not empty, it is the resolved asset path
that ``assetPath`` should be anchored to if it is a relative path.
Parameters
----------
assetPath : str
anchorAssetPath : ResolvedPath
"""
result["Resolver"].CreateIdentifierForNewAsset.func_doc = """CreateIdentifierForNewAsset(assetPath, anchorAssetPath) -> str
Returns an identifier for a new asset specified by ``assetPath`` .
If ``anchorAssetPath`` is not empty, it is the resolved asset path
that ``assetPath`` should be anchored to if it is a relative path.
Parameters
----------
assetPath : str
anchorAssetPath : ResolvedPath
"""
result["Resolver"].Resolve.func_doc = """Resolve(assetPath) -> ResolvedPath
Returns the resolved path for the asset identified by the given
``assetPath`` if it exists.
If the asset does not exist, returns an empty ArResolvedPath.
Parameters
----------
assetPath : str
"""
result["Resolver"].ResolveForNewAsset.func_doc = """ResolveForNewAsset(assetPath) -> ResolvedPath
Returns the resolved path for the given ``assetPath`` that may be used
to create a new asset.
If such a path cannot be computed for ``assetPath`` , returns an empty
ArResolvedPath.
Note that an asset might or might not already exist at the returned
resolved path.
Parameters
----------
assetPath : str
"""
result["Resolver"].CreateDefaultContext.func_doc = """CreateDefaultContext() -> ResolverContext
Return an ArResolverContext that may be bound to this resolver to
resolve assets when no other context is explicitly specified.
The returned ArResolverContext will contain the default context
returned by the primary resolver and all URI resolvers.
"""
result["Resolver"].CreateDefaultContextForAsset.func_doc = """CreateDefaultContextForAsset(assetPath) -> ResolverContext
Return an ArResolverContext that may be bound to this resolver to
resolve the asset located at ``assetPath`` or referenced by that asset
when no other context is explicitly specified.
The returned ArResolverContext will contain the default context for
``assetPath`` returned by the primary resolver and all URI resolvers.
Parameters
----------
assetPath : str
"""
result["Resolver"].CreateContextFromString.func_doc = """CreateContextFromString(contextStr) -> ResolverContext
Return an ArResolverContext created from the primary ArResolver
implementation using the given ``contextStr`` .
Parameters
----------
contextStr : str
----------------------------------------------------------------------
CreateContextFromString(uriScheme, contextStr) -> ResolverContext
Return an ArResolverContext created from the ArResolver registered for
the given ``uriScheme`` using the given ``contextStr`` .
An empty ``uriScheme`` indicates the primary resolver and is
equivalent to CreateContextFromString(string).
If no resolver is registered for ``uriScheme`` , returns an empty
ArResolverContext.
Parameters
----------
uriScheme : str
contextStr : str
"""
result["Resolver"].CreateContextFromStrings.func_doc = """CreateContextFromStrings(contextStrs) -> ResolverContext
Return an ArResolverContext created by combining the ArResolverContext
objects created from the given ``contextStrs`` .
``contextStrs`` is a list of pairs of strings. The first element in
the pair is the URI scheme for the ArResolver that will be used to
create the ArResolverContext from the second element in the pair. An
empty URI scheme indicates the primary resolver.
For example:
.. code-block:: text
ArResolverContext ctx = ArGetResolver().CreateContextFromStrings(
{ {"", "context str 1"},
{"my_scheme", "context str 2"} });
This will use the primary resolver to create an ArResolverContext
using the string"context str 1"and use the resolver registered for
the"my_scheme"URI scheme to create an ArResolverContext using"context
str 2". These contexts will be combined into a single
ArResolverContext and returned.
If no resolver is registered for a URI scheme in an entry in
``contextStrs`` , that entry will be ignored.
Parameters
----------
contextStrs : list[tuple[str, str]]
"""
result["Resolver"].RefreshContext.func_doc = """RefreshContext(context) -> None
Refresh any caches associated with the given context.
If doing so would invalidate asset paths that had previously been
resolved, an ArNotice::ResolverChanged notice will be sent to inform
clients of this.
Parameters
----------
context : ResolverContext
"""
result["Resolver"].GetCurrentContext.func_doc = """GetCurrentContext() -> ResolverContext
Returns the asset resolver context currently bound in this thread.
ArResolver::BindContext, ArResolver::UnbindContext
"""
result["Resolver"].IsContextDependentPath.func_doc = """IsContextDependentPath(assetPath) -> bool
Returns true if ``assetPath`` is a context-dependent path, false
otherwise.
A context-dependent path may result in different resolved paths
depending on what asset resolver context is bound when Resolve is
called. Assets located at the same context-dependent path may not be
the same since those assets may have been loaded from different
resolved paths. In this case, the assets'resolved paths must be
consulted to determine if they are the same.
Parameters
----------
assetPath : str
"""
result["Resolver"].GetExtension.func_doc = """GetExtension(assetPath) -> str
Returns the file extension for the given ``assetPath`` .
The returned extension does not include a"."at the beginning.
Parameters
----------
assetPath : str
"""
result["Resolver"].GetAssetInfo.func_doc = """GetAssetInfo(assetPath, resolvedPath) -> ArAssetInfo
Returns an ArAssetInfo populated with additional metadata (if any)
about the asset at the given ``assetPath`` .
``resolvedPath`` is the resolved path computed for the given
``assetPath`` .
Parameters
----------
assetPath : str
resolvedPath : ResolvedPath
"""
result["Resolver"].GetModificationTimestamp.func_doc = """GetModificationTimestamp(assetPath, resolvedPath) -> Timestamp
Returns an ArTimestamp representing the last time the asset at
``assetPath`` was modified.
``resolvedPath`` is the resolved path computed for the given
``assetPath`` . If a timestamp cannot be retrieved, return an invalid
ArTimestamp.
Parameters
----------
assetPath : str
resolvedPath : ResolvedPath
"""
result["Resolver"].CanWriteAssetToPath.func_doc = """CanWriteAssetToPath(resolvedPath, whyNot) -> bool
Returns true if an asset may be written to the given ``resolvedPath``
, false otherwise.
If this function returns false and ``whyNot`` is not ``nullptr`` , it
may be filled with an explanation.
Parameters
----------
resolvedPath : ResolvedPath
whyNot : str
"""
result["ResolverContext"].__doc__ = """
An asset resolver context allows clients to provide additional data to
the resolver for use during resolution. Clients may provide this data
via context objects of their own (subject to restrictions below). An
ArResolverContext is simply a wrapper around these objects that allows
it to be treated as a single type. Note that an ArResolverContext may
not hold multiple context objects with the same type.
A client-defined context object must provide the following:
- Default and copy constructors
- operator<
- operator==
- An overload for size_t hash_value(const T&)
Note that the user may define a free function:
std::string ArGetDebugString(const Context & ctx); (Where Context is
the type of the user's path resolver context.)
This is optional; a default generic implementation has been
predefined. This function should return a string representation of the
context to be utilized for debugging purposes(such as in TF_DEBUG
statements).
The ArIsContextObject template must also be specialized for this
object to declare that it can be used as a context object. This is to
avoid accidental use of an unexpected object as a context object. The
AR_DECLARE_RESOLVER_CONTEXT macro can be used to do this as a
convenience.
AR_DECLARE_RESOLVER_CONTEXT
ArResolver::BindContext
ArResolver::UnbindContext
ArResolverContextBinder
"""
result["ResolverContext"].__init__.func_doc = """__init__()
Construct an empty asset resolver context.
----------------------------------------------------------------------
__init__(objs)
Construct a resolver context using the given objects ``objs`` .
Each argument must either be an ArResolverContext or a registered
context object. See class documentation for requirements on context
objects.
If an argument is a context object, it will be added to the
constructed ArResolverContext. If an argument is an ArResolverContext,
all of the context objects it holds will be added to the constructed
ArResolverContext.
Arguments are ordered from strong-to-weak. If a context object is
encountered with the same type as a previously-added object, the
previously-added object will remain and the other context object will
be ignored.
Parameters
----------
objs : Objects...
----------------------------------------------------------------------
__init__(ctxs)
Construct a resolver context using the ArResolverContexts in ``ctxs``
.
All of the context objects held by each ArResolverContext in ``ctxs``
will be added to the constructed ArResolverContext.
Arguments are ordered from strong-to-weak. If a context object is
encountered with the same type as a previously-added object, the
previously-added object will remain and the other context object will
be ignored.
Parameters
----------
ctxs : list[ResolverContext]
"""
result["ResolverContext"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns whether this resolver context is empty.
"""
result["ResolverContext"].Get.func_doc = """Get() -> ContextObj
Returns pointer to the context object of the given type held in this
resolver context.
Returns None if this resolver context is not holding an object of the
requested type.
"""
result["ResolverContext"].GetDebugString.func_doc = """GetDebugString() -> str
Returns a debug string representing the contained context objects.
"""
result["ResolverContextBinder"].__doc__ = """
Helper object for managing the binding and unbinding of
ArResolverContext objects with the asset resolver.
Asset Resolver Context Operations
"""
result["ResolverContextBinder"].__init__.func_doc = """__init__(context)
Bind the given ``context`` with the asset resolver.
Calls ArResolver::BindContext on the configured asset resolver and
saves the bindingData populated by that function.
Parameters
----------
context : ResolverContext
----------------------------------------------------------------------
__init__(assetResolver, context)
Bind the given ``context`` to the given ``assetResolver`` .
Calls ArResolver::BindContext on the given ``assetResolver`` and saves
the bindingData populated by that function.
Parameters
----------
assetResolver : Resolver
context : ResolverContext
"""
result["ResolverScopedCache"].__doc__ = """
Helper object for managing asset resolver cache scopes.
A scoped resolution cache indicates to the resolver that results of
calls to Resolve should be cached for a certain scope. This is
important for performance and also for consistency it ensures that
repeated calls to Resolve with the same parameters will return the
same result.
Scoped Resolution Cache
"""
result["ResolverScopedCache"].__init__.func_doc = """__init__(arg1)
Parameters
----------
arg1 : ResolverScopedCache
----------------------------------------------------------------------
__init__()
Begin an asset resolver cache scope.
Calls ArResolver::BeginCacheScope on the configured asset resolver and
saves the cacheScopeData populated by that function.
----------------------------------------------------------------------
__init__(parent)
Begin an asset resolver cache scope that shares data with the given
``parent`` scope.
Calls ArResolver::BeginCacheScope on the configured asset resolver,
saves the cacheScopeData stored in ``parent`` and passes that to that
function.
Parameters
----------
parent : ResolverScopedCache
"""
result["Timestamp"].__doc__ = """
Represents a timestamp for an asset. Timestamps are represented by
Unix time, the number of seconds elapsed since 00:00:00 UTC 1/1/1970.
"""
result["Timestamp"].__init__.func_doc = """__init__()
Create an invalid timestamp.
----------------------------------------------------------------------
__init__(time)
Create a timestamp at ``time`` , which must be a Unix time value.
Parameters
----------
time : float
"""
result["Timestamp"].IsValid.func_doc = """IsValid() -> bool
Return true if this timestamp is valid, false otherwise.
"""
result["Timestamp"].GetTime.func_doc = """GetTime() -> float
Return the time represented by this timestamp as a double.
If this timestamp is invalid, issue a coding error and return a quiet
NaN value.
""" | 17,675 | Python | 22.166448 | 126 | 0.709873 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Tf/__init__.py | #
# Copyright 2016 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.
#
"""
Tf -- Tools Foundation
"""
# Type to help handle DLL import paths on Windows with python interpreters v3.8
# and newer. These interpreters don't search for DLLs in the path anymore, you
# have to provide a path explicitly. This re-enables path searching for USD
# dependency libraries
import platform, sys
if sys.version_info >= (3, 8) and platform.system() == "Windows":
import contextlib
@contextlib.contextmanager
def WindowsImportWrapper():
import os
dirs = []
import_paths = os.getenv('PXR_USD_WINDOWS_DLL_PATH')
if import_paths is None:
import_paths = os.getenv('PATH', '')
for path in import_paths.split(os.pathsep):
# Calling add_dll_directory raises an exception if paths don't
# exist, or if you pass in dot
if os.path.exists(path) and path != '.':
dirs.append(os.add_dll_directory(path))
# This block guarantees we clear the dll directories if an exception
# is raised in the with block.
try:
yield
finally:
for dll_dir in dirs:
dll_dir.close()
del os
del contextlib
else:
class WindowsImportWrapper(object):
def __enter__(self):
pass
def __exit__(self, exc_type, ex_val, exc_tb):
pass
del platform, sys
def PreparePythonModule(moduleName=None):
"""Prepare an extension module at import time. This will import the
Python module associated with the caller's module (e.g. '_tf' for 'pxr.Tf')
or the module with the specified moduleName and copy its contents into
the caller's local namespace.
Generally, this should only be called by the __init__.py script for a module
upon loading a boost python module (generally '_libName.so')."""
import importlib
import inspect
import os
frame = inspect.currentframe().f_back
try:
f_locals = frame.f_locals
# If an explicit moduleName is not supplied, construct it from the
# caller's module name, like "pxr.Tf", and our naming conventions,
# which results in "_tf".
if moduleName is None:
moduleName = f_locals["__name__"].split(".")[-1]
moduleName = "_" + moduleName[0].lower() + moduleName[1:]
with WindowsImportWrapper():
module = importlib.import_module(
"." + moduleName, f_locals["__name__"])
PrepareModule(module, f_locals)
try:
del f_locals[moduleName]
except KeyError:
pass
if not os.environ.get("PXR_DISABLE_EXTERNAL_PY_DOCSTRINGS"):
try:
module = importlib.import_module(".__DOC", f_locals["__name__"])
module.Execute(f_locals)
try:
del f_locals["__DOC"]
except KeyError:
pass
except Exception:
pass
finally:
del frame
def PrepareModule(module, result):
"""PrepareModule(module, result) -- Prepare an extension module at import
time. Generally, this should only be called by the __init__.py script for a
module upon loading a boost python module (generally '_libName.so')."""
# inject into result.
ignore = frozenset(['__name__', '__package__', '__builtins__',
'__doc__', '__file__', '__path__'])
newModuleName = result.get('__name__')
for key, value in module.__dict__.items():
if not key in ignore:
result[key] = value
# Lie about the module from which value came.
if newModuleName and hasattr(value, '__module__'):
try:
setattr(value, '__module__', newModuleName)
except AttributeError as e:
# The __module__ attribute of Boost.Python.function
# objects is not writable, so we get this exception
# a lot. Just ignore it. We're really only concerned
# about the data objects like enum values and such.
#
pass
def GetCodeLocation(framesUp):
"""Returns a tuple (moduleName, functionName, fileName, lineNo).
To trace the current location of python execution, use GetCodeLocation().
By default, the information is returned at the current stack-frame; thus::
info = GetCodeLocation()
will return information about the line that GetCodeLocation() was called
from. One can write: ::
def genericDebugFacility():
info = GetCodeLocation(1)
# print out data
def someCode():
...
if bad:
genericDebugFacility()
and genericDebugFacility() will get information associated with its caller,
i.e. the function someCode()."""
import sys
f_back = sys._getframe(framesUp).f_back
return (f_back.f_globals['__name__'], f_back.f_code.co_name,
f_back.f_code.co_filename, f_back.f_lineno)
PreparePythonModule()
# Need to provide an exception type that tf errors will show up as.
class ErrorException(RuntimeError):
def __init__(self, *args):
RuntimeError.__init__(self, *args)
self.__TfException = True
def __str__(self):
return '\n\t' + '\n\t'.join([str(e) for e in self.args])
__SetErrorExceptionClass(ErrorException)
def Warn(msg, template=""):
"""Issue a warning via the TfDiagnostic system.
At this time, template is ignored.
"""
codeInfo = GetCodeLocation(framesUp=1)
_Warn(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
def Status(msg, verbose=True):
"""Issues a status update to the Tf diagnostic system.
If verbose is True (the default) then information about where in the code
the status update was issued from is included.
"""
if verbose:
codeInfo = GetCodeLocation(framesUp=1)
_Status(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
else:
_Status(msg, "", "", "", 0)
def RaiseCodingError(msg):
"""Raise a coding error to the Tf Diagnostic system."""
codeInfo = GetCodeLocation(framesUp=1)
_RaiseCodingError(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
def RaiseRuntimeError(msg):
"""Raise a runtime error to the Tf Diagnostic system."""
codeInfo = GetCodeLocation(framesUp=1)
_RaiseRuntimeError(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
def Fatal(msg):
"""Raise a fatal error to the Tf Diagnostic system."""
codeInfo = GetCodeLocation(framesUp=1)
_Fatal(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
class NamedTemporaryFile(object):
"""A named temporary file which keeps the internal file handle closed.
A class which constructs a temporary file(that isn't open) on __enter__,
provides its name as an attribute, and deletes it on __exit__.
Note: The constructor args for this object match those of
python's tempfile.mkstemp() function, and will have the same effect on
the underlying file created."""
def __init__(self, suffix='', prefix='', dir=None, text=False):
# Note that we defer creation until the enter block to
# prevent users from unintentionally creating a bunch of
# temp files that don't get cleaned up.
self._args = (suffix, prefix, dir, text)
def __enter__(self):
from tempfile import mkstemp
from os import close
fd, path = mkstemp(*self._args)
close(fd)
# XXX: We currently only expose the name attribute
# more can be added based on client needs in the future.
self._name = path
return self
def __exit__(self, *args):
import os
os.remove(self.name)
@property
def name(self):
"""The path for the temporary file created."""
return self._name
| 9,036 | Python | 35.293173 | 80 | 0.625609 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Tf/__DOC.py | def Execute(result):
result["CallContext"].__doc__ = """"""
result["Debug"].__doc__ = """
Enum-based debugging messages.
The ``TfDebug`` class encapsulates a simple enum-based conditional
debugging message system. It is meant as a tool for developers, and
*NOT* as a means of issuing diagnostic messages to end-users. (This is
not strictly true. The TfDebug class is extremely useful and has many
properties that make its use attractive for issuing messages to end-
users. However, for this purpose, please use the ``TF_INFO`` macro
which more clearly indicates its intent.)
The features of ``TfDebug`` are:
- Debugging messages/calls for an entire enum group can be compiled
out-of-existence.
- The cost of checking if a specific message should be printed at
runtime (assuming the enum group of the message has not been compile-
time disabled) is a single inline array lookup, with a compile-time
index into a global array.
The use of the facility is simple:
.. code-block:: text
// header file
#include "pxr/base/tf/debug.h"
TF_DEBUG_CODES(MY_E1, MY_E2, MY_E3);
// source file
TF_DEBUG(MY_E2).Msg("something about e2\n");
TF_DEBUG(MY_E3).Msg("val = %d\n", value);
The code in the header file declares the debug symbols to use. Under
the hood, this creates an enum with the values given in the argument
to TF_DEBUG_CODES, along with a first and last sentinel values and
passes that to TF_DEBUG_RANGE.
If you need to obtain the enum type name, use
decltype(SOME_ENUM_VALUE).
In the source file, the indicated debugging messages are printed only
if the debugging symbols are enabled. Effectively, the construct
.. code-block:: text
TF_DEBUG(MY_E1).Msg(msgExpr)
is translated to
.. code-block:: text
if (symbol-MY_E1-is-enabled)
output(msgExpr)
The implications are that ``msgExpr`` is only evaluated if symbol
``MY_E1`` symbol is enabled.
To totally disable TF_DEBUG output for a set of codes at compile time,
declare the codes using
TF_CONDITIONALLY_COMPILE_TIME_ENABLED_DEBUG_CODES(condition,
\\.\\.\\.) where \\.\\.\\. is all the debug codes. If'condition'is
false at compile time then all TF_DEBUG() .Msg()s for these codes are
elminated at compile time, so they have zero cost.
Most commonly debug symbols are inactive by default, but can be turned
on either by an environment variable ``TF_DEBUG`` , or interactively
once a program has started.
.. code-block:: text
TfDebug::DisableAll<MyDebugCodes>(); // disable everything
TfDebug::Enable(MY_E1); // enable just MY_E1
Description strings may be associated with debug codes as follows:
.. code-block:: text
// source file xyz/debugCodes.cpp
#include "proj/my/debugCodes.h"
#include "pxr/base/tf/debug.h"
#include "pxr/base/tf/registryManager.h"
TF_REGISTRY_FUNCTION(TfDebug) {
TF_DEBUG_ENVIRONMENT_SYMBOL(MY_E1, "loading of blah-blah files");
TF_DEBUG_ENVIRONMENT_SYMBOL(MY_E2, "parsing of mdl code");
// etc.
}
"""
result["Debug"].SetDebugSymbolsByName.func_doc = """**classmethod** SetDebugSymbolsByName(pattern, value) -> list[str]
Set registered debug symbols matching ``pattern`` to ``value`` .
All registered debug symbols matching ``pattern`` are set to ``value``
. The only matching is an exact match with ``pattern`` , or if
``pattern`` ends with an'\\*'as is otherwise a prefix of a debug
symbols. The names of all debug symbols set by this call are returned
as a vector.
Parameters
----------
pattern : str
value : bool
"""
result["Debug"].IsDebugSymbolNameEnabled.func_doc = """**classmethod** IsDebugSymbolNameEnabled(name) -> bool
True if the specified debug symbol is set.
Parameters
----------
name : str
"""
result["Debug"].GetDebugSymbolDescriptions.func_doc = """**classmethod** GetDebugSymbolDescriptions() -> str
Get a description of all debug symbols and their purpose.
A single string describing all registered debug symbols along with
short descriptions is returned.
"""
result["Debug"].GetDebugSymbolNames.func_doc = """**classmethod** GetDebugSymbolNames() -> list[str]
Get a listing of all debug symbols.
"""
result["Debug"].GetDebugSymbolDescription.func_doc = """**classmethod** GetDebugSymbolDescription(name) -> str
Get a description for the specified debug symbol.
A short description of the debug symbol is returned. This is the same
description string that is embedded in the return value of
GetDebugSymbolDescriptions.
Parameters
----------
name : str
"""
result["Debug"].SetOutputFile.func_doc = """**classmethod** SetOutputFile(file) -> None
Direct debug output to *either* stdout or stderr.
Note that *file* MUST be either stdout or stderr. If not, issue an
error and do nothing. Debug output is issued to stdout by default. If
the environment variable TF_DEBUG_OUTPUT_FILE is set to'stderr', then
output is issued to stderr by default.
Parameters
----------
file : FILE
"""
result["Enum"].__doc__ = """
An enum class that records both enum type and enum value.
"""
result["Enum"].GetValueFromFullName.func_doc = """**classmethod** GetValueFromFullName(fullname, foundIt) -> Enum
Returns the enumerated value for a fully-qualified name.
This takes a fully-qualified enumerated value name (e.g.,
``"Season::WINTER"`` ) and returns the associated value. If there is
no such name, this returns -1. Since -1 can sometimes be a valid
value, the ``foundIt`` flag pointer, if not ``None`` , is set to
``true`` if the name was found and ``false`` otherwise. Also, since
this is not a templated function, it has to return a generic value
type, so we use ``TfEnum`` .
Parameters
----------
fullname : str
foundIt : bool
"""
result["Error"].__doc__ = """
Represents an object that contains error information.
See Guide To Diagnostic Facilities in the C++ API reference for a
detailed description of the error issuing API. For a example of how to
post an error, see ``TF_ERROR()`` , also in the C++ API reference.
In the Python API, you can raise several different types of errors,
including coding errors (Tf.RaiseCodingError), run time errors
(Tf.RaiseRuntimeError), fatal errors (Tf.Fatal).
"""
result["MallocTag"].__doc__ = """
Top-down memory tagging system.
See The TfMallocTag Memory Tagging System for a detailed description.
"""
result["MallocTag"].Initialize.func_doc = """**classmethod** Initialize(errMsg) -> bool
Initialize the memory tagging system.
This function returns ``true`` if the memory tagging system can be
successfully initialized or it has already been initialized.
Otherwise, ``\\*errMsg`` is set with an explanation for the failure.
Until the system is initialized, the various memory reporting calls
will indicate that no memory has been allocated. Note also that memory
allocated prior to calling ``Initialize()`` is not tracked i.e. all
data refers to allocations that happen subsequent to calling
``Initialize()`` .
Parameters
----------
errMsg : str
"""
result["MallocTag"].IsInitialized.func_doc = """**classmethod** IsInitialized() -> bool
Return true if the tagging system is active.
If ``Initialize()`` has been successfully called, this function
returns ``true`` .
"""
result["MallocTag"].GetTotalBytes.func_doc = """**classmethod** GetTotalBytes() -> int
Return total number of allocated bytes.
The current total memory that has been allocated and not freed is
returned. Memory allocated before calling ``Initialize()`` is not
accounted for.
"""
result["MallocTag"].GetMaxTotalBytes.func_doc = """**classmethod** GetMaxTotalBytes() -> int
Return the maximum total number of bytes that have ever been allocated
at one time.
This is simply the maximum value of GetTotalBytes() since Initialize()
was called.
"""
result["MallocTag"].GetCallTree.func_doc = """**classmethod** GetCallTree(tree, skipRepeated) -> bool
Return a snapshot of memory usage.
Returns a snapshot by writing into ``\\*tree`` . See the ``C`` \\*tree
structure for documentation. If ``Initialize()`` has not been called,
\ \\*tree is set to a rather blank structure (empty vectors, empty
strings, zero in all integral fields) and ``false`` is returned;
otherwise, ``\\*tree`` is set with the contents of the current memory
snapshot and ``true`` is returned. It is fine to call this function on
the same ``\\*tree`` instance; each call simply overwrites the data
from the last call. If /p skipRepeated is ``true`` , then any repeated
callsite is skipped. See the ``CallTree`` documentation for more
details.
Parameters
----------
tree : CallTree
skipRepeated : bool
"""
result["MallocTag"].SetDebugMatchList.func_doc = """**classmethod** SetDebugMatchList(matchList) -> None
Sets the tags to trap in the debugger.
When memory is allocated or freed for any tag that matches
``matchList`` the debugger trap is invoked. If a debugger is attached
the program will stop in the debugger, otherwise the program will
continue to run. See ``ArchDebuggerTrap()`` and ``ArchDebuggerWait()``
.
``matchList`` is a comma, tab or newline separated list of malloc tag
names. The names can have internal spaces but leading and trailing
spaces are stripped. If a name ends in'\\*'then the suffix is
wildcarded. A name can have a leading'-'or'+'to prevent or allow a
match. Each name is considered in order and later matches override
earlier matches. For example,'Csd\\*, -CsdScene::_Populate\\*,
+CsdScene::_PopulatePrimCacheLocal'matches any malloc tag starting
with'Csd'but nothing starting
with'CsdScene::_Populate'except'CsdScene::_PopulatePrimCacheLocal'.
Use the empty string to disable debugging traps.
Parameters
----------
matchList : str
"""
result["MallocTag"].SetCapturedMallocStacksMatchList.func_doc = """**classmethod** SetCapturedMallocStacksMatchList(matchList) -> None
Sets the tags to trace.
When memory is allocated for any tag that matches ``matchList`` a
stack trace is recorded. When that memory is released the stack trace
is discarded. Clients can call ``GetCapturedMallocStacks()`` to get a
list of all recorded stack traces. This is useful for finding leaks.
Traces recorded for any tag that will no longer be matched are
discarded by this call. Traces recorded for tags that continue to be
matched are retained.
``matchList`` is a comma, tab or newline separated list of malloc tag
names. The names can have internal spaces but leading and trailing
spaces are stripped. If a name ends in'\\*'then the suffix is
wildcarded. A name can have a leading'-'or'+'to prevent or allow a
match. Each name is considered in order and later matches override
earlier matches. For example,'Csd\\*, -CsdScene::_Populate\\*,
+CsdScene::_PopulatePrimCacheLocal'matches any malloc tag starting
with'Csd'but nothing starting
with'CsdScene::_Populate'except'CsdScene::_PopulatePrimCacheLocal'.
Use the empty string to disable stack capturing.
Parameters
----------
matchList : str
"""
result["Notice"].__doc__ = """
The base class for objects used to notify interested parties
(listeners) when events have occurred. The TfNotice class also serves
as a container for various dispatching routines such as Register() and
Send() .
See The TfNotice Notification System in the C++ API reference for a
detailed description of the notification system.
Python Example: Registering For and Sending
===========================================
Notices The following code provides examples of how to set up a Notice
listener connection (represented in Python by the Listener class),
including creating and sending notices, registering to receive
notices, and breaking a listener connection.
.. code-block:: text
# To create a new notice type:
class APythonClass(Tf.Notice):
'''TfNotice sent when APythonClass does something of interest.'''
pass
Tf.Type.Define(APythonClass)
# An interested listener can register to receive notices from all
# senders, or from a particular type of sender.
# To send a notice to all registered listeners:;
APythonClass().SendGlobally()
# To send a notice to listeners who register with a specific sender:
APythonClass().Send(self)
# To register for the notice from any sender:
my_listener = Tf.Notice.RegisterGlobally(APythonClass, self._HandleNotice)
# To register for the notice from a specific sender
my_listener = Tf.Notice.Register(APythonClass, self._HandleNotice, sender)
def _HandleNotice(self, notice, sender):
'''callback function for handling a notice'''
# do something when the notice arrives
# To revoke interest in a notice
my_listener.Revoke()
For more on using notices in Python, see the Editor With Notices
tutorial.
"""
result["PyModuleWasLoaded"].__doc__ = """
A *TfNotice* that is sent when a script module is loaded. Since many
modules may be loaded at once, listeners are encouraged to defer work
triggered by this notice to the end of an application iteration. This,
of course, is good practice in general.
"""
result["RefPtrTracker"].__doc__ = """
Provides tracking of ``TfRefPtr`` objects to particular objects.
Clients can enable, at compile time, tracking of ``TfRefPtr`` objects
that point to particular instances of classes derived from
``TfRefBase`` . This is useful if you have a ref counted object with a
ref count that should've gone to zero but didn't. This tracker can
tell you every ``TfRefPtr`` that's holding the ``TfRefBase`` and a
stack trace where it was created or last assigned to.
Clients can get a report of all watched instances and how many
``TfRefPtr`` objects are holding them using
``ReportAllWatchedCounts()`` (in python use ``Tf.RefPtrTracker()``
.GetAllWatchedCountsReport()). You can see all of the stack traces
using ``ReportAllTraces()`` (in python use ``Tf.RefPtrTracker()``
.GetAllTracesReport()).
Clients will typically enable tracking using code like this:
.. code-block:: text
#include "pxr/base/tf/refPtrTracker.h"
class MyRefBaseType;
typedef TfRefPtr<MyRefBaseType> MyRefBaseTypeRefPtr;
TF_DECLARE_REFPTR_TRACK(MyRefBaseType);
class MyRefBaseType {
\\.\\.\\.
public:
static bool _ShouldWatch(const MyRefBaseType\\*);
\\.\\.\\.
};
TF_DEFINE_REFPTR_TRACK(MyRefBaseType, MyRefBaseType::_ShouldWatch);
Note that the ``TF_DECLARE_REFPTR_TRACK()`` macro must be invoked
before any use of the ``MyRefBaseTypeRefPtr`` type.
The ``MyRefBaseType::_ShouldWatch()`` function returns ``true`` if the
given instance of ``MyRefBaseType`` should be tracked. You can also
use ``TfRefPtrTracker::WatchAll()`` to watch every instance (but that
might use a lot of memory and time).
If you have a base type, ``B`` , and a derived type, ``D`` , and you
hold instances of ``D`` in a ``TfRefPtr < ``B>```` (i.e. a pointer to
the base) then you must track both type ``B`` and type ``D`` . But you
can use ``TfRefPtrTracker::WatchNone()`` when tracking ``B`` if you're
not interested in instances of ``B`` .
"""
result["RefPtrTracker"].__init__.func_doc = """__init__()
"""
result["ScopeDescription"].__doc__ = """
This class is used to provide high-level descriptions about scopes of
execution that could possibly block, or to provide relevant
information about high-level action that would be useful in a crash
report.
This class is reasonably fast to use, especially if the message
strings are not dynamically created, however it should not be used in
very highly performance sensitive contexts. The cost to push & pop is
essentially a TLS lookup plus a couple of atomic operations.
"""
result["ScopeDescription"].__init__.func_doc = """__init__()
----------------------------------------------------------------------
__init__(arg1)
Parameters
----------
arg1 : ScopeDescription
----------------------------------------------------------------------
__init__(description, context)
Construct with a description.
Push *description* on the stack of descriptions for this thread.
Caller guarantees that the string ``description`` lives at least as
long as this TfScopeDescription object.
Parameters
----------
description : str
context : CallContext
----------------------------------------------------------------------
__init__(description, context)
Construct with a description.
Push *description* on the stack of descriptions for this thread. This
object adopts ownership of the rvalue ``description`` .
Parameters
----------
description : str
context : CallContext
----------------------------------------------------------------------
__init__(description, context)
Construct with a description.
Push *description* on the stack of descriptions for this thread.
Caller guarantees that the string ``description`` lives at least as
long as this TfScopeDescription object.
Parameters
----------
description : char
context : CallContext
"""
result["ScopeDescription"].SetDescription.func_doc = """SetDescription(description) -> None
Replace the description stack entry for this scope description.
Caller guarantees that the string ``description`` lives at least as
long as this TfScopeDescription object.
Parameters
----------
description : str
----------------------------------------------------------------------
SetDescription(description) -> None
Replace the description stack entry for this scope description.
This object adopts ownership of the rvalue ``description`` .
Parameters
----------
description : str
----------------------------------------------------------------------
SetDescription(description) -> None
Replace the description stack entry for this scope description.
Caller guarantees that the string ``description`` lives at least as
long as this TfScopeDescription object.
Parameters
----------
description : char
"""
result["ScriptModuleLoader"].__doc__ = """
Provides low-level facilities for shared modules with script
bindings to register themselves with their dependences, and provides a
mechanism whereby those script modules will be loaded when necessary.
Currently, this is when one of our script modules is loaded, when
TfPyInitialize is called, and when Plug opens shared modules.
Generally, user code will not make use of this.
"""
result["ScriptModuleLoader"].GetModuleNames.func_doc = """GetModuleNames() -> list[str]
Return a list of all currently known modules in a valid dependency
order.
"""
result["ScriptModuleLoader"].GetModulesDict.func_doc = """GetModulesDict() -> python.dict
Return a python dict containing all currently known modules under
their canonical names.
"""
result["ScriptModuleLoader"].WriteDotFile.func_doc = """WriteDotFile(file) -> None
Write a graphviz dot-file for the dependency graph of all.
currently known modules/modules to *file*.
Parameters
----------
file : str
"""
result["ScriptModuleLoader"].__init__.func_doc = """__init__()
"""
result["Singleton"].__doc__ = """
Manage a single instance of an object (see
Typical Use for a canonical example).
"""
result["Stopwatch"].__doc__ = """
Low-cost, high-resolution timer datatype.
A ``TfStopwatch`` can be used to perform very precise timings at
runtime, even in very tight loops. The cost of"starting"or"stopping"a
``TfStopwatch`` is very small: approximately 40 nanoseconds on a 900
Mhz Pentium III Linux box, 300 nanoseconds on a 400 Mhz Sun, and 200
nanoseconds on a 250 Mhz SGI.
Note that this class is not thread-safe: if you need to take timings
in a multi-threaded region of a process, let each thread have its own
``TfStopwatch`` and then combine results using the ``AddFrom()``
member function.
"""
result["Stopwatch"].Start.func_doc = """Start() -> None
Record the current time for use by the next ``Stop()`` call.
The ``Start()`` function records the current time. A subsequent call
to ``Start()`` before a call to ``Stop()`` simply records a later
current time, but does not change the accumulated time of the
``TfStopwatch`` .
"""
result["Stopwatch"].Stop.func_doc = """Stop() -> None
Increases the accumulated time stored in the ``TfStopwatch`` .
The ``Stop()`` function increases the accumulated time by the duration
between the current time and the last time recorded by a ``Start()``
call. A subsequent call to ``Stop()`` before another call to
``Start()`` will therefore double-count time and throw off the
results.
A ``TfStopwatch`` also counts the number of samples it has taken.
The"sample count"is simply the number of times that ``Stop()`` has
been called.
"""
result["Stopwatch"].Reset.func_doc = """Reset() -> None
Resets the accumulated time and the sample count to zero.
"""
result["Stopwatch"].AddFrom.func_doc = """AddFrom(t) -> None
Adds the accumulated time and sample count from ``t`` into the
``TfStopwatch`` .
If you have several timers taking measurements, and you wish to
combine them together, you can add one timer's results into another;
for example, ``t2.AddFrom(t1)`` will add ``t1`` 's time and sample
count into ``t2`` .
Parameters
----------
t : Stopwatch
"""
result["TemplateString"].__doc__ = """
TfTemplateString provides simple string substitutions based on named
placeholders. Instead of the''-based substitutions used by printf,
template strings use'$'-based substitutions, using the following
rules:
- "$$"is replaced with a single"$"
- "$identifier"names a substitution placeholder matching a mapping
key of"identifier". The first non-identifier character after
the"$"character terminates the placeholder specification.
- "${identifier}"is equivalent to"$identifier". It is required when
valid identifier characters follow the placeholder but are not part of
the placeholder, such as"${noun}ification".
- An identifier is a sequence of characters"[A-Z][a-z][0-9]_".
*TfTemplateString* is immutable: once one is created it may not be
modified. *TfTemplateString* is fast to copy, since it shares state
internally between copies. *TfTemplateString* is thread-safe. It may
be read freely by multiple threads concurrently.
"""
result["TemplateString"].__init__.func_doc = """__init__()
Constructs a new template string.
----------------------------------------------------------------------
__init__(template_)
Constructs a new template string.
Parameters
----------
template_ : str
"""
result["TemplateString"].Substitute.func_doc = """Substitute(arg1) -> str
Performs the template substitution, returning a new string.
The mapping contains keys which match the placeholders in the
template. If a placeholder is found for which no mapping is present, a
coding error is raised.
Parameters
----------
arg1 : Mapping
"""
result["TemplateString"].SafeSubstitute.func_doc = """SafeSubstitute(arg1) -> str
Like Substitute() , except that if placeholders are missing from the
mapping, instead of raising a coding error, the original placeholder
will appear in the resulting string intact.
Parameters
----------
arg1 : Mapping
"""
result["TemplateString"].GetEmptyMapping.func_doc = """GetEmptyMapping() -> Mapping
Returns an empty mapping for the current template.
This method first calls IsValid to ensure that the template is valid.
"""
result["TemplateString"].GetParseErrors.func_doc = """GetParseErrors() -> list[str]
Returns any error messages generated during template parsing.
"""
result["Type"].__doc__ = """
TfType represents a dynamic runtime type.
TfTypes are created and discovered at runtime, rather than compile
time.
Features:
- unique typename
- safe across DSO boundaries
- can represent C++ types, pure Python types, or Python subclasses
of wrapped C++ types
- lightweight value semantics you can copy and default construct
TfType, unlike ``std::type_info`` .
- totally ordered can use as a ``std::map`` key
"""
result["Type"].FindDerivedByName.func_doc = """**classmethod** FindDerivedByName(name) -> Type
Retrieve the ``TfType`` that derives from this type and has the given
alias or typename.
AddAlias
Parameters
----------
name : str
----------------------------------------------------------------------
FindDerivedByName(name) -> Type
Retrieve the ``TfType`` that derives from BASE and has the given alias
or typename.
This is a convenience method, and is equivalent to:
.. code-block:: text
TfType::Find<BASE>().FindDerivedByName(name)
Parameters
----------
name : str
"""
result["Type"].Find.func_doc = """**classmethod** Find() -> Type
Retrieve the ``TfType`` corresponding to type ``T`` .
The type ``T`` must have been declared or defined in the type system
or the ``TfType`` corresponding to an unknown type is returned.
IsUnknown()
----------------------------------------------------------------------
Find(obj) -> Type
Retrieve the ``TfType`` corresponding to ``obj`` .
The ``TfType`` corresponding to the actual object represented by
``obj`` is returned; this may not be the object returned by
``TfType::Find<T>()`` if ``T`` is a polymorphic type.
This works for Python subclasses of the C++ type ``T`` as well, as
long as ``T`` has been wrapped using TfPyPolymorphic.
Of course, the object's type must have been declared or defined in the
type system or the ``TfType`` corresponding to an unknown type is
returned.
IsUnknown()
Parameters
----------
obj : T
----------------------------------------------------------------------
Find(t) -> Type
Retrieve the ``TfType`` corresponding to an obj with the given
``type_info`` .
Parameters
----------
t : type_info
"""
result["Type"].FindByName.func_doc = """**classmethod** FindByName(name) -> Type
Retrieve the ``TfType`` corresponding to the given ``name`` .
Every type defined in the TfType system has a unique, implementation
independent name. In addition, aliases can be added to identify a type
underneath a specific base type; see TfType::AddAlias() . The given
name will first be tried as an alias under the root type, and
subsequently as a typename.
This method is equivalent to:
.. code-block:: text
TfType::GetRoot().FindDerivedByName(name)
For any object ``obj`` ,
.. code-block:: text
Find(obj) == FindByName( Find(obj).GetTypeName() )
Parameters
----------
name : str
"""
result["Type"].GetAliases.func_doc = """GetAliases(derivedType) -> list[str]
Returns a vector of the aliases registered for the derivedType under
this, the base type.
AddAlias()
Parameters
----------
derivedType : Type
"""
result["Type"].GetAllDerivedTypes.func_doc = """GetAllDerivedTypes(result) -> None
Return the set of all types derived (directly or indirectly) from this
type.
Parameters
----------
result : set[Type]
"""
result["Type"].GetAllAncestorTypes.func_doc = """GetAllAncestorTypes(result) -> None
Build a vector of all ancestor types inherited by this type.
The starting type is itself included, as the first element of the
results vector.
Types are given in"C3"resolution order, as used for new-style classes
starting in Python 2.3. This algorithm is more complicated than a
simple depth-first traversal of base classes, in order to prevent some
subtle errors with multiple-inheritance. See the references below for
more background.
This can be expensive; consider caching the results. TfType does not
cache this itself since it is not needed internally.
Guido van Rossum."Unifying types and classes in Python 2.2: Method
resolution order."
http://www.python.org/download/releases/2.2.2/descrintro/#mro
Barrett, Cassels, Haahr, Moon, Playford, Withington."A Monotonic
Superclass Linearization for Dylan."OOPSLA 96.
http://www.webcom.com/haahr/dylan/linearization-oopsla96.html
Parameters
----------
result : list[Type]
"""
result["Type"].IsA.func_doc = """IsA(queryType) -> bool
Return true if this type is the same as or derived from ``queryType``
.
If ``queryType`` is unknown, this always returns ``false`` .
Parameters
----------
queryType : Type
----------------------------------------------------------------------
IsA() -> bool
Return true if this type is the same as or derived from T.
This is equivalent to:
.. code-block:: text
IsA(Find<T>())
"""
result["Type"].GetRoot.func_doc = """**classmethod** GetRoot() -> Type
Return the root type of the type hierarchy.
All known types derive (directly or indirectly) from the root. If a
type is specified with no bases, it is implicitly considered to derive
from the root type.
"""
result["Type"].AddAlias.func_doc = """**classmethod** AddAlias(base, name) -> None
Add an alias name for this type under the given base type.
Aliases are similar to typedefs in C++: they provide an alternate name
for a type. The alias is defined with respect to the given ``base``
type. Aliases must be unique with respect to both other aliases
beneath that base type and names of derived types of that base.
Parameters
----------
base : Type
name : str
----------------------------------------------------------------------
AddAlias(name) -> None
Add an alias for DERIVED beneath BASE.
This is a convenience method, that declares both DERIVED and BASE as
TfTypes before adding the alias.
Parameters
----------
name : str
"""
result["Type"].Define.func_doc = """**classmethod** Define() -> Type
Define a TfType with the given C++ type T and C++ base types B.
Each of the base types will be declared (but not defined) as TfTypes
if they have not already been.
The typeName of the created TfType will be the canonical demangled
RTTI type name, as defined by GetCanonicalTypeName() .
It is an error to attempt to define a type that has already been
defined.
----------------------------------------------------------------------
Define() -> Type
Define a TfType with the given C++ type T and no bases.
See the other Define() template for more details.
C++ does not allow default template arguments for function templates,
so we provide this separate definition for the case of no bases.
"""
result["Type"].__init__.func_doc = """__init__()
Construct an TfType representing an unknown type.
To actually register a new type with the TfType system, see
TfType::Declare() .
Note that this always holds true:
.. code-block:: text
TfType().IsUnknown() == true
----------------------------------------------------------------------
__init__(info)
Parameters
----------
info : _TypeInfo
"""
result["Warning"].__doc__ = """
Represents an object that contains information about a warning.
See Guide To Diagnostic Facilities in the C++ API reference for a
detailed description of the warning issuing API. For a example of how
to post a warning, see ``TF_WARN()`` , also in the C++ API reference.
In the Python API, you can issue a warning with Tf.Warn().
"""
result["Notice"].__doc__ = """"""
result["ReportActiveErrorMarks"].func_doc = """ReportActiveErrorMarks() -> None
Report current TfErrorMark instances and the stack traces that created
them to stdout for debugging purposes.
To call this function, set _enableTfErrorMarkStackTraces in
errorMark.cpp and enable the TF_ERROR_MARK_TRACKING TfDebug code.
"""
result["Error"].__doc__ = """"""
result["Warning"].__doc__ = """"""
result["InstallTerminateAndCrashHandlers"].func_doc = """InstallTerminateAndCrashHandlers() -> None
(Re)install Tf's crash handler.
This should not generally need to be called since Tf does this itself
when loaded. However, when run in 3rd party environments that install
their own signal handlers, possibly overriding Tf's, this provides a
way to reinstall them, in hopes that they'll stick.
This calls std::set_terminate() and installs signal handlers for
SIGSEGV, SIGBUS, SIGFPE, and SIGABRT.
"""
result["MallocTag"].__doc__ = """"""
result["Singleton"].__doc__ = """"""
result["Enum"].__doc__ = """"""
result["Debug"].__doc__ = """"""
result["TemplateString"].__doc__ = """"""
result["StringToDouble"].func_doc = """StringToDouble(txt) -> float
Converts text string to double.
This method converts strings to floating point numbers. It is similar
to libc's atof(), but performs the conversion much more quickly.
It expects somewhat valid input: it will continue parsing the input
until it hits an unrecognized character, as described by the regexp
below, and at that point will return the results up to that point.
(-?[0-9]+(.[0-9]\\*)?|-?.[0-9]+)([eE][-+]?[0-9]+)?
It will not check to see if there is any input at all, or whitespace
after the digits. Ie: TfStringToDouble("") == 0.0
TfStringToDouble("blah") == 0.0 TfStringToDouble("-") == -0.0
TfStringToDouble("1.2foo") == 1.2
``TfStringToDouble`` is a wrapper around the extern-c TfStringToDouble
Parameters
----------
txt : str
----------------------------------------------------------------------
StringToDouble(text) -> float
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
text : str
----------------------------------------------------------------------
StringToDouble(text, len) -> float
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
text : str
len : int
"""
result["StringToLong"].func_doc = """StringToLong(txt, outOfRange) -> long
Convert a sequence of digits in ``txt`` to a long int value.
Caller is responsible for ensuring that ``txt`` has content matching:
.. code-block:: text
-?[0-9]+
If the digit sequence's value is out of range, set ``\\*outOfRange``
to true (if ``outOfRange`` is not None) and return either
std::numeric_limits<long>::min() or max(), whichever is closest to the
true value.
Parameters
----------
txt : str
outOfRange : bool
----------------------------------------------------------------------
StringToLong(txt, outOfRange) -> long
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
txt : str
outOfRange : bool
"""
result["StringToULong"].func_doc = """StringToULong(txt, outOfRange) -> int
Convert a sequence of digits in ``txt`` to an unsigned long value.
Caller is responsible for ensuring that ``txt`` has content matching:
.. code-block:: text
[0-9]+
If the digit sequence's value is out of range, set ``\\*outOfRange``
to true (if ``outOfRange`` is not None) and return
std::numeric_limits<unsignedlong>::max().
Parameters
----------
txt : str
outOfRange : bool
----------------------------------------------------------------------
StringToULong(txt, outOfRange) -> int
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
txt : str
outOfRange : bool
"""
result["StringSplit"].func_doc = """StringSplit(src, separator) -> list[str]
Breaks the given string apart, returning a vector of strings.
The string ``source`` is broken apart into individual words, where a
word is delimited by the string ``separator`` . This function behaves
like pythons string split method.
Parameters
----------
src : str
separator : str
"""
result["IsValidIdentifier"].func_doc = """IsValidIdentifier(identifier) -> bool
Test whether *identifier* is valid.
An identifier is valid if it follows the C/Python identifier
convention; that is, it must be at least one character long, must
start with a letter or underscore, and must contain only letters,
underscores, and numerals.
Parameters
----------
identifier : str
"""
result["MakeValidIdentifier"].func_doc = """MakeValidIdentifier(in) -> str
Produce a valid identifier (see TfIsValidIdentifier) from ``in`` by
replacing invalid characters with'_'.
If ``in`` is empty, return"_".
Parameters
----------
in : str
"""
result["Stopwatch"].__doc__ = """"""
result["CallContext"].file = property(result["CallContext"].file.fget, result["CallContext"].file.fset, result["CallContext"].file.fdel, """type : char
""")
result["CallContext"].function = property(result["CallContext"].function.fget, result["CallContext"].function.fset, result["CallContext"].function.fdel, """type : char
""")
result["CallContext"].line = property(result["CallContext"].line.fget, result["CallContext"].line.fset, result["CallContext"].line.fdel, """type : int
""")
result["CallContext"].prettyFunction = property(result["CallContext"].prettyFunction.fget, result["CallContext"].prettyFunction.fset, result["CallContext"].prettyFunction.fdel, """type : char
""")
result["PyModuleWasLoaded"].name.func_doc = """name() -> str
Return the name of the module that was loaded.
"""
result["Stopwatch"].nanoseconds = property(result["Stopwatch"].nanoseconds.fget, result["Stopwatch"].nanoseconds.fset, result["Stopwatch"].nanoseconds.fdel, """type : int
Return the accumulated time in nanoseconds.
Note that this number can easily overflow a 32-bit counter, so take
care to save the result in an ``int64_t`` , and not a regular ``int``
or ``long`` .
""")
result["Stopwatch"].microseconds = property(result["Stopwatch"].microseconds.fget, result["Stopwatch"].microseconds.fset, result["Stopwatch"].microseconds.fdel, """type : int
Return the accumulated time in microseconds.
Note that 45 minutes will overflow a 32-bit counter, so take care to
save the result in an ``int64_t`` , and not a regular ``int`` or
``long`` .
""")
result["Stopwatch"].milliseconds = property(result["Stopwatch"].milliseconds.fget, result["Stopwatch"].milliseconds.fset, result["Stopwatch"].milliseconds.fdel, """type : int
Return the accumulated time in milliseconds.
""")
result["Stopwatch"].sampleCount = property(result["Stopwatch"].sampleCount.fget, result["Stopwatch"].sampleCount.fset, result["Stopwatch"].sampleCount.fdel, """type : int
Return the current sample count.
The sample count, which is simply the number of calls to ``Stop()``
since creation or a call to ``Reset()`` , is useful for computing
average running times of a repeated task.
""")
result["Stopwatch"].seconds = property(result["Stopwatch"].seconds.fget, result["Stopwatch"].seconds.fset, result["Stopwatch"].seconds.fdel, """type : float
Return the accumulated time in seconds as a ``double`` .
""")
result["TemplateString"].template = property(result["TemplateString"].template.fget, result["TemplateString"].template.fset, result["TemplateString"].template.fdel, """type : str
Returns the template source string supplied to the constructor.
""")
result["TemplateString"].valid = property(result["TemplateString"].valid.fget, result["TemplateString"].valid.fset, result["TemplateString"].valid.fdel, """type : bool
Returns true if the current template is well formed.
Empty templates are valid.
""")
result["Type"].typeName = property(result["Type"].typeName.fget, result["Type"].typeName.fset, result["Type"].typeName.fdel, """type : str
Return the machine-independent name for this type.
This name is specified when the TfType is declared.
Declare()
""")
result["Type"].pythonClass = property(result["Type"].pythonClass.fget, result["Type"].pythonClass.fset, result["Type"].pythonClass.fdel, """type : TfPyObjWrapper
Return the Python class object for this type.
If this type is unknown or has not yet had a Python class defined,
this will return ``None`` , as an empty ``TfPyObjWrapper``
DefinePythonClass()
""")
result["Type"].baseTypes = property(result["Type"].baseTypes.fget, result["Type"].baseTypes.fset, result["Type"].baseTypes.fdel, """type : list[Type]
Return a vector of types from which this type was derived.
""")
result["Type"].isUnknown = property(result["Type"].isUnknown.fget, result["Type"].isUnknown.fset, result["Type"].isUnknown.fdel, """type : bool
Return true if this is the unknown type, representing a type unknown
to the TfType system.
The unknown type does not derive from the root type, or any other
type.
""")
result["Type"].isEnumType = property(result["Type"].isEnumType.fget, result["Type"].isEnumType.fset, result["Type"].isEnumType.fdel, """type : bool
Return true if this is an enum type.
""")
result["Type"].isPlainOldDataType = property(result["Type"].isPlainOldDataType.fget, result["Type"].isPlainOldDataType.fset, result["Type"].isPlainOldDataType.fdel, """type : bool
Return true if this is a plain old data type, as defined by C++.
""")
result["Type"].sizeof = property(result["Type"].sizeof.fget, result["Type"].sizeof.fset, result["Type"].sizeof.fdel, """type : int
Return the size required to hold an instance of this type on the stack
(does not include any heap allocated memory the instance uses).
This is what the C++ sizeof operator returns for the type, so this
value is not very useful for Python types (it will always be
sizeof(boost::python::object)).
""") | 41,089 | Python | 24.474272 | 194 | 0.696731 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Ndr/__DOC.py | def Execute(result):
result["DiscoveryPlugin"].__doc__ = """
Interface for discovery plugins.
Discovery plugins, like the name implies, find nodes. Where the plugin
searches is up to the plugin that implements this interface. Examples
of discovery plugins could include plugins that look for nodes on the
filesystem, another that finds nodes in a cloud service, and another
that searches a local database. Multiple discovery plugins that search
the filesystem in specific locations/ways could also be created. All
discovery plugins are executed as soon as the registry is
instantiated.
These plugins simply report back to the registry what nodes they found
in a generic way. The registry doesn't know much about the innards of
the nodes yet, just that the nodes exist. Understanding the nodes is
the responsibility of another set of plugins defined by the
``NdrParserPlugin`` interface.
Discovery plugins report back to the registry via
``NdrNodeDiscoveryResult`` s. These are small, lightweight classes
that contain the information for a single node that was found during
discovery. The discovery result only includes node information that
can be gleaned pre-parse, so the data is fairly limited; to see
exactly what's included, and what is expected to be populated, see the
documentation for ``NdrNodeDiscoveryResult`` .
How to Create a Discovery Plugin
================================
There are three steps to creating a discovery plugin:
- Implement the discovery plugin interface, ``NdrDiscoveryPlugin``
- Register your new plugin with the registry. The registration
macro must be called in your plugin's implementation file:
.. code-block:: text
NDR_REGISTER_DISCOVERY_PLUGIN(YOUR_DISCOVERY_PLUGIN_CLASS_NAME)
This macro is available in discoveryPlugin.h.
- In the same folder as your plugin, create a ``plugInfo.json``
file. This file must be formatted like so, substituting
``YOUR_LIBRARY_NAME`` , ``YOUR_CLASS_NAME`` , and
``YOUR_DISPLAY_NAME`` :
.. code-block:: text
{
"Plugins": [{
"Type": "module",
"Name": "YOUR_LIBRARY_NAME",
"Root": "@PLUG_INFO_ROOT@",
"LibraryPath": "@PLUG_INFO_LIBRARY_PATH@",
"ResourcePath": "@PLUG_INFO_RESOURCE_PATH@",
"Info": {
"Types": {
"YOUR_CLASS_NAME" : {
"bases": ["NdrDiscoveryPlugin"],
"displayName": "YOUR_DISPLAY_NAME"
}
}
}
}]
}
The NDR ships with one discovery plugin, the
``_NdrFilesystemDiscoveryPlugin`` . Take a look at NDR's plugInfo.json
file for example values for ``YOUR_LIBRARY_NAME`` ,
``YOUR_CLASS_NAME`` , and ``YOUR_DISPLAY_NAME`` . If multiple
discovery plugins exist in the same folder, you can continue adding
additional plugins under the ``Types`` key in the JSON. More detailed
information about the plugInfo.json format can be found in the
documentation for the ``plug`` module (in pxr/base).
"""
result["DiscoveryPlugin"].DiscoverNodes.func_doc = """DiscoverNodes(arg1) -> NdrNodeDiscoveryResultVec
Finds and returns all nodes that the implementing plugin should be
aware of.
Parameters
----------
arg1 : Context
"""
result["DiscoveryPlugin"].GetSearchURIs.func_doc = """GetSearchURIs() -> NdrStringVec
Gets the URIs that this plugin is searching for nodes in.
"""
result["DiscoveryPluginContext"].__doc__ = """
A context for discovery.
Discovery plugins can use this to get a limited set of non-local
information without direct coupling between plugins.
"""
result["DiscoveryPluginContext"].GetSourceType.func_doc = """GetSourceType(discoveryType) -> str
Returns the source type associated with the discovery type.
This may return an empty token if there is no such association.
Parameters
----------
discoveryType : str
"""
result["DiscoveryUri"].__doc__ = """
Struct for holding a URI and its resolved URI for a file discovered by
NdrFsHelpersDiscoverFiles.
"""
result["Node"].__doc__ = """
Represents an abstract node. Describes information like the name of
the node, what its inputs and outputs are, and any associated
metadata.
In almost all cases, this class will not be used directly. More
specialized nodes can be created that derive from ``NdrNode`` ; those
specialized nodes can add their own domain-specific data and methods.
"""
result["Node"].GetIdentifier.func_doc = """GetIdentifier() -> NdrIdentifier
Return the identifier of the node.
"""
result["Node"].GetVersion.func_doc = """GetVersion() -> Version
Return the version of the node.
"""
result["Node"].GetName.func_doc = """GetName() -> str
Gets the name of the node.
"""
result["Node"].GetFamily.func_doc = """GetFamily() -> str
Gets the name of the family that the node belongs to.
An empty token will be returned if the node does not belong to a
family.
"""
result["Node"].GetContext.func_doc = """GetContext() -> str
Gets the context of the node.
The context is the context that the node declares itself as having
(or, if a particular node does not declare a context, it will be
assigned a default context by the parser).
As a concrete example from the ``Sdr`` module, a shader with a
specific source type may perform different duties vs. another shader
with the same source type. For example, one shader with a source type
of ``SdrArgsParser::SourceType`` may declare itself as having a
context of'pattern', while another shader of the same source type may
say it is used for lighting, and thus has a context of'light'.
"""
result["Node"].GetSourceType.func_doc = """GetSourceType() -> str
Gets the type of source that this node originated from.
Note that this is distinct from ``GetContext()`` , which is the type
that the node declares itself as having.
As a concrete example from the ``Sdr`` module, several shader parsers
exist and operate on different types of shaders. In this scenario,
each distinct type of shader (OSL, Args, etc) is considered a
different *source*, even though they are all shaders. In addition, the
shaders under each source type may declare themselves as having a
specific context (shaders can serve different roles). See
``GetContext()`` for more information on this.
"""
result["Node"].GetResolvedDefinitionURI.func_doc = """GetResolvedDefinitionURI() -> str
Gets the URI to the resource that provided this node's definition.
Could be a path to a file, or some other resource identifier. This URI
should be fully resolved.
NdrNode::GetResolvedImplementationURI()
"""
result["Node"].GetResolvedImplementationURI.func_doc = """GetResolvedImplementationURI() -> str
Gets the URI to the resource that provides this node's implementation.
Could be a path to a file, or some other resource identifier. This URI
should be fully resolved.
NdrNode::GetResolvedDefinitionURI()
"""
result["Node"].GetSourceCode.func_doc = """GetSourceCode() -> str
Returns the source code for this node.
This will be empty for most nodes. It will be non-empty only for the
nodes that are constructed using NdrRegistry::GetNodeFromSourceCode()
, in which case, the source code has not been parsed (or even
compiled) yet.
An unparsed node with non-empty source-code but no properties is
considered to be invalid. Once the node is parsed and the relevant
properties and metadata are extracted from the source code, the node
becomes valid.
NdrNode::IsValid
"""
result["Node"].IsValid.func_doc = """IsValid() -> bool
Whether or not this node is valid.
A node that is valid indicates that the parser plugin was able to
successfully parse the contents of this node.
Note that if a node is not valid, some data like its name, URI, source
code etc. could still be available (data that was obtained during the
discovery process). However, other data that must be gathered from the
parsing process will NOT be available (eg, inputs and outputs).
"""
result["Node"].GetInfoString.func_doc = """GetInfoString() -> str
Gets a string with basic information about this node.
Helpful for things like adding this node to a log.
"""
result["Node"].GetInputNames.func_doc = """GetInputNames() -> NdrTokenVec
Get an ordered list of all the input names on this node.
"""
result["Node"].GetOutputNames.func_doc = """GetOutputNames() -> NdrTokenVec
Get an ordered list of all the output names on this node.
"""
result["Node"].GetInput.func_doc = """GetInput(inputName) -> Property
Get an input property by name.
``nullptr`` is returned if an input with the given name does not
exist.
Parameters
----------
inputName : str
"""
result["Node"].GetOutput.func_doc = """GetOutput(outputName) -> Property
Get an output property by name.
``nullptr`` is returned if an output with the given name does not
exist.
Parameters
----------
outputName : str
"""
result["Node"].GetMetadata.func_doc = """GetMetadata() -> NdrTokenMap
All metadata that came from the parse process.
Specialized nodes may isolate values in the metadata (with possible
manipulations and/or additional parsing) and expose those values in
their API.
"""
result["NodeDiscoveryResult"].__doc__ = """
Represents the raw data of a node, and some other bits of metadata,
that were determined via a ``NdrDiscoveryPlugin`` .
"""
result["NodeDiscoveryResult"].__init__.func_doc = """__init__(identifier, version, name, family, discoveryType, sourceType, uri, resolvedUri, sourceCode, metadata, blindData, subIdentifier)
Constructor.
Parameters
----------
identifier : NdrIdentifier
version : Version
name : str
family : str
discoveryType : str
sourceType : str
uri : str
resolvedUri : str
sourceCode : str
metadata : NdrTokenMap
blindData : str
subIdentifier : str
"""
result["Property"].__doc__ = """
Represents a property (input or output) that is part of a ``NdrNode``
instance.
A property must have a name and type, but may also specify a host of
additional metadata. Instances can also be queried to determine if
another ``NdrProperty`` instance can be connected to it.
In almost all cases, this class will not be used directly. More
specialized properties can be created that derive from ``NdrProperty``
; those specialized properties can add their own domain-specific data
and methods.
"""
result["Property"].GetName.func_doc = """GetName() -> str
Gets the name of the property.
"""
result["Property"].GetType.func_doc = """GetType() -> str
Gets the type of the property.
"""
result["Property"].GetDefaultValue.func_doc = """GetDefaultValue() -> VtValue
Gets this property's default value associated with the type of the
property.
GetType()
"""
result["Property"].IsOutput.func_doc = """IsOutput() -> bool
Whether this property is an output.
"""
result["Property"].IsArray.func_doc = """IsArray() -> bool
Whether this property's type is an array type.
"""
result["Property"].IsDynamicArray.func_doc = """IsDynamicArray() -> bool
Whether this property's array type is dynamically-sized.
"""
result["Property"].GetArraySize.func_doc = """GetArraySize() -> int
Gets this property's array size.
If this property is a fixed-size array type, the array size is
returned. In the case of a dynamically-sized array, this method
returns the array size that the parser reports, and should not be
relied upon to be accurate. A parser may report -1 for the array size,
for example, to indicate a dynamically-sized array. For types that are
not a fixed-size array or dynamic array, this returns 0.
"""
result["Property"].GetInfoString.func_doc = """GetInfoString() -> str
Gets a string with basic information about this property.
Helpful for things like adding this property to a log.
"""
result["Property"].GetMetadata.func_doc = """GetMetadata() -> NdrTokenMap
All of the metadata that came from the parse process.
"""
result["Property"].IsConnectable.func_doc = """IsConnectable() -> bool
Whether this property can be connected to other properties.
"""
result["Property"].CanConnectTo.func_doc = """CanConnectTo(other) -> bool
Determines if this property can be connected to the specified
property.
Parameters
----------
other : Property
"""
result["Property"].GetTypeAsSdfType.func_doc = """GetTypeAsSdfType() -> NdrSdfTypeIndicator
Converts the property's type from ``GetType()`` into a
``SdfValueTypeName`` .
Two scenarios can result: an exact mapping from property type to Sdf
type, and an inexact mapping. In the first scenario, the first element
in the pair will be the cleanly-mapped Sdf type, and the second
element, a TfToken, will be empty. In the second scenario, the Sdf
type will be set to ``Token`` to indicate an unclean mapping, and the
second element will be set to the original type returned by
``GetType()`` .
This base property class is generic and cannot know ahead of time how
to perform this mapping reliably, thus it will always fall into the
second scenario. It is up to specialized properties to perform the
mapping.
GetDefaultValueAsSdfType()
"""
result["Registry"].__doc__ = """
The registry provides access to node information."Discovery
Plugins"are responsible for finding the nodes that should be included
in the registry.
Discovery plugins are found through the plugin system. If additional
discovery plugins need to be specified, a client can pass them to
``SetExtraDiscoveryPlugins()`` .
When the registry is first told about the discovery plugins, the
plugins will be asked to discover nodes. These plugins will generate
``NdrNodeDiscoveryResult`` instances, which only contain basic
metadata. Once the client asks for information that would require the
node's contents to be parsed (eg, what its inputs and outputs are),
the registry will begin the parsing process on an as-needed basis. See
``NdrNodeDiscoveryResult`` for the information that can be retrieved
without triggering a parse.
Some methods in this module may allow for a"family"to be provided. A
family is simply a generic grouping which is optional.
"""
result["Registry"].SetExtraDiscoveryPlugins.func_doc = """SetExtraDiscoveryPlugins(plugins) -> None
Allows the client to set any additional discovery plugins that would
otherwise NOT be found through the plugin system.
Runs the discovery process for the specified plugins immediately.
Note that this method cannot be called after any nodes in the registry
have been parsed (eg, through GetNode\\*()), otherwise an error will
result.
Parameters
----------
plugins : DiscoveryPluginRefPtrVec
----------------------------------------------------------------------
SetExtraDiscoveryPlugins(pluginTypes) -> None
Allows the client to set any additional discovery plugins that would
otherwise NOT be found through the plugin system.
Runs the discovery process for the specified plugins immediately.
Note that this method cannot be called after any nodes in the registry
have been parsed (eg, through GetNode\\*()), otherwise an error will
result.
Parameters
----------
pluginTypes : list[Type]
"""
result["Registry"].SetExtraParserPlugins.func_doc = """SetExtraParserPlugins(pluginTypes) -> None
Allows the client to set any additional parser plugins that would
otherwise NOT be found through the plugin system.
Note that this method cannot be called after any nodes in the registry
have been parsed (eg, through GetNode\\*()), otherwise an error will
result.
Parameters
----------
pluginTypes : list[Type]
"""
result["Registry"].GetNodeFromAsset.func_doc = """GetNodeFromAsset(asset, metadata, subIdentifier, sourceType) -> Node
Parses the given ``asset`` , constructs a NdrNode from it and adds it
to the registry.
Nodes created from an asset using this API can be looked up by the
unique identifier and sourceType of the returned node, or by URI,
which will be set to the unresolved asset path value.
``metadata`` contains additional metadata needed for parsing and
compiling the source code in the file pointed to by ``asset``
correctly. This metadata supplements the metadata available in the
asset and overrides it in cases where there are key collisions.
``subidentifier`` is optional, and it would be used to indicate a
particular definition in the asset file if the asset contains multiple
node definitions.
``sourceType`` is optional, and it is only needed to indicate a
particular type if the asset file is capable of representing a node
definition of multiple source types.
Returns a valid node if the asset is parsed successfully using one of
the registered parser plugins.
Parameters
----------
asset : AssetPath
metadata : NdrTokenMap
subIdentifier : str
sourceType : str
"""
result["Registry"].GetNodeFromSourceCode.func_doc = """GetNodeFromSourceCode(sourceCode, sourceType, metadata) -> Node
Parses the given ``sourceCode`` string, constructs a NdrNode from it
and adds it to the registry.
The parser to be used is determined by the specified ``sourceType`` .
Nodes created from source code using this API can be looked up by the
unique identifier and sourceType of the returned node.
``metadata`` contains additional metadata needed for parsing and
compiling the source code correctly. This metadata supplements the
metadata available in ``sourceCode`` and overrides it cases where
there are key collisions.
Returns a valid node if the given source code is parsed successfully
using the parser plugins that is registered for the specified
``sourceType`` .
Parameters
----------
sourceCode : str
sourceType : str
metadata : NdrTokenMap
"""
result["Registry"].GetSearchURIs.func_doc = """GetSearchURIs() -> NdrStringVec
Get the locations where the registry is searching for nodes.
Depending on which discovery plugins were used, this may include non-
filesystem paths.
"""
result["Registry"].GetNodeIdentifiers.func_doc = """GetNodeIdentifiers(family, filter) -> NdrIdentifierVec
Get the identifiers of all the nodes that the registry is aware of.
This will not run the parsing plugins on the nodes that have been
discovered, so this method is relatively quick. Optionally,
a"family"name can be specified to only get the identifiers of nodes
that belong to that family and a filter can be specified to get just
the default version (the default) or all versions of the node.
Parameters
----------
family : str
filter : VersionFilter
"""
result["Registry"].GetNodeNames.func_doc = """GetNodeNames(family) -> NdrStringVec
Get the names of all the nodes that the registry is aware of.
This will not run the parsing plugins on the nodes that have been
discovered, so this method is relatively quick. Optionally,
a"family"name can be specified to only get the names of nodes that
belong to that family.
Parameters
----------
family : str
"""
result["Registry"].GetNodeByIdentifier.func_doc = """GetNodeByIdentifier(identifier, sourceTypePriority) -> Node
Get the node with the specified ``identifier`` , and an optional
``sourceTypePriority`` list specifying the set of node SOURCE types
(see ``NdrNode::GetSourceType()`` ) that should be searched.
If no sourceTypePriority is specified, the first encountered node with
the specified identifier will be returned (first is arbitrary) if
found.
If a sourceTypePriority list is specified, then this will iterate
through each source type and try to find a node matching by
identifier. This is equivalent to calling
NdrRegistry::GetNodeByIdentifierAndType for each source type until a
node is found.
Nodes of the same identifier but different source type can exist in
the registry. If a node'Foo'with source types'abc'and'xyz'exist in the
registry, and you want to make sure the'abc'version is fetched before
the'xyz'version, the priority list would be specified as
['abc','xyz']. If the'abc'version did not exist in the registry, then
the'xyz'version would be returned.
Returns ``nullptr`` if a node matching the arguments can't be found.
Parameters
----------
identifier : NdrIdentifier
sourceTypePriority : NdrTokenVec
"""
result["Registry"].GetNodeByIdentifierAndType.func_doc = """GetNodeByIdentifierAndType(identifier, sourceType) -> Node
Get the node with the specified ``identifier`` and ``sourceType`` .
If there is no matching node for the sourceType, nullptr is returned.
Parameters
----------
identifier : NdrIdentifier
sourceType : str
"""
result["Registry"].GetNodeByName.func_doc = """GetNodeByName(name, sourceTypePriority, filter) -> Node
Get the node with the specified name.
An optional priority list specifies the set of node SOURCE types (
NdrNode::GetSourceType() ) that should be searched and in what order.
Optionally, a filter can be specified to consider just the default
versions of nodes matching ``name`` (the default) or all versions of
the nodes.
GetNodeByIdentifier() .
Parameters
----------
name : str
sourceTypePriority : NdrTokenVec
filter : VersionFilter
"""
result["Registry"].GetNodeByNameAndType.func_doc = """GetNodeByNameAndType(name, sourceType, filter) -> Node
A convenience wrapper around ``GetNodeByName()`` .
Instead of providing a priority list, an exact type is specified, and
``nullptr`` is returned if a node with the exact identifier and type
does not exist.
Optionally, a filter can be specified to consider just the default
versions of nodes matching ``name`` (the default) or all versions of
the nodes.
Parameters
----------
name : str
sourceType : str
filter : VersionFilter
"""
result["Registry"].GetNodesByIdentifier.func_doc = """GetNodesByIdentifier(identifier) -> NdrNodeConstPtrVec
Get all nodes matching the specified identifier (multiple nodes of the
same identifier, but different source types, may exist).
If no nodes match the identifier, an empty vector is returned.
Parameters
----------
identifier : NdrIdentifier
"""
result["Registry"].GetNodesByName.func_doc = """GetNodesByName(name, filter) -> NdrNodeConstPtrVec
Get all nodes matching the specified name.
Only nodes matching the specified name will be parsed. Optionally, a
filter can be specified to get just the default version (the default)
or all versions of the node. If no nodes match an empty vector is
returned.
Parameters
----------
name : str
filter : VersionFilter
"""
result["Registry"].GetNodesByFamily.func_doc = """GetNodesByFamily(family, filter) -> NdrNodeConstPtrVec
Get all nodes from the registry, optionally restricted to the nodes
that fall under a specified family and/or the default version.
Note that this will parse *all* nodes that the registry is aware of
(unless a family is specified), so this may take some time to run the
first time it is called.
Parameters
----------
family : str
filter : VersionFilter
"""
result["Registry"].GetAllNodeSourceTypes.func_doc = """GetAllNodeSourceTypes() -> NdrTokenVec
Get a sorted list of all node source types that may be present on the
nodes in the registry.
Source types originate from the discovery process, but there is no
guarantee that the discovered source types will also have a registered
parser plugin. The actual supported source types here depend on the
parsers that are available. Also note that some parser plugins may not
advertise a source type.
See the documentation for ``NdrParserPlugin`` and
``NdrNode::GetSourceType()`` for more information.
"""
result["Version"].__doc__ = """"""
result["Version"].__init__.func_doc = """__init__()
Create an invalid version.
----------------------------------------------------------------------
__init__(major, minor)
Create a version with the given major and minor numbers.
Numbers must be non-negative, and at least one must be non-zero. On
failure generates an error and yields an invalid version.
Parameters
----------
major : int
minor : int
----------------------------------------------------------------------
__init__(x)
Create a version from a string.
On failure generates an error and yields an invalid version.
Parameters
----------
x : str
----------------------------------------------------------------------
__init__(x, arg2)
Parameters
----------
x : Version
arg2 : bool
"""
result["Version"].GetAsDefault.func_doc = """GetAsDefault() -> Version
Return an equal version marked as default.
It's permitted to mark an invalid version as the default.
"""
result["Version"].GetMajor.func_doc = """GetMajor() -> int
Return the major version number or zero for an invalid version.
"""
result["Version"].GetMinor.func_doc = """GetMinor() -> int
Return the minor version number or zero for an invalid version.
"""
result["Version"].IsDefault.func_doc = """IsDefault() -> bool
Return true iff this version is marked as default.
"""
result["Version"].GetStringSuffix.func_doc = """GetStringSuffix() -> str
Return the version as a identifier suffix.
""" | 24,958 | Python | 23.350244 | 192 | 0.728504 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdRender/__DOC.py | def Execute(result):
result["DenoisePass"].__doc__ = """
A RenderDenoisePass generates renders via a denoising process. This
may be the same renderer that a pipeline uses for UsdRender, or may be
a separate one. Notably, a RenderDenoisePass requires another Pass to
be present for it to operate. The denoising process itself is not
generative, and requires images inputs to operate.
As denoising integration varies so widely across pipelines, all
implementation details are left to pipeline-specific prims that
inherit from RenderDenoisePass.
"""
result["DenoisePass"].__init__.func_doc = """__init__(prim)
Construct a UsdRenderDenoisePass on UsdPrim ``prim`` .
Equivalent to UsdRenderDenoisePass::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRenderDenoisePass on the prim held by ``schemaObj`` .
Should be preferred over UsdRenderDenoisePass (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["DenoisePass"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["DenoisePass"].Get.func_doc = """**classmethod** Get(stage, path) -> DenoisePass
Return a UsdRenderDenoisePass holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRenderDenoisePass(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["DenoisePass"].Define.func_doc = """**classmethod** Define(stage, path) -> DenoisePass
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["DenoisePass"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Pass"].__doc__ = """
A RenderPass prim encapsulates the necessary information to generate
multipass renders. It houses properties for generating dependencies
and the necessary commands to run to generate renders, as well as
visibility controls for the scene. While RenderSettings describes the
information needed to generate images from a single invocation of a
renderer, RenderPass describes the additional information needed to
generate a time varying set of images.
There are two consumers of RenderPass prims - a runtime executable
that generates images from usdRender prims, and pipeline specific code
that translates between usdRender prims and the pipeline's resource
scheduling software. We'll refer to the latter as'job submission
code'.
The name of the prim is used as the pass's name.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdRenderTokens. So to set an attribute to the value"rightHanded",
use UsdRenderTokens->rightHanded as the value.
"""
result["Pass"].__init__.func_doc = """__init__(prim)
Construct a UsdRenderPass on UsdPrim ``prim`` .
Equivalent to UsdRenderPass::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRenderPass on the prim held by ``schemaObj`` .
Should be preferred over UsdRenderPass (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Pass"].GetPassTypeAttr.func_doc = """GetPassTypeAttr() -> Attribute
A string used to categorize differently structured or executed types
of passes within a customized pipeline.
For example, when multiple DCC's (e.g. Houdini, Katana, Nuke) each
compute and contribute different Products to a final result, it may be
clearest and most flexible to create a separate RenderPass for each.
Declaration
``uniform token passType``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["Pass"].CreatePassTypeAttr.func_doc = """CreatePassTypeAttr(defaultValue, writeSparsely) -> Attribute
See GetPassTypeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Pass"].GetCommandAttr.func_doc = """GetCommandAttr() -> Attribute
The command to run in order to generate renders for this pass.
The job submission code can use this to properly send tasks to the job
scheduling software that will generate products.
The command can contain variables that will be substituted
appropriately during submission, as seen in the example below with
{fileName}.
For example: command[0] ="prman"command[1] ="-progress"command[2]
="-pixelvariance"command[3] ="-0.15"command[4] ="{fileName}"# the
fileName property will be substituted
Declaration
``uniform string[] command``
C++ Type
VtArray<std::string>
Usd Type
SdfValueTypeNames->StringArray
Variability
SdfVariabilityUniform
"""
result["Pass"].CreateCommandAttr.func_doc = """CreateCommandAttr(defaultValue, writeSparsely) -> Attribute
See GetCommandAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Pass"].GetFileNameAttr.func_doc = """GetFileNameAttr() -> Attribute
The asset that contains the rendering prims or other information
needed to render this pass.
Declaration
``uniform asset fileName``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
Variability
SdfVariabilityUniform
"""
result["Pass"].CreateFileNameAttr.func_doc = """CreateFileNameAttr(defaultValue, writeSparsely) -> Attribute
See GetFileNameAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Pass"].GetDenoiseEnableAttr.func_doc = """GetDenoiseEnableAttr() -> Attribute
When True, this Pass pass should be denoised.
Declaration
``uniform bool denoise:enable = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
Variability
SdfVariabilityUniform
"""
result["Pass"].CreateDenoiseEnableAttr.func_doc = """CreateDenoiseEnableAttr(defaultValue, writeSparsely) -> Attribute
See GetDenoiseEnableAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Pass"].GetRenderSourceRel.func_doc = """GetRenderSourceRel() -> Relationship
The source prim to render from.
If *fileName* is not present, the source is assumed to be a
RenderSettings prim present in the current Usd stage. If fileName is
present, the source should be found in the file there. This
relationship might target a string attribute on this or another prim
that identifies the appropriate object in the external container.
For example, for a Usd-backed pass, this would point to a
RenderSettings prim. Houdini passes would point to a Rop. Nuke passes
would point to a write node.
"""
result["Pass"].CreateRenderSourceRel.func_doc = """CreateRenderSourceRel() -> Relationship
See GetRenderSourceRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["Pass"].GetInputPassesRel.func_doc = """GetInputPassesRel() -> Relationship
The set of other Passes that this Pass depends on in order to be
constructed properly.
For example, a Pass A may generate a texture, which is then used as an
input to Pass B.
By default, usdRender makes some assumptions about the relationship
between this prim and the prims listed in inputPasses. Namely, when
per-frame tasks are generated from these pass prims, usdRender will
assume a one-to-one relationship between tasks that share their frame
number. Consider a pass named'composite'whose *inputPasses* targets a
Pass prim named'beauty`. By default, each frame for'composite'will
depend on the same frame from'beauty': beauty.1 ->composite.1 beauty.2
\\->composite.2 etc
The consumer of this RenderPass graph of inputs will need to resolve
the transitive dependencies.
"""
result["Pass"].CreateInputPassesRel.func_doc = """CreateInputPassesRel() -> Relationship
See GetInputPassesRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["Pass"].GetDenoisePassRel.func_doc = """GetDenoisePassRel() -> Relationship
The The UsdRenderDenoisePass prim from which to source denoise
settings.
"""
result["Pass"].CreateDenoisePassRel.func_doc = """CreateDenoisePassRel() -> Relationship
See GetDenoisePassRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["Pass"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Pass"].Get.func_doc = """**classmethod** Get(stage, path) -> Pass
Return a UsdRenderPass holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRenderPass(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Pass"].Define.func_doc = """**classmethod** Define(stage, path) -> Pass
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Pass"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Product"].__doc__ = """
A UsdRenderProduct describes an image or other file-like artifact
produced by a render. A RenderProduct combines one or more RenderVars
into a file or interactive buffer. It also provides all the controls
established in UsdRenderSettingsBase as optional overrides to whatever
the owning UsdRenderSettings prim dictates.
Specific renderers may support additional settings, such as a way to
configure compression settings, filetype metadata, and so forth. Such
settings can be encoded using renderer-specific API schemas applied to
the product prim.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdRenderTokens. So to set an attribute to the value"rightHanded",
use UsdRenderTokens->rightHanded as the value.
"""
result["Product"].__init__.func_doc = """__init__(prim)
Construct a UsdRenderProduct on UsdPrim ``prim`` .
Equivalent to UsdRenderProduct::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRenderProduct on the prim held by ``schemaObj`` .
Should be preferred over UsdRenderProduct (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Product"].GetProductTypeAttr.func_doc = """GetProductTypeAttr() -> Attribute
The type of output to produce.
The default,"raster", indicates a 2D image.
In the future, UsdRender may define additional product types.
Declaration
``uniform token productType ="raster"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["Product"].CreateProductTypeAttr.func_doc = """CreateProductTypeAttr(defaultValue, writeSparsely) -> Attribute
See GetProductTypeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Product"].GetProductNameAttr.func_doc = """GetProductNameAttr() -> Attribute
Specifies the name that the output/display driver should give the
product.
This is provided as-authored to the driver, whose responsibility it is
to situate the product on a filesystem or other storage, in the
desired location.
Declaration
``token productName =""``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["Product"].CreateProductNameAttr.func_doc = """CreateProductNameAttr(defaultValue, writeSparsely) -> Attribute
See GetProductNameAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Product"].GetOrderedVarsRel.func_doc = """GetOrderedVarsRel() -> Relationship
Specifies the RenderVars that should be consumed and combined into the
final product.
If ordering is relevant to the output driver, then the ordering of
targets in this relationship provides the order to use.
"""
result["Product"].CreateOrderedVarsRel.func_doc = """CreateOrderedVarsRel() -> Relationship
See GetOrderedVarsRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["Product"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Product"].Get.func_doc = """**classmethod** Get(stage, path) -> Product
Return a UsdRenderProduct holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRenderProduct(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Product"].Define.func_doc = """**classmethod** Define(stage, path) -> Product
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Product"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Settings"].__doc__ = """
A UsdRenderSettings prim specifies global settings for a render
process, including an enumeration of the RenderProducts that should
result, and the UsdGeomImageable purposes that should be rendered. How
settings affect rendering
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdRenderTokens. So to set an attribute to the value"rightHanded",
use UsdRenderTokens->rightHanded as the value.
"""
result["Settings"].__init__.func_doc = """__init__(prim)
Construct a UsdRenderSettings on UsdPrim ``prim`` .
Equivalent to UsdRenderSettings::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRenderSettings on the prim held by ``schemaObj`` .
Should be preferred over UsdRenderSettings (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Settings"].GetIncludedPurposesAttr.func_doc = """GetIncludedPurposesAttr() -> Attribute
The list of UsdGeomImageable *purpose* values that should be included
in the render.
Note this cannot be specified per-RenderProduct because it is a
statement of which geometry is present.
Declaration
``uniform token[] includedPurposes = ["default","render"]``
C++ Type
VtArray<TfToken>
Usd Type
SdfValueTypeNames->TokenArray
Variability
SdfVariabilityUniform
"""
result["Settings"].CreateIncludedPurposesAttr.func_doc = """CreateIncludedPurposesAttr(defaultValue, writeSparsely) -> Attribute
See GetIncludedPurposesAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Settings"].GetMaterialBindingPurposesAttr.func_doc = """GetMaterialBindingPurposesAttr() -> Attribute
Ordered list of material purposes to consider when resolving material
bindings in the scene.
The empty string indicates the"allPurpose"binding.
Declaration
``uniform token[] materialBindingPurposes = ["full",""]``
C++ Type
VtArray<TfToken>
Usd Type
SdfValueTypeNames->TokenArray
Variability
SdfVariabilityUniform
Allowed Values
full, preview,""
"""
result["Settings"].CreateMaterialBindingPurposesAttr.func_doc = """CreateMaterialBindingPurposesAttr(defaultValue, writeSparsely) -> Attribute
See GetMaterialBindingPurposesAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Settings"].GetRenderingColorSpaceAttr.func_doc = """GetRenderingColorSpaceAttr() -> Attribute
Describes a renderer's working (linear) colorSpace where all the
renderer/shader math is expected to happen.
When no renderingColorSpace is provided, renderer should use its own
default.
Declaration
``uniform token renderingColorSpace``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["Settings"].CreateRenderingColorSpaceAttr.func_doc = """CreateRenderingColorSpaceAttr(defaultValue, writeSparsely) -> Attribute
See GetRenderingColorSpaceAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Settings"].GetProductsRel.func_doc = """GetProductsRel() -> Relationship
The set of RenderProducts the render should produce.
This relationship should target UsdRenderProduct prims. If no
*products* are specified, an application should produce an rgb image
according to the RenderSettings configuration, to a default display or
image name.
"""
result["Settings"].CreateProductsRel.func_doc = """CreateProductsRel() -> Relationship
See GetProductsRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["Settings"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Settings"].Get.func_doc = """**classmethod** Get(stage, path) -> Settings
Return a UsdRenderSettings holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRenderSettings(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Settings"].Define.func_doc = """**classmethod** Define(stage, path) -> Settings
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Settings"].GetStageRenderSettings.func_doc = """**classmethod** GetStageRenderSettings(stage) -> Settings
Fetch and return ``stage`` 's render settings, as indicated by root
layer metadata.
If unauthored, or the metadata does not refer to a valid
UsdRenderSettings prim, this will return an invalid UsdRenderSettings
prim.
Parameters
----------
stage : UsdStageWeak
"""
result["Settings"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["SettingsBase"].__doc__ = """
Abstract base class that defines render settings that can be specified
on either a RenderSettings prim or a RenderProduct prim.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdRenderTokens. So to set an attribute to the value"rightHanded",
use UsdRenderTokens->rightHanded as the value.
"""
result["SettingsBase"].__init__.func_doc = """__init__(prim)
Construct a UsdRenderSettingsBase on UsdPrim ``prim`` .
Equivalent to UsdRenderSettingsBase::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRenderSettingsBase on the prim held by ``schemaObj`` .
Should be preferred over UsdRenderSettingsBase (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["SettingsBase"].GetResolutionAttr.func_doc = """GetResolutionAttr() -> Attribute
The image pixel resolution, corresponding to the camera's screen
window.
Declaration
``uniform int2 resolution = (2048, 1080)``
C++ Type
GfVec2i
Usd Type
SdfValueTypeNames->Int2
Variability
SdfVariabilityUniform
"""
result["SettingsBase"].CreateResolutionAttr.func_doc = """CreateResolutionAttr(defaultValue, writeSparsely) -> Attribute
See GetResolutionAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SettingsBase"].GetPixelAspectRatioAttr.func_doc = """GetPixelAspectRatioAttr() -> Attribute
The aspect ratio (width/height) of image pixels.
The default ratio 1.0 indicates square pixels.
Declaration
``uniform float pixelAspectRatio = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
Variability
SdfVariabilityUniform
"""
result["SettingsBase"].CreatePixelAspectRatioAttr.func_doc = """CreatePixelAspectRatioAttr(defaultValue, writeSparsely) -> Attribute
See GetPixelAspectRatioAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SettingsBase"].GetAspectRatioConformPolicyAttr.func_doc = """GetAspectRatioConformPolicyAttr() -> Attribute
Indicates the policy to use to resolve an aspect ratio mismatch
between the camera aperture and image settings.
This policy allows a standard render setting to do something
reasonable given varying camera inputs.
The camera aperture aspect ratio is determined by the aperture
atributes on the UsdGeomCamera.
The image aspect ratio is determined by the resolution and
pixelAspectRatio attributes in the render settings.
- "expandAperture": if necessary, expand the aperture to fit the
image, exposing additional scene content
- "cropAperture": if necessary, crop the aperture to fit the image,
cropping scene content
- "adjustApertureWidth": if necessary, adjust aperture width to
make its aspect ratio match the image
- "adjustApertureHeight": if necessary, adjust aperture height to
make its aspect ratio match the image
- "adjustPixelAspectRatio": compute pixelAspectRatio to make the
image exactly cover the aperture; disregards existing attribute value
of pixelAspectRatio
Declaration
``uniform token aspectRatioConformPolicy ="expandAperture"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
expandAperture, cropAperture, adjustApertureWidth,
adjustApertureHeight, adjustPixelAspectRatio
"""
result["SettingsBase"].CreateAspectRatioConformPolicyAttr.func_doc = """CreateAspectRatioConformPolicyAttr(defaultValue, writeSparsely) -> Attribute
See GetAspectRatioConformPolicyAttr() , and also Create vs Get
Property Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SettingsBase"].GetDataWindowNDCAttr.func_doc = """GetDataWindowNDCAttr() -> Attribute
dataWindowNDC specifies the axis-aligned rectangular region in the
adjusted aperture window within which the renderer should produce
data.
It is specified as (xmin, ymin, xmax, ymax) in normalized device
coordinates, where the range 0 to 1 corresponds to the aperture. (0,0)
corresponds to the bottom-left corner and (1,1) corresponds to the
upper-right corner.
Specifying a window outside the unit square will produce overscan
data. Specifying a window that does not cover the unit square will
produce a cropped render.
A pixel is included in the rendered result if the pixel center is
contained by the data window. This is consistent with standard rules
used by polygon rasterization engines. UsdRenderRasterization
The data window is expressed in NDC so that cropping and overscan may
be resolution independent. In interactive workflows, incremental
cropping and resolution adjustment may be intermixed to isolate and
examine parts of the scene. In compositing workflows, overscan may be
used to support image post-processing kernels, and reduced-resolution
proxy renders may be used for faster iteration.
The dataWindow:ndc coordinate system references the aperture after any
adjustments required by aspectRatioConformPolicy.
Declaration
``uniform float4 dataWindowNDC = (0, 0, 1, 1)``
C++ Type
GfVec4f
Usd Type
SdfValueTypeNames->Float4
Variability
SdfVariabilityUniform
"""
result["SettingsBase"].CreateDataWindowNDCAttr.func_doc = """CreateDataWindowNDCAttr(defaultValue, writeSparsely) -> Attribute
See GetDataWindowNDCAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SettingsBase"].GetInstantaneousShutterAttr.func_doc = """GetInstantaneousShutterAttr() -> Attribute
Deprecated - use disableMotionBlur instead.
Override the targeted *camera* 's *shutterClose* to be equal to the
value of its *shutterOpen*, to produce a zero-width shutter interval.
This gives us a convenient way to disable motion blur.
Declaration
``uniform bool instantaneousShutter = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
Variability
SdfVariabilityUniform
"""
result["SettingsBase"].CreateInstantaneousShutterAttr.func_doc = """CreateInstantaneousShutterAttr(defaultValue, writeSparsely) -> Attribute
See GetInstantaneousShutterAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SettingsBase"].GetDisableMotionBlurAttr.func_doc = """GetDisableMotionBlurAttr() -> Attribute
Disable all motion blur by setting the shutter interval of the
targeted camera to [0,0] - that is, take only one sample, namely at
the current time code.
Declaration
``uniform bool disableMotionBlur = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
Variability
SdfVariabilityUniform
"""
result["SettingsBase"].CreateDisableMotionBlurAttr.func_doc = """CreateDisableMotionBlurAttr(defaultValue, writeSparsely) -> Attribute
See GetDisableMotionBlurAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SettingsBase"].GetCameraRel.func_doc = """GetCameraRel() -> Relationship
The *camera* relationship specifies the primary camera to use in a
render.
It must target a UsdGeomCamera.
"""
result["SettingsBase"].CreateCameraRel.func_doc = """CreateCameraRel() -> Relationship
See GetCameraRel() , and also Create vs Get Property Methods for when
to use Get vs Create.
"""
result["SettingsBase"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["SettingsBase"].Get.func_doc = """**classmethod** Get(stage, path) -> SettingsBase
Return a UsdRenderSettingsBase holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRenderSettingsBase(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["SettingsBase"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Var"].__doc__ = """
A UsdRenderVar describes a custom data variable for a render to
produce. The prim describes the source of the data, which can be a
shader output or an LPE (Light Path Expression), and also allows
encoding of (generally renderer-specific) parameters that configure
the renderer for computing the variable.
The name of the RenderVar prim drives the name of the data variable
that the renderer will produce.
In the future, UsdRender may standardize RenderVar representation for
well-known variables under the sourceType ``intrinsic`` , such as *r*,
*g*, *b*, *a*, *z*, or *id*. For any described attribute *Fallback*
*Value* or *Allowed* *Values* below that are text/tokens, the actual
token is published and defined in UsdRenderTokens. So to set an
attribute to the value"rightHanded", use UsdRenderTokens->rightHanded
as the value.
"""
result["Var"].__init__.func_doc = """__init__(prim)
Construct a UsdRenderVar on UsdPrim ``prim`` .
Equivalent to UsdRenderVar::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRenderVar on the prim held by ``schemaObj`` .
Should be preferred over UsdRenderVar (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Var"].GetDataTypeAttr.func_doc = """GetDataTypeAttr() -> Attribute
The type of this channel, as a USD attribute type.
Declaration
``uniform token dataType ="color3f"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["Var"].CreateDataTypeAttr.func_doc = """CreateDataTypeAttr(defaultValue, writeSparsely) -> Attribute
See GetDataTypeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Var"].GetSourceNameAttr.func_doc = """GetSourceNameAttr() -> Attribute
The renderer should look for an output of this name as the computed
value for the RenderVar.
Declaration
``uniform string sourceName =""``
C++ Type
std::string
Usd Type
SdfValueTypeNames->String
Variability
SdfVariabilityUniform
"""
result["Var"].CreateSourceNameAttr.func_doc = """CreateSourceNameAttr(defaultValue, writeSparsely) -> Attribute
See GetSourceNameAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Var"].GetSourceTypeAttr.func_doc = """GetSourceTypeAttr() -> Attribute
Indicates the type of the source.
- "raw": The name should be passed directly to the renderer. This
is the default behavior.
- "primvar": This source represents the name of a primvar. Some
renderers may use this to ensure that the primvar is provided; other
renderers may require that a suitable material network be provided, in
which case this is simply an advisory setting.
- "lpe": Specifies a Light Path Expression in the OSL Light Path
Expressions language as the source for this RenderVar. Some renderers
may use extensions to that syntax, which will necessarily be non-
portable.
- "intrinsic": This setting is currently unimplemented, but
represents a future namespace for UsdRender to provide portable
baseline RenderVars, such as camera depth, that may have varying
implementations for each renderer.
Declaration
``uniform token sourceType ="raw"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
raw, primvar, lpe, intrinsic
"""
result["Var"].CreateSourceTypeAttr.func_doc = """CreateSourceTypeAttr(defaultValue, writeSparsely) -> Attribute
See GetSourceTypeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Var"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Var"].Get.func_doc = """**classmethod** Get(stage, path) -> Var
Return a UsdRenderVar holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRenderVar(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Var"].Define.func_doc = """**classmethod** Define(stage, path) -> Var
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Var"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
""" | 43,289 | Python | 22.174518 | 151 | 0.737878 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdRi/__DOC.py | def Execute(result):
result["MaterialAPI"].__doc__ = """
Deprecated
Materials should use UsdShadeMaterial instead. This schema will be
removed in a future release.
This API provides outputs that connect a material prim to prman
shaders and RIS objects.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdRiTokens. So to set an attribute to the value"rightHanded", use
UsdRiTokens->rightHanded as the value.
"""
result["MaterialAPI"].GetSurfaceOutput.func_doc = """GetSurfaceOutput() -> Output
Returns the"surface"output associated with the material.
"""
result["MaterialAPI"].GetDisplacementOutput.func_doc = """GetDisplacementOutput() -> Output
Returns the"displacement"output associated with the material.
"""
result["MaterialAPI"].GetVolumeOutput.func_doc = """GetVolumeOutput() -> Output
Returns the"volume"output associated with the material.
"""
result["MaterialAPI"].SetSurfaceSource.func_doc = """SetSurfaceSource(surfacePath) -> bool
Parameters
----------
surfacePath : Path
"""
result["MaterialAPI"].SetDisplacementSource.func_doc = """SetDisplacementSource(displacementPath) -> bool
Parameters
----------
displacementPath : Path
"""
result["MaterialAPI"].SetVolumeSource.func_doc = """SetVolumeSource(volumePath) -> bool
Parameters
----------
volumePath : Path
"""
result["MaterialAPI"].GetSurface.func_doc = """GetSurface(ignoreBaseMaterial) -> Shader
Returns a valid shader object if the"surface"output on the material is
connected to one.
If ``ignoreBaseMaterial`` is true and if the"surface"shader source is
specified in the base-material of this material, then this returns an
invalid shader object.
Parameters
----------
ignoreBaseMaterial : bool
"""
result["MaterialAPI"].GetDisplacement.func_doc = """GetDisplacement(ignoreBaseMaterial) -> Shader
Returns a valid shader object if the"displacement"output on the
material is connected to one.
If ``ignoreBaseMaterial`` is true and if the"displacement"shader
source is specified in the base-material of this material, then this
returns an invalid shader object.
Parameters
----------
ignoreBaseMaterial : bool
"""
result["MaterialAPI"].GetVolume.func_doc = """GetVolume(ignoreBaseMaterial) -> Shader
Returns a valid shader object if the"volume"output on the material is
connected to one.
If ``ignoreBaseMaterial`` is true and if the"volume"shader source is
specified in the base-material of this material, then this returns an
invalid shader object.
Parameters
----------
ignoreBaseMaterial : bool
"""
result["MaterialAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdRiMaterialAPI on UsdPrim ``prim`` .
Equivalent to UsdRiMaterialAPI::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRiMaterialAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdRiMaterialAPI (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
----------------------------------------------------------------------
__init__(material)
A constructor for creating a MaterialAPI object from a material prim.
Parameters
----------
material : Material
"""
result["MaterialAPI"].GetSurfaceAttr.func_doc = """GetSurfaceAttr() -> Attribute
Declaration
``token outputs:ri:surface``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["MaterialAPI"].CreateSurfaceAttr.func_doc = """CreateSurfaceAttr(defaultValue, writeSparsely) -> Attribute
See GetSurfaceAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MaterialAPI"].GetDisplacementAttr.func_doc = """GetDisplacementAttr() -> Attribute
Declaration
``token outputs:ri:displacement``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["MaterialAPI"].CreateDisplacementAttr.func_doc = """CreateDisplacementAttr(defaultValue, writeSparsely) -> Attribute
See GetDisplacementAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MaterialAPI"].GetVolumeAttr.func_doc = """GetVolumeAttr() -> Attribute
Declaration
``token outputs:ri:volume``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["MaterialAPI"].CreateVolumeAttr.func_doc = """CreateVolumeAttr(defaultValue, writeSparsely) -> Attribute
See GetVolumeAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MaterialAPI"].ComputeInterfaceInputConsumersMap.func_doc = """ComputeInterfaceInputConsumersMap(computeTransitiveConsumers) -> NodeGraph.InterfaceInputConsumersMap
Walks the namespace subtree below the material and computes a map
containing the list of all inputs on the material and the associated
vector of consumers of their values.
The consumers can be inputs on shaders within the material or on node-
graphs under it.
Parameters
----------
computeTransitiveConsumers : bool
"""
result["MaterialAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["MaterialAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> MaterialAPI
Return a UsdRiMaterialAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRiMaterialAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["MaterialAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["MaterialAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> MaterialAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"RiMaterialAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdRiMaterialAPI object is returned upon success. An invalid
(or empty) UsdRiMaterialAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["MaterialAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["SplineAPI"].__doc__ = """
Deprecated
This API schema will be removed in a future release.
RiSplineAPI is a general purpose API schema used to describe a named
spline stored as a set of attributes on a prim.
It is an add-on schema that can be applied many times to a prim with
different spline names. All the attributes authored by the schema are
namespaced under"$NAME:spline:", with the name of the spline providing
a namespace for the attributes.
The spline describes a 2D piecewise cubic curve with a position and
value for each knot. This is chosen to give straightforward artistic
control over the shape. The supported basis types are:
- linear (UsdRiTokens->linear)
- bspline (UsdRiTokens->bspline)
- Catmull-Rom (UsdRiTokens->catmullRom)
"""
result["SplineAPI"].Validate.func_doc = """Validate(reason) -> bool
Validates the attribute values belonging to the spline.
Returns true if the spline has all valid attribute values. Returns
false and populates the ``reason`` output argument if the spline has
invalid attribute values.
Here's the list of validations performed by this method:
- the SplineAPI must be fully initialized
- interpolation attribute must exist and use an allowed value
- the positions array must be a float array
- the positions array must be sorted by increasing value
- the values array must use the correct value type
- the positions and values array must have the same size
Parameters
----------
reason : str
"""
result["SplineAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdRiSplineAPI on UsdPrim ``prim`` .
Equivalent to UsdRiSplineAPI::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRiSplineAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdRiSplineAPI (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
----------------------------------------------------------------------
__init__(prim, splineName, valuesTypeName, doesDuplicateBSplineEndpoints)
Construct a UsdRiSplineAPI with the given ``splineName`` on the
UsdPrim ``prim`` .
Parameters
----------
prim : Prim
splineName : str
valuesTypeName : ValueTypeName
doesDuplicateBSplineEndpoints : bool
----------------------------------------------------------------------
__init__(schemaObj, splineName, valuesTypeName, doesDuplicateBSplineEndpoints)
Construct a UsdRiSplineAPI with the given ``splineName`` on the prim
held by ``schemaObj`` .
Parameters
----------
schemaObj : SchemaBase
splineName : str
valuesTypeName : ValueTypeName
doesDuplicateBSplineEndpoints : bool
"""
result["SplineAPI"].GetValuesTypeName.func_doc = """GetValuesTypeName() -> ValueTypeName
Returns the intended typename of the values attribute of the spline.
"""
result["SplineAPI"].GetInterpolationAttr.func_doc = """GetInterpolationAttr() -> Attribute
Interpolation method for the spline.
C++ Type: TfToken Usd Type: SdfValueTypeNames->Token Variability:
SdfVariabilityUniform Fallback Value: linear Allowed Values :
[linear, constant, bspline, catmullRom]
"""
result["SplineAPI"].CreateInterpolationAttr.func_doc = """CreateInterpolationAttr(defaultValue, writeSparsely) -> Attribute
See GetInterpolationAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SplineAPI"].GetPositionsAttr.func_doc = """GetPositionsAttr() -> Attribute
Positions of the knots.
C++ Type: VtArray<float> Usd Type: SdfValueTypeNames->FloatArray
Variability: SdfVariabilityUniform Fallback Value: No Fallback
"""
result["SplineAPI"].CreatePositionsAttr.func_doc = """CreatePositionsAttr(defaultValue, writeSparsely) -> Attribute
See GetPositionsAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SplineAPI"].GetValuesAttr.func_doc = """GetValuesAttr() -> Attribute
Values of the knots.
C++ Type: See GetValuesTypeName() Usd Type: See GetValuesTypeName()
Variability: SdfVariabilityUniform Fallback Value: No Fallback
"""
result["SplineAPI"].CreateValuesAttr.func_doc = """CreateValuesAttr(defaultValue, writeSparsely) -> Attribute
See GetValuesAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SplineAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["SplineAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> SplineAPI
Return a UsdRiSplineAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRiSplineAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["SplineAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["SplineAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> SplineAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"RiSplineAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdRiSplineAPI object is returned upon success. An invalid (or
empty) UsdRiSplineAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["SplineAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["StatementsAPI"].__doc__ = """
Container namespace schema for all renderman statements.
The longer term goal is for clients to go directly to primvar or
render-attribute API's, instead of using UsdRi StatementsAPI for
inherited attributes. Anticpating this, StatementsAPI can smooth the
way via a few environment variables:
- USDRI_STATEMENTS_READ_OLD_ENCODING: Causes StatementsAPI to read
old-style attributes instead of primvars in the"ri:"namespace.
"""
result["StatementsAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdRiStatementsAPI on UsdPrim ``prim`` .
Equivalent to UsdRiStatementsAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRiStatementsAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdRiStatementsAPI (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["StatementsAPI"].CreateRiAttribute.func_doc = """CreateRiAttribute(name, riType, nameSpace) -> Attribute
Create a rib attribute on the prim to which this schema is attached.
A rib attribute consists of an attribute *"nameSpace"* and an
attribute *"name"*. For example, the namespace"cull"may define
attributes"backfacing"and"hidden", and user-defined attributes belong
to the namespace"user".
This method makes no attempt to validate that the given ``nameSpace``
and *name* are actually meaningful to prman or any other renderer.
riType
should be a known RenderMan type definition, which can be array-
valued. For instance, both"color"and"float[3]"are valid values for
``riType`` .
Parameters
----------
name : str
riType : str
nameSpace : str
----------------------------------------------------------------------
CreateRiAttribute(name, tfType, nameSpace) -> Attribute
Creates an attribute of the given ``tfType`` .
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
name : str
tfType : Type
nameSpace : str
"""
result["StatementsAPI"].GetRiAttribute.func_doc = """GetRiAttribute(name, nameSpace) -> Attribute
Return a UsdAttribute representing the Ri attribute with the name
*name*, in the namespace *nameSpace*.
The attribute returned may or may not **actually** exist so it must be
checked for validity.
Parameters
----------
name : str
nameSpace : str
"""
result["StatementsAPI"].GetRiAttributes.func_doc = """GetRiAttributes(nameSpace) -> list[Property]
Return all rib attributes on this prim, or under a specific namespace
(e.g."user").
As noted above, rib attributes can be either UsdAttribute or
UsdRelationship, and like all UsdProperties, need not have a defined
value.
Parameters
----------
nameSpace : str
"""
result["StatementsAPI"].SetCoordinateSystem.func_doc = """SetCoordinateSystem(coordSysName) -> None
Sets the"ri:coordinateSystem"attribute to the given string value,
creating the attribute if needed.
That identifies this prim as providing a coordinate system, which can
be retrieved via UsdGeomXformable::GetTransformAttr(). Also adds the
owning prim to the ri:modelCoordinateSystems relationship targets on
its parent leaf model prim, if it exists. If this prim is not under a
leaf model, no relationship targets will be authored.
Parameters
----------
coordSysName : str
"""
result["StatementsAPI"].GetCoordinateSystem.func_doc = """GetCoordinateSystem() -> str
Returns the value in the"ri:coordinateSystem"attribute if it exists.
"""
result["StatementsAPI"].HasCoordinateSystem.func_doc = """HasCoordinateSystem() -> bool
Returns true if the underlying prim has a ri:coordinateSystem opinion.
"""
result["StatementsAPI"].SetScopedCoordinateSystem.func_doc = """SetScopedCoordinateSystem(coordSysName) -> None
Sets the"ri:scopedCoordinateSystem"attribute to the given string
value, creating the attribute if needed.
That identifies this prim as providing a coordinate system, which can
be retrieved via UsdGeomXformable::GetTransformAttr(). Such coordinate
systems are local to the RI attribute stack state, but does get
updated properly for instances when defined inside an object master.
Also adds the owning prim to the ri:modelScopedCoordinateSystems
relationship targets on its parent leaf model prim, if it exists. If
this prim is not under a leaf model, no relationship targets will be
authored.
Parameters
----------
coordSysName : str
"""
result["StatementsAPI"].GetScopedCoordinateSystem.func_doc = """GetScopedCoordinateSystem() -> str
Returns the value in the"ri:scopedCoordinateSystem"attribute if it
exists.
"""
result["StatementsAPI"].HasScopedCoordinateSystem.func_doc = """HasScopedCoordinateSystem() -> bool
Returns true if the underlying prim has a ri:scopedCoordinateSystem
opinion.
"""
result["StatementsAPI"].GetModelCoordinateSystems.func_doc = """GetModelCoordinateSystems(targets) -> bool
Populates the output ``targets`` with the authored
ri:modelCoordinateSystems, if any.
Returns true if the query was successful.
Parameters
----------
targets : list[SdfPath]
"""
result["StatementsAPI"].GetModelScopedCoordinateSystems.func_doc = """GetModelScopedCoordinateSystems(targets) -> bool
Populates the output ``targets`` with the authored
ri:modelScopedCoordinateSystems, if any.
Returns true if the query was successful.
Parameters
----------
targets : list[SdfPath]
"""
result["StatementsAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["StatementsAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> StatementsAPI
Return a UsdRiStatementsAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRiStatementsAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["StatementsAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["StatementsAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> StatementsAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"StatementsAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdRiStatementsAPI object is returned upon success. An invalid
(or empty) UsdRiStatementsAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["StatementsAPI"].GetRiAttributeName.func_doc = """**classmethod** GetRiAttributeName(prop) -> str
Return the base, most-specific name of the rib attribute.
For example, the *name* of the rib
attribute"cull:backfacing"is"backfacing"
Parameters
----------
prop : Property
"""
result["StatementsAPI"].GetRiAttributeNameSpace.func_doc = """**classmethod** GetRiAttributeNameSpace(prop) -> str
Return the containing namespace of the rib attribute (e.g."user").
Parameters
----------
prop : Property
"""
result["StatementsAPI"].IsRiAttribute.func_doc = """**classmethod** IsRiAttribute(prop) -> bool
Return true if the property is in the"ri:attributes"namespace.
Parameters
----------
prop : Property
"""
result["StatementsAPI"].MakeRiAttributePropertyName.func_doc = """**classmethod** MakeRiAttributePropertyName(attrName) -> str
Returns the given ``attrName`` prefixed with the full Ri attribute
namespace, creating a name suitable for an RiAttribute UsdProperty.
This handles conversion of common separator characters used in other
packages, such as periods and underscores.
Will return empty string if attrName is not a valid property
identifier; otherwise, will return a valid property name that
identifies the property as an RiAttribute, according to the following
rules:
- If ``attrName`` is already a properly constructed RiAttribute
property name, return it unchanged.
- If ``attrName`` contains two or more tokens separated by a
*colon*, consider the first to be the namespace, and the rest the
name, joined by underscores
- If ``attrName`` contains two or more tokens separated by a
*period*, consider the first to be the namespace, and the rest the
name, joined by underscores
- If ``attrName`` contains two or more tokens separated by an,
*underscore* consider the first to be the namespace, and the rest the
name, joined by underscores
- else, assume ``attrName`` is the name, and"user"is the namespace
Parameters
----------
attrName : str
"""
result["StatementsAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["TextureAPI"].__doc__ = """
Deprecated
This API schema will be removed in a future release.
RiTextureAPI is an API schema that provides an interface to add
Renderman-specific attributes to adjust textures.
"""
result["TextureAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdRiTextureAPI on UsdPrim ``prim`` .
Equivalent to UsdRiTextureAPI::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdRiTextureAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdRiTextureAPI (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["TextureAPI"].GetRiTextureGammaAttr.func_doc = """GetRiTextureGammaAttr() -> Attribute
Gamma-correct the texture.
Declaration
``float ri:texture:gamma``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["TextureAPI"].CreateRiTextureGammaAttr.func_doc = """CreateRiTextureGammaAttr(defaultValue, writeSparsely) -> Attribute
See GetRiTextureGammaAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["TextureAPI"].GetRiTextureSaturationAttr.func_doc = """GetRiTextureSaturationAttr() -> Attribute
Adjust the texture's saturation.
Declaration
``float ri:texture:saturation``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["TextureAPI"].CreateRiTextureSaturationAttr.func_doc = """CreateRiTextureSaturationAttr(defaultValue, writeSparsely) -> Attribute
See GetRiTextureSaturationAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["TextureAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["TextureAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> TextureAPI
Return a UsdRiTextureAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdRiTextureAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["TextureAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["TextureAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> TextureAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"RiTextureAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdRiTextureAPI object is returned upon success. An invalid
(or empty) UsdRiTextureAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["TextureAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
""" | 30,791 | Python | 20.279889 | 174 | 0.719821 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdProc/__DOC.py | def Execute(result):
result["GenerativeProcedural"].__doc__ = """
Represents an abstract generative procedural prim which delivers its
input parameters via properties (including relationships) within
the"primvars:"namespace.
It does not itself have any awareness or participation in the
execution of the procedural but rather serves as a means of delivering
a procedural's definition and input parameters.
The value of its"proceduralSystem"property (either authored or
provided by API schema fallback) indicates to which system the
procedural definition is meaningful.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdProcTokens. So to set an attribute to the value"rightHanded",
use UsdProcTokens->rightHanded as the value.
"""
result["GenerativeProcedural"].__init__.func_doc = """__init__(prim)
Construct a UsdProcGenerativeProcedural on UsdPrim ``prim`` .
Equivalent to UsdProcGenerativeProcedural::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdProcGenerativeProcedural on the prim held by
``schemaObj`` .
Should be preferred over UsdProcGenerativeProcedural
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["GenerativeProcedural"].GetProceduralSystemAttr.func_doc = """GetProceduralSystemAttr() -> Attribute
The name or convention of the system responsible for evaluating the
procedural.
NOTE: A fallback value for this is typically set via an API schema.
Declaration
``token proceduralSystem``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["GenerativeProcedural"].CreateProceduralSystemAttr.func_doc = """CreateProceduralSystemAttr(defaultValue, writeSparsely) -> Attribute
See GetProceduralSystemAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["GenerativeProcedural"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["GenerativeProcedural"].Get.func_doc = """**classmethod** Get(stage, path) -> GenerativeProcedural
Return a UsdProcGenerativeProcedural holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdProcGenerativeProcedural(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["GenerativeProcedural"].Define.func_doc = """**classmethod** Define(stage, path) -> GenerativeProcedural
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["GenerativeProcedural"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
""" | 4,660 | Python | 24.60989 | 146 | 0.741631 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdLux/__DOC.py | def Execute(result):
result["BoundableLightBase"].__doc__ = """
Base class for intrinsic lights that are boundable.
The primary purpose of this class is to provide a direct API to the
functions provided by LightAPI for concrete derived light types.
"""
result["BoundableLightBase"].LightAPI.func_doc = """LightAPI() -> LightAPI
Contructs and returns a UsdLuxLightAPI object for this light.
"""
result["BoundableLightBase"].GetIntensityAttr.func_doc = """GetIntensityAttr() -> Attribute
See UsdLuxLightAPI::GetIntensityAttr() .
"""
result["BoundableLightBase"].CreateIntensityAttr.func_doc = """CreateIntensityAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateIntensityAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BoundableLightBase"].GetExposureAttr.func_doc = """GetExposureAttr() -> Attribute
See UsdLuxLightAPI::GetExposureAttr() .
"""
result["BoundableLightBase"].CreateExposureAttr.func_doc = """CreateExposureAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateExposureAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BoundableLightBase"].GetDiffuseAttr.func_doc = """GetDiffuseAttr() -> Attribute
See UsdLuxLightAPI::GetDiffuseAttr() .
"""
result["BoundableLightBase"].CreateDiffuseAttr.func_doc = """CreateDiffuseAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateDiffuseAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BoundableLightBase"].GetSpecularAttr.func_doc = """GetSpecularAttr() -> Attribute
See UsdLuxLightAPI::GetSpecularAttr() .
"""
result["BoundableLightBase"].CreateSpecularAttr.func_doc = """CreateSpecularAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateSpecularAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BoundableLightBase"].GetNormalizeAttr.func_doc = """GetNormalizeAttr() -> Attribute
See UsdLuxLightAPI::GetNormalizeAttr() .
"""
result["BoundableLightBase"].CreateNormalizeAttr.func_doc = """CreateNormalizeAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateNormalizeAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BoundableLightBase"].GetColorAttr.func_doc = """GetColorAttr() -> Attribute
See UsdLuxLightAPI::GetColorAttr() .
"""
result["BoundableLightBase"].CreateColorAttr.func_doc = """CreateColorAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateColorAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BoundableLightBase"].GetEnableColorTemperatureAttr.func_doc = """GetEnableColorTemperatureAttr() -> Attribute
See UsdLuxLightAPI::GetEnableColorTemperatureAttr() .
"""
result["BoundableLightBase"].CreateEnableColorTemperatureAttr.func_doc = """CreateEnableColorTemperatureAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateEnableColorTemperatureAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BoundableLightBase"].GetColorTemperatureAttr.func_doc = """GetColorTemperatureAttr() -> Attribute
See UsdLuxLightAPI::GetColorTemperatureAttr() .
"""
result["BoundableLightBase"].CreateColorTemperatureAttr.func_doc = """CreateColorTemperatureAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateColorTemperatureAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BoundableLightBase"].GetFiltersRel.func_doc = """GetFiltersRel() -> Relationship
See UsdLuxLightAPI::GetFiltersRel() .
"""
result["BoundableLightBase"].CreateFiltersRel.func_doc = """CreateFiltersRel() -> Relationship
See UsdLuxLightAPI::CreateFiltersRel() .
"""
result["BoundableLightBase"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxBoundableLightBase on UsdPrim ``prim`` .
Equivalent to UsdLuxBoundableLightBase::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxBoundableLightBase on the prim held by ``schemaObj``
.
Should be preferred over UsdLuxBoundableLightBase
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["BoundableLightBase"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["BoundableLightBase"].Get.func_doc = """**classmethod** Get(stage, path) -> BoundableLightBase
Return a UsdLuxBoundableLightBase holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxBoundableLightBase(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["BoundableLightBase"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["CylinderLight"].__doc__ = """
Light emitted outward from a cylinder. The cylinder is centered at the
origin and has its major axis on the X axis. The cylinder does not
emit light from the flat end-caps.
"""
result["CylinderLight"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxCylinderLight on UsdPrim ``prim`` .
Equivalent to UsdLuxCylinderLight::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxCylinderLight on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxCylinderLight (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["CylinderLight"].GetLengthAttr.func_doc = """GetLengthAttr() -> Attribute
Width of the rectangle, in the local X axis.
Declaration
``float inputs:length = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["CylinderLight"].CreateLengthAttr.func_doc = """CreateLengthAttr(defaultValue, writeSparsely) -> Attribute
See GetLengthAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["CylinderLight"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute
Radius of the cylinder.
Declaration
``float inputs:radius = 0.5``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["CylinderLight"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute
See GetRadiusAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["CylinderLight"].GetTreatAsLineAttr.func_doc = """GetTreatAsLineAttr() -> Attribute
A hint that this light can be treated as a'line'light (effectively, a
zero-radius cylinder) by renderers that benefit from non-area
lighting.
Renderers that only support area lights can disregard this.
Declaration
``bool treatAsLine = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["CylinderLight"].CreateTreatAsLineAttr.func_doc = """CreateTreatAsLineAttr(defaultValue, writeSparsely) -> Attribute
See GetTreatAsLineAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["CylinderLight"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["CylinderLight"].Get.func_doc = """**classmethod** Get(stage, path) -> CylinderLight
Return a UsdLuxCylinderLight holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxCylinderLight(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["CylinderLight"].Define.func_doc = """**classmethod** Define(stage, path) -> CylinderLight
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["CylinderLight"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["DiskLight"].__doc__ = """
Light emitted from one side of a circular disk. The disk is centered
in the XY plane and emits light along the -Z axis.
"""
result["DiskLight"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxDiskLight on UsdPrim ``prim`` .
Equivalent to UsdLuxDiskLight::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxDiskLight on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxDiskLight (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["DiskLight"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute
Radius of the disk.
Declaration
``float inputs:radius = 0.5``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DiskLight"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute
See GetRadiusAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DiskLight"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["DiskLight"].Get.func_doc = """**classmethod** Get(stage, path) -> DiskLight
Return a UsdLuxDiskLight holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxDiskLight(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["DiskLight"].Define.func_doc = """**classmethod** Define(stage, path) -> DiskLight
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["DiskLight"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["DistantLight"].__doc__ = """
Light emitted from a distant source along the -Z axis. Also known as a
directional light.
"""
result["DistantLight"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxDistantLight on UsdPrim ``prim`` .
Equivalent to UsdLuxDistantLight::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxDistantLight on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxDistantLight (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["DistantLight"].GetAngleAttr.func_doc = """GetAngleAttr() -> Attribute
Angular size of the light in degrees.
As an example, the Sun is approximately 0.53 degrees as seen from
Earth. Higher values broaden the light and therefore soften shadow
edges.
Declaration
``float inputs:angle = 0.53``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DistantLight"].CreateAngleAttr.func_doc = """CreateAngleAttr(defaultValue, writeSparsely) -> Attribute
See GetAngleAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DistantLight"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["DistantLight"].Get.func_doc = """**classmethod** Get(stage, path) -> DistantLight
Return a UsdLuxDistantLight holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxDistantLight(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["DistantLight"].Define.func_doc = """**classmethod** Define(stage, path) -> DistantLight
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["DistantLight"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["DomeLight"].__doc__ = """
Light emitted inward from a distant external environment, such as a
sky or IBL light probe. The orientation of a dome light with a latlong
texture is expected to match the OpenEXR specification for latlong
environment maps. From the OpenEXR documentation:
Latitude-Longitude Map:
The environment is projected onto the image using polar coordinates
(latitude and longitude). A pixel's x coordinate corresponds to its
longitude, and the y coordinate corresponds to its latitude. Pixel
(dataWindow.min.x, dataWindow.min.y) has latitude +pi/2 and longitude
+pi; pixel (dataWindow.max.x, dataWindow.max.y) has latitude -pi/2 and
longitude -pi.
In 3D space, latitudes -pi/2 and +pi/2 correspond to the negative and
positive y direction. Latitude 0, longitude 0 points into positive z
direction; and latitude 0, longitude pi/2 points into positive x
direction.
The size of the data window should be 2\\*N by N pixels (width by
height),
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdLuxTokens. So to set an attribute to the value"rightHanded", use
UsdLuxTokens->rightHanded as the value.
"""
result["DomeLight"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxDomeLight on UsdPrim ``prim`` .
Equivalent to UsdLuxDomeLight::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxDomeLight on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxDomeLight (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["DomeLight"].GetTextureFileAttr.func_doc = """GetTextureFileAttr() -> Attribute
A color texture to use on the dome, such as an HDR (high dynamic
range) texture intended for IBL (image based lighting).
Declaration
``asset inputs:texture:file``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
"""
result["DomeLight"].CreateTextureFileAttr.func_doc = """CreateTextureFileAttr(defaultValue, writeSparsely) -> Attribute
See GetTextureFileAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DomeLight"].GetTextureFormatAttr.func_doc = """GetTextureFormatAttr() -> Attribute
Specifies the parameterization of the color map file.
Valid values are:
- automatic: Tries to determine the layout from the file itself.
For example, Renderman texture files embed an explicit
parameterization.
- latlong: Latitude as X, longitude as Y.
- mirroredBall: An image of the environment reflected in a sphere,
using an implicitly orthogonal projection.
- angular: Similar to mirroredBall but the radial dimension is
mapped linearly to the angle, providing better sampling at the edges.
- cubeMapVerticalCross: A cube map with faces laid out as a
vertical cross.
Declaration
``token inputs:texture:format ="automatic"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Allowed Values
automatic, latlong, mirroredBall, angular, cubeMapVerticalCross
"""
result["DomeLight"].CreateTextureFormatAttr.func_doc = """CreateTextureFormatAttr(defaultValue, writeSparsely) -> Attribute
See GetTextureFormatAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DomeLight"].GetGuideRadiusAttr.func_doc = """GetGuideRadiusAttr() -> Attribute
The radius of guide geometry to use to visualize the dome light.
The default is 1 km for scenes whose metersPerUnit is the USD default
of 0.01 (i.e., 1 world unit is 1 cm).
Declaration
``float guideRadius = 100000``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["DomeLight"].CreateGuideRadiusAttr.func_doc = """CreateGuideRadiusAttr(defaultValue, writeSparsely) -> Attribute
See GetGuideRadiusAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["DomeLight"].GetPortalsRel.func_doc = """GetPortalsRel() -> Relationship
Optional portals to guide light sampling.
"""
result["DomeLight"].CreatePortalsRel.func_doc = """CreatePortalsRel() -> Relationship
See GetPortalsRel() , and also Create vs Get Property Methods for when
to use Get vs Create.
"""
result["DomeLight"].OrientToStageUpAxis.func_doc = """OrientToStageUpAxis() -> None
Adds a transformation op, if neeeded, to orient the dome to align with
the stage's up axis.
Uses UsdLuxTokens->orientToStageUpAxis as the op suffix. If an op with
this suffix already exists, this method assumes it is already applying
the proper correction and does nothing further. If no op is required
to match the stage's up axis, no op will be created.
UsdGeomXformOp
UsdGeomGetStageUpAxis
"""
result["DomeLight"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["DomeLight"].Get.func_doc = """**classmethod** Get(stage, path) -> DomeLight
Return a UsdLuxDomeLight holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxDomeLight(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["DomeLight"].Define.func_doc = """**classmethod** Define(stage, path) -> DomeLight
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["DomeLight"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["GeometryLight"].__doc__ = """
Deprecated
Light emitted outward from a geometric prim (UsdGeomGprim), which is
typically a mesh.
"""
result["GeometryLight"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxGeometryLight on UsdPrim ``prim`` .
Equivalent to UsdLuxGeometryLight::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxGeometryLight on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxGeometryLight (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["GeometryLight"].GetGeometryRel.func_doc = """GetGeometryRel() -> Relationship
Relationship to the geometry to use as the light source.
"""
result["GeometryLight"].CreateGeometryRel.func_doc = """CreateGeometryRel() -> Relationship
See GetGeometryRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["GeometryLight"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["GeometryLight"].Get.func_doc = """**classmethod** Get(stage, path) -> GeometryLight
Return a UsdLuxGeometryLight holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxGeometryLight(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["GeometryLight"].Define.func_doc = """**classmethod** Define(stage, path) -> GeometryLight
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["GeometryLight"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["LightAPI"].__doc__ = """
API schema that imparts the quality of being a light onto a prim.
A light is any prim that has this schema applied to it. This is true
regardless of whether LightAPI is included as a built-in API of the
prim type (e.g. RectLight or DistantLight) or is applied directly to a
Gprim that should be treated as a light.
**Linking**
Lights can be linked to geometry. Linking controls which geometry a
light illuminates, and which geometry casts shadows from the light.
Linking is specified as collections (UsdCollectionAPI) which can be
accessed via GetLightLinkCollection() and GetShadowLinkCollection().
Note that these collections have their includeRoot set to true, so
that lights will illuminate and cast shadows from all objects by
default. To illuminate only a specific set of objects, there are two
options. One option is to modify the collection paths to explicitly
exclude everything else, assuming it is known; the other option is to
set includeRoot to false and explicitly include the desired objects.
These are complementary approaches that may each be preferable
depending on the scenario and how to best express the intent of the
light setup.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdLuxTokens. So to set an attribute to the value"rightHanded", use
UsdLuxTokens->rightHanded as the value.
"""
result["LightAPI"].__init__.func_doc = """__init__(connectable)
Constructor that takes a ConnectableAPI object.
Allow implicit conversion of a UsdShadeConnectableAPI to
UsdLuxLightAPI
Parameters
----------
connectable : ConnectableAPI
----------------------------------------------------------------------
__init__(prim)
Construct a UsdLuxLightAPI on UsdPrim ``prim`` .
Equivalent to UsdLuxLightAPI::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxLightAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxLightAPI (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["LightAPI"].ConnectableAPI.func_doc = """ConnectableAPI() -> ConnectableAPI
Contructs and returns a UsdShadeConnectableAPI object with this light.
Note that most tasks can be accomplished without explicitly
constructing a UsdShadeConnectable API, since connection-related API
such as UsdShadeConnectableAPI::ConnectToSource() are static methods,
and UsdLuxLightAPI will auto-convert to a UsdShadeConnectableAPI when
passed to functions that want to act generically on a connectable
UsdShadeConnectableAPI object.
"""
result["LightAPI"].CreateOutput.func_doc = """CreateOutput(name, typeName) -> Output
Create an output which can either have a value or can be connected.
The attribute representing the output is created in
the"outputs:"namespace. Outputs on a light cannot be connected, as
their value is assumed to be computed externally.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["LightAPI"].GetOutput.func_doc = """GetOutput(name) -> Output
Return the requested output if it exists.
Parameters
----------
name : str
"""
result["LightAPI"].GetOutputs.func_doc = """GetOutputs(onlyAuthored) -> list[Output]
Outputs are represented by attributes in the"outputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["LightAPI"].CreateInput.func_doc = """CreateInput(name, typeName) -> Input
Create an input which can either have a value or can be connected.
The attribute representing the input is created in
the"inputs:"namespace. Inputs on lights are connectable.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["LightAPI"].GetInput.func_doc = """GetInput(name) -> Input
Return the requested input if it exists.
Parameters
----------
name : str
"""
result["LightAPI"].GetInputs.func_doc = """GetInputs(onlyAuthored) -> list[Input]
Inputs are represented by attributes in the"inputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["LightAPI"].GetShaderIdAttr.func_doc = """GetShaderIdAttr() -> Attribute
Default ID for the light's shader.
This defines the shader ID for this light when a render context
specific shader ID is not available.
The default shaderId for the intrinsic UsdLux lights (RectLight,
DistantLight, etc.) are set to default to the light's type name. For
each intrinsic UsdLux light, we will always register an SdrShaderNode
in the SdrRegistry, with the identifier matching the type name and the
source type"USD", that corresponds to the light's inputs.
GetShaderId
GetShaderIdAttrForRenderContext
SdrRegistry::GetShaderNodeByIdentifier
SdrRegistry::GetShaderNodeByIdentifierAndType
Declaration
``uniform token light:shaderId =""``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["LightAPI"].CreateShaderIdAttr.func_doc = """CreateShaderIdAttr(defaultValue, writeSparsely) -> Attribute
See GetShaderIdAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetMaterialSyncModeAttr.func_doc = """GetMaterialSyncModeAttr() -> Attribute
For a LightAPI applied to geometry that has a bound Material, which is
entirely or partly emissive, this specifies the relationship of the
Material response to the lighting response.
Valid values are:
- materialGlowTintsLight: All primary and secondary rays see the
emissive/glow response as dictated by the bound Material while the
base color seen by light rays (which is then modulated by all of the
other LightAPI controls) is the multiplication of the color feeding
the emission/glow input of the Material (i.e. its surface or volume
shader) with the scalar or pattern input to *inputs:color*. This
allows the light's color to tint the geometry's glow color while
preserving access to intensity and other light controls as ways to
further modulate the illumination.
- independent: All primary and secondary rays see the emissive/glow
response as dictated by the bound Material, while the base color seen
by light rays is determined solely by *inputs:color*. Note that for
partially emissive geometry (in which some parts are reflective rather
than emissive), a suitable pattern must be connected to the light's
color input, or else the light will radiate uniformly from the
geometry.
- noMaterialResponse: The geometry behaves as if there is no
Material bound at all, i.e. there is no diffuse, specular, or
transmissive response. The base color of light rays is entirely
controlled by the *inputs:color*. This is the standard mode
for"canonical"lights in UsdLux and indicates to renderers that a
Material will either never be bound or can always be ignored.
Declaration
``uniform token light:materialSyncMode ="noMaterialResponse"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
materialGlowTintsLight, independent, noMaterialResponse
"""
result["LightAPI"].CreateMaterialSyncModeAttr.func_doc = """CreateMaterialSyncModeAttr(defaultValue, writeSparsely) -> Attribute
See GetMaterialSyncModeAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetIntensityAttr.func_doc = """GetIntensityAttr() -> Attribute
Scales the power of the light linearly.
Declaration
``float inputs:intensity = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["LightAPI"].CreateIntensityAttr.func_doc = """CreateIntensityAttr(defaultValue, writeSparsely) -> Attribute
See GetIntensityAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetExposureAttr.func_doc = """GetExposureAttr() -> Attribute
Scales the power of the light exponentially as a power of 2 (similar
to an F-stop control over exposure).
The result is multiplied against the intensity.
Declaration
``float inputs:exposure = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["LightAPI"].CreateExposureAttr.func_doc = """CreateExposureAttr(defaultValue, writeSparsely) -> Attribute
See GetExposureAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetDiffuseAttr.func_doc = """GetDiffuseAttr() -> Attribute
A multiplier for the effect of this light on the diffuse response of
materials.
This is a non-physical control.
Declaration
``float inputs:diffuse = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["LightAPI"].CreateDiffuseAttr.func_doc = """CreateDiffuseAttr(defaultValue, writeSparsely) -> Attribute
See GetDiffuseAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetSpecularAttr.func_doc = """GetSpecularAttr() -> Attribute
A multiplier for the effect of this light on the specular response of
materials.
This is a non-physical control.
Declaration
``float inputs:specular = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["LightAPI"].CreateSpecularAttr.func_doc = """CreateSpecularAttr(defaultValue, writeSparsely) -> Attribute
See GetSpecularAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetNormalizeAttr.func_doc = """GetNormalizeAttr() -> Attribute
Normalizes power by the surface area of the light.
This makes it easier to independently adjust the power and shape of
the light, by causing the power to not vary with the area or angular
size of the light.
Declaration
``bool inputs:normalize = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["LightAPI"].CreateNormalizeAttr.func_doc = """CreateNormalizeAttr(defaultValue, writeSparsely) -> Attribute
See GetNormalizeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetColorAttr.func_doc = """GetColorAttr() -> Attribute
The color of emitted light, in energy-linear terms.
Declaration
``color3f inputs:color = (1, 1, 1)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Color3f
"""
result["LightAPI"].CreateColorAttr.func_doc = """CreateColorAttr(defaultValue, writeSparsely) -> Attribute
See GetColorAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetEnableColorTemperatureAttr.func_doc = """GetEnableColorTemperatureAttr() -> Attribute
Enables using colorTemperature.
Declaration
``bool inputs:enableColorTemperature = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["LightAPI"].CreateEnableColorTemperatureAttr.func_doc = """CreateEnableColorTemperatureAttr(defaultValue, writeSparsely) -> Attribute
See GetEnableColorTemperatureAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetColorTemperatureAttr.func_doc = """GetColorTemperatureAttr() -> Attribute
Color temperature, in degrees Kelvin, representing the white point.
The default is a common white point, D65. Lower values are warmer and
higher values are cooler. The valid range is from 1000 to 10000. Only
takes effect when enableColorTemperature is set to true. When active,
the computed result multiplies against the color attribute. See
UsdLuxBlackbodyTemperatureAsRgb() .
Declaration
``float inputs:colorTemperature = 6500``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["LightAPI"].CreateColorTemperatureAttr.func_doc = """CreateColorTemperatureAttr(defaultValue, writeSparsely) -> Attribute
See GetColorTemperatureAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetFiltersRel.func_doc = """GetFiltersRel() -> Relationship
Relationship to the light filters that apply to this light.
"""
result["LightAPI"].CreateFiltersRel.func_doc = """CreateFiltersRel() -> Relationship
See GetFiltersRel() , and also Create vs Get Property Methods for when
to use Get vs Create.
"""
result["LightAPI"].GetLightLinkCollectionAPI.func_doc = """GetLightLinkCollectionAPI() -> CollectionAPI
Return the UsdCollectionAPI interface used for examining and modifying
the light-linking of this light.
Light-linking controls which geometry this light illuminates.
"""
result["LightAPI"].GetShadowLinkCollectionAPI.func_doc = """GetShadowLinkCollectionAPI() -> CollectionAPI
Return the UsdCollectionAPI interface used for examining and modifying
the shadow-linking of this light.
Shadow-linking controls which geometry casts shadows from this light.
"""
result["LightAPI"].GetShaderIdAttrForRenderContext.func_doc = """GetShaderIdAttrForRenderContext(renderContext) -> Attribute
Returns the shader ID attribute for the given ``renderContext`` .
If ``renderContext`` is non-empty, this will try to return an
attribute named *light:shaderId* with the namespace prefix
``renderContext`` . For example, if the passed in render context
is"ri"then the attribute returned by this function would have the
following signature:
Declaration
``token ri:light:shaderId``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
If the render context is empty, this will return the default shader ID
attribute as returned by GetShaderIdAttr() .
Parameters
----------
renderContext : str
"""
result["LightAPI"].CreateShaderIdAttrForRenderContext.func_doc = """CreateShaderIdAttrForRenderContext(renderContext, defaultValue, writeSparsely) -> Attribute
Creates the shader ID attribute for the given ``renderContext`` .
See GetShaderIdAttrForRenderContext() , and also Create vs Get
Property Methods for when to use Get vs Create. If specified, author
``defaultValue`` as the attribute's default, sparsely (when it makes
sense to do so) if ``writeSparsely`` is ``true`` - the default for
``writeSparsely`` is ``false`` .
Parameters
----------
renderContext : str
defaultValue : VtValue
writeSparsely : bool
"""
result["LightAPI"].GetShaderId.func_doc = """GetShaderId(renderContexts) -> str
Return the light's shader ID for the given list of available
``renderContexts`` .
The shader ID returned by this function is the identifier to use when
looking up the shader definition for this light in the shader
registry.
The render contexts are expected to be listed in priority order, so
for each render context provided, this will try to find the shader ID
attribute specific to that render context (see
GetShaderIdAttrForRenderContext() ) and will return the value of the
first one found that has a non-empty value. If no shader ID value can
be found for any of the given render contexts or ``renderContexts`` is
empty, then this will return the value of the default shader ID
attribute (see GetShaderIdAttr() ).
Parameters
----------
renderContexts : list[TfToken]
"""
result["LightAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["LightAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> LightAPI
Return a UsdLuxLightAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxLightAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["LightAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["LightAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> LightAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"LightAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdLuxLightAPI object is returned upon success. An invalid (or
empty) UsdLuxLightAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["LightAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["LightFilter"].__doc__ = """
A light filter modifies the effect of a light. Lights refer to filters
via relationships so that filters may be shared.
**Linking**
Filters can be linked to geometry. Linking controls which geometry a
light-filter affects, when considering the light filters attached to a
light illuminating the geometry.
Linking is specified as a collection (UsdCollectionAPI) which can be
accessed via GetFilterLinkCollection().
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdLuxTokens. So to set an attribute to the value"rightHanded", use
UsdLuxTokens->rightHanded as the value.
"""
result["LightFilter"].__init__.func_doc = """__init__(connectable)
Constructor that takes a ConnectableAPI object.
Allow implicit conversion of UsdShadeConnectableAPI to
UsdLuxLightFilter.
Parameters
----------
connectable : ConnectableAPI
----------------------------------------------------------------------
__init__(prim)
Construct a UsdLuxLightFilter on UsdPrim ``prim`` .
Equivalent to UsdLuxLightFilter::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxLightFilter on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxLightFilter (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["LightFilter"].ConnectableAPI.func_doc = """ConnectableAPI() -> ConnectableAPI
Contructs and returns a UsdShadeConnectableAPI object with this light
filter.
Note that most tasks can be accomplished without explicitly
constructing a UsdShadeConnectable API, since connection-related API
such as UsdShadeConnectableAPI::ConnectToSource() are static methods,
and UsdLuxLightFilter will auto-convert to a UsdShadeConnectableAPI
when passed to functions that want to act generically on a connectable
UsdShadeConnectableAPI object.
"""
result["LightFilter"].CreateOutput.func_doc = """CreateOutput(name, typeName) -> Output
Create an output which can either have a value or can be connected.
The attribute representing the output is created in
the"outputs:"namespace. Outputs on a light filter cannot be connected,
as their value is assumed to be computed externally.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["LightFilter"].GetOutput.func_doc = """GetOutput(name) -> Output
Return the requested output if it exists.
Parameters
----------
name : str
"""
result["LightFilter"].GetOutputs.func_doc = """GetOutputs(onlyAuthored) -> list[Output]
Outputs are represented by attributes in the"outputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["LightFilter"].CreateInput.func_doc = """CreateInput(name, typeName) -> Input
Create an input which can either have a value or can be connected.
The attribute representing the input is created in
the"inputs:"namespace. Inputs on light filters are connectable.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["LightFilter"].GetInput.func_doc = """GetInput(name) -> Input
Return the requested input if it exists.
Parameters
----------
name : str
"""
result["LightFilter"].GetInputs.func_doc = """GetInputs(onlyAuthored) -> list[Input]
Inputs are represented by attributes in the"inputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["LightFilter"].GetShaderIdAttr.func_doc = """GetShaderIdAttr() -> Attribute
Default ID for the light filter's shader.
This defines the shader ID for this light filter when a render context
specific shader ID is not available.
GetShaderId
GetShaderIdAttrForRenderContext
SdrRegistry::GetShaderNodeByIdentifier
SdrRegistry::GetShaderNodeByIdentifierAndType
Declaration
``uniform token lightFilter:shaderId =""``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["LightFilter"].CreateShaderIdAttr.func_doc = """CreateShaderIdAttr(defaultValue, writeSparsely) -> Attribute
See GetShaderIdAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightFilter"].GetFilterLinkCollectionAPI.func_doc = """GetFilterLinkCollectionAPI() -> CollectionAPI
Return the UsdCollectionAPI interface used for examining and modifying
the filter-linking of this light filter.
Linking controls which geometry this light filter affects.
"""
result["LightFilter"].GetShaderIdAttrForRenderContext.func_doc = """GetShaderIdAttrForRenderContext(renderContext) -> Attribute
Returns the shader ID attribute for the given ``renderContext`` .
If ``renderContext`` is non-empty, this will try to return an
attribute named *lightFilter:shaderId* with the namespace prefix
``renderContext`` . For example, if the passed in render context
is"ri"then the attribute returned by this function would have the
following signature:
Declaration
``token ri:lightFilter:shaderId``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
If the render context is empty, this will return the default shader ID
attribute as returned by GetShaderIdAttr() .
Parameters
----------
renderContext : str
"""
result["LightFilter"].CreateShaderIdAttrForRenderContext.func_doc = """CreateShaderIdAttrForRenderContext(renderContext, defaultValue, writeSparsely) -> Attribute
Creates the shader ID attribute for the given ``renderContext`` .
See GetShaderIdAttrForRenderContext() , and also Create vs Get
Property Methods for when to use Get vs Create. If specified, author
``defaultValue`` as the attribute's default, sparsely (when it makes
sense to do so) if ``writeSparsely`` is ``true`` - the default for
``writeSparsely`` is ``false`` .
Parameters
----------
renderContext : str
defaultValue : VtValue
writeSparsely : bool
"""
result["LightFilter"].GetShaderId.func_doc = """GetShaderId(renderContexts) -> str
Return the light filter's shader ID for the given list of available
``renderContexts`` .
The shader ID returned by this function is the identifier to use when
looking up the shader definition for this light filter in the shader
registry.
The render contexts are expected to be listed in priority order, so
for each render context provided, this will try to find the shader ID
attribute specific to that render context (see
GetShaderIdAttrForRenderContext() ) and will return the value of the
first one found that has a non-empty value. If no shader ID value can
be found for any of the given render contexts or ``renderContexts`` is
empty, then this will return the value of the default shader ID
attribute (see GetShaderIdAttr() ).
Parameters
----------
renderContexts : list[TfToken]
"""
result["LightFilter"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["LightFilter"].Get.func_doc = """**classmethod** Get(stage, path) -> LightFilter
Return a UsdLuxLightFilter holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxLightFilter(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["LightFilter"].Define.func_doc = """**classmethod** Define(stage, path) -> LightFilter
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["LightFilter"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["LightListAPI"].__doc__ = """
API schema to support discovery and publishing of lights in a scene.
Discovering Lights via Traversal
================================
To motivate this API, consider what is required to discover all lights
in a scene. We must load all payloads and traverse all prims:
.. code-block:: text
01 // Load everything on the stage so we can find all lights,
02 // including those inside payloads
03 stage->Load();
04
05 // Traverse all prims, checking if they have an applied UsdLuxLightAPI
06 // (Note: ignoring instancing and a few other things for simplicity)
07 SdfPathVector lights;
08 for (UsdPrim prim: stage->Traverse()) {
09 if (prim.HasAPI<UsdLuxLightAPI>()) {
10 lights.push_back(i->GetPath());
11 }
12 }
This traversal suitably elaborated to handle certain details is the
first and simplest thing UsdLuxLightListAPI provides.
UsdLuxLightListAPI::ComputeLightList() performs this traversal and
returns all lights in the scene:
.. code-block:: text
01 UsdLuxLightListAPI listAPI(stage->GetPseudoRoot());
02 SdfPathVector lights = listAPI.ComputeLightList();
Publishing a Cached Light List
==============================
Consider a USD client that needs to quickly discover lights but wants
to defer loading payloads and traversing the entire scene where
possible, and is willing to do up-front computation and caching to
achieve that.
UsdLuxLightListAPI provides a way to cache the computed light list, by
publishing the list of lights onto prims in the model hierarchy.
Consider a big set that contains lights:
.. code-block:: text
01 def Xform "BigSetWithLights" (
02 kind = "assembly"
03 payload = @BigSetWithLights.usd@ // Heavy payload
04 ) {
05 // Pre-computed, cached list of lights inside payload
06 rel lightList = [
07 <./Lights/light_1>,
08 <./Lights/light_2>,
09 \\.\\.\\.
10 ]
11 token lightList:cacheBehavior = "consumeAndContinue";
12 }
The lightList relationship encodes a set of lights, and the
lightList:cacheBehavior property provides fine-grained control over
how to use that cache. (See details below.)
The cache can be created by first invoking
ComputeLightList(ComputeModeIgnoreCache) to pre-compute the list and
then storing the result with UsdLuxLightListAPI::StoreLightList() .
To enable efficient retrieval of the cache, it should be stored on a
model hierarchy prim. Furthermore, note that while you can use a
UsdLuxLightListAPI bound to the pseudo-root prim to query the lights
(as in the example above) because it will perform a traversal over
descendants, you cannot store the cache back to the pseduo-root prim.
To consult the cached list, we invoke
ComputeLightList(ComputeModeConsultModelHierarchyCache):
.. code-block:: text
01 // Find and load all lights, using lightList cache where available
02 UsdLuxLightListAPI list(stage->GetPseudoRoot());
03 SdfPathSet lights = list.ComputeLightList(
04 UsdLuxLightListAPI::ComputeModeConsultModelHierarchyCache);
05 stage.LoadAndUnload(lights, SdfPathSet());
In this mode, ComputeLightList() will traverse the model hierarchy,
accumulating cached light lists.
Controlling Cache Behavior
==========================
The lightList:cacheBehavior property gives additional fine-grained
control over cache behavior:
- The fallback value,"ignore", indicates that the lightList should
be disregarded. This provides a way to invalidate cache entries. Note
that unless"ignore"is specified, a lightList with an empty list of
targets is considered a cache indicating that no lights are present.
- The value"consumeAndContinue"indicates that the cache should be
consulted to contribute lights to the scene, and that recursion should
continue down the model hierarchy in case additional lights are added
as descedants. This is the default value established when
StoreLightList() is invoked. This behavior allows the lights within a
large model, such as the BigSetWithLights example above, to be
published outside the payload, while also allowing referencing and
layering to add additional lights over that set.
- The value"consumeAndHalt"provides a way to terminate recursive
traversal of the scene for light discovery. The cache will be
consulted but no descendant prims will be examined.
Instancing
==========
Where instances are present, UsdLuxLightListAPI::ComputeLightList()
will return the instance-unique paths to any lights discovered within
those instances. Lights within a UsdGeomPointInstancer will not be
returned, however, since they cannot be referred to solely via paths.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdLuxTokens. So to set an attribute to the value"rightHanded", use
UsdLuxTokens->rightHanded as the value.
"""
result["LightListAPI"].ComputeMode.__doc__ = """
Runtime control over whether to consult stored lightList caches.
"""
result["LightListAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxLightListAPI on UsdPrim ``prim`` .
Equivalent to UsdLuxLightListAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxLightListAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxLightListAPI (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["LightListAPI"].GetLightListCacheBehaviorAttr.func_doc = """GetLightListCacheBehaviorAttr() -> Attribute
Controls how the lightList should be interpreted.
Valid values are:
- consumeAndHalt: The lightList should be consulted, and if it
exists, treated as a final authoritative statement of any lights that
exist at or below this prim, halting recursive discovery of lights.
- consumeAndContinue: The lightList should be consulted, but
recursive traversal over nameChildren should continue in case
additional lights are added by descendants.
- ignore: The lightList should be entirely ignored. This provides a
simple way to temporarily invalidate an existing cache. This is the
fallback behavior.
Declaration
``token lightList:cacheBehavior``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Allowed Values
consumeAndHalt, consumeAndContinue, ignore
"""
result["LightListAPI"].CreateLightListCacheBehaviorAttr.func_doc = """CreateLightListCacheBehaviorAttr(defaultValue, writeSparsely) -> Attribute
See GetLightListCacheBehaviorAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["LightListAPI"].GetLightListRel.func_doc = """GetLightListRel() -> Relationship
Relationship to lights in the scene.
"""
result["LightListAPI"].CreateLightListRel.func_doc = """CreateLightListRel() -> Relationship
See GetLightListRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["LightListAPI"].ComputeLightList.func_doc = """ComputeLightList(mode) -> SdfPathSet
Computes and returns the list of lights and light filters in the
stage, optionally consulting a cached result.
In ComputeModeIgnoreCache mode, caching is ignored, and this does a
prim traversal looking for prims that have a UsdLuxLightAPI or are of
type UsdLuxLightFilter.
In ComputeModeConsultModelHierarchyCache, this does a traversal only
of the model hierarchy. In this traversal, any lights that live as
model hierarchy prims are accumulated, as well as any paths stored in
lightList caches. The lightList:cacheBehavior attribute gives further
control over the cache behavior; see the class overview for details.
When instances are present, ComputeLightList(ComputeModeIgnoreCache)
will return the instance-uniqiue paths to any lights discovered within
those instances. Lights within a UsdGeomPointInstancer will not be
returned, however, since they cannot be referred to solely via paths.
Parameters
----------
mode : ComputeMode
"""
result["LightListAPI"].StoreLightList.func_doc = """StoreLightList(arg1) -> None
Store the given paths as the lightlist for this prim.
Paths that do not have this prim's path as a prefix will be silently
ignored. This will set the listList:cacheBehavior
to"consumeAndContinue".
Parameters
----------
arg1 : SdfPathSet
"""
result["LightListAPI"].InvalidateLightList.func_doc = """InvalidateLightList() -> None
Mark any stored lightlist as invalid, by setting the
lightList:cacheBehavior attribute to ignore.
"""
result["LightListAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["LightListAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> LightListAPI
Return a UsdLuxLightListAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxLightListAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["LightListAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["LightListAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> LightListAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"LightListAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdLuxLightListAPI object is returned upon success. An invalid
(or empty) UsdLuxLightListAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["LightListAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["ListAPI"].__doc__ = """
Deprecated
Use LightListAPI instead
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdLuxTokens. So to set an attribute to the value"rightHanded", use
UsdLuxTokens->rightHanded as the value.
"""
result["ListAPI"].ComputeMode.__doc__ = """
Runtime control over whether to consult stored lightList caches.
"""
result["ListAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxListAPI on UsdPrim ``prim`` .
Equivalent to UsdLuxListAPI::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxListAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxListAPI (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["ListAPI"].GetLightListCacheBehaviorAttr.func_doc = """GetLightListCacheBehaviorAttr() -> Attribute
Controls how the lightList should be interpreted.
Valid values are:
- consumeAndHalt: The lightList should be consulted, and if it
exists, treated as a final authoritative statement of any lights that
exist at or below this prim, halting recursive discovery of lights.
- consumeAndContinue: The lightList should be consulted, but
recursive traversal over nameChildren should continue in case
additional lights are added by descendants.
- ignore: The lightList should be entirely ignored. This provides a
simple way to temporarily invalidate an existing cache. This is the
fallback behavior.
Declaration
``token lightList:cacheBehavior``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Allowed Values
consumeAndHalt, consumeAndContinue, ignore
"""
result["ListAPI"].CreateLightListCacheBehaviorAttr.func_doc = """CreateLightListCacheBehaviorAttr(defaultValue, writeSparsely) -> Attribute
See GetLightListCacheBehaviorAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ListAPI"].GetLightListRel.func_doc = """GetLightListRel() -> Relationship
Relationship to lights in the scene.
"""
result["ListAPI"].CreateLightListRel.func_doc = """CreateLightListRel() -> Relationship
See GetLightListRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["ListAPI"].ComputeLightList.func_doc = """ComputeLightList(mode) -> SdfPathSet
Computes and returns the list of lights and light filters in the
stage, optionally consulting a cached result.
In ComputeModeIgnoreCache mode, caching is ignored, and this does a
prim traversal looking for prims that have a UsdLuxLightAPI or are of
type UsdLuxLightFilter.
In ComputeModeConsultModelHierarchyCache, this does a traversal only
of the model hierarchy. In this traversal, any lights that live as
model hierarchy prims are accumulated, as well as any paths stored in
lightList caches. The lightList:cacheBehavior attribute gives further
control over the cache behavior; see the class overview for details.
When instances are present, ComputeLightList(ComputeModeIgnoreCache)
will return the instance-uniqiue paths to any lights discovered within
those instances. Lights within a UsdGeomPointInstancer will not be
returned, however, since they cannot be referred to solely via paths.
Parameters
----------
mode : ComputeMode
"""
result["ListAPI"].StoreLightList.func_doc = """StoreLightList(arg1) -> None
Store the given paths as the lightlist for this prim.
Paths that do not have this prim's path as a prefix will be silently
ignored. This will set the listList:cacheBehavior
to"consumeAndContinue".
Parameters
----------
arg1 : SdfPathSet
"""
result["ListAPI"].InvalidateLightList.func_doc = """InvalidateLightList() -> None
Mark any stored lightlist as invalid, by setting the
lightList:cacheBehavior attribute to ignore.
"""
result["ListAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["ListAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> ListAPI
Return a UsdLuxListAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxListAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["ListAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["ListAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> ListAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"ListAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdLuxListAPI object is returned upon success. An invalid (or
empty) UsdLuxListAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["ListAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["MeshLightAPI"].__doc__ = """
This is the preferred API schema to apply to Mesh type prims when
adding light behaviors to a mesh. At its base, this API schema has the
built-in behavior of applying LightAPI to the mesh and overriding the
default materialSyncMode to allow the emission/glow of the bound
material to affect the color of the light. But, it additionally serves
as a hook for plugins to attach additional properties to"mesh
lights"through the creation of API schemas which are authored to auto-
apply to MeshLightAPI.
Auto applied API schemas
"""
result["MeshLightAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxMeshLightAPI on UsdPrim ``prim`` .
Equivalent to UsdLuxMeshLightAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxMeshLightAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxMeshLightAPI (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["MeshLightAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["MeshLightAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> MeshLightAPI
Return a UsdLuxMeshLightAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxMeshLightAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["MeshLightAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["MeshLightAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> MeshLightAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"MeshLightAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdLuxMeshLightAPI object is returned upon success. An invalid
(or empty) UsdLuxMeshLightAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["MeshLightAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["NonboundableLightBase"].__doc__ = """
Base class for intrinsic lights that are not boundable.
The primary purpose of this class is to provide a direct API to the
functions provided by LightAPI for concrete derived light types.
"""
result["NonboundableLightBase"].LightAPI.func_doc = """LightAPI() -> LightAPI
Contructs and returns a UsdLuxLightAPI object for this light.
"""
result["NonboundableLightBase"].GetIntensityAttr.func_doc = """GetIntensityAttr() -> Attribute
See UsdLuxLightAPI::GetIntensityAttr() .
"""
result["NonboundableLightBase"].CreateIntensityAttr.func_doc = """CreateIntensityAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateIntensityAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NonboundableLightBase"].GetExposureAttr.func_doc = """GetExposureAttr() -> Attribute
See UsdLuxLightAPI::GetExposureAttr() .
"""
result["NonboundableLightBase"].CreateExposureAttr.func_doc = """CreateExposureAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateExposureAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NonboundableLightBase"].GetDiffuseAttr.func_doc = """GetDiffuseAttr() -> Attribute
See UsdLuxLightAPI::GetDiffuseAttr() .
"""
result["NonboundableLightBase"].CreateDiffuseAttr.func_doc = """CreateDiffuseAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateDiffuseAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NonboundableLightBase"].GetSpecularAttr.func_doc = """GetSpecularAttr() -> Attribute
See UsdLuxLightAPI::GetSpecularAttr() .
"""
result["NonboundableLightBase"].CreateSpecularAttr.func_doc = """CreateSpecularAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateSpecularAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NonboundableLightBase"].GetNormalizeAttr.func_doc = """GetNormalizeAttr() -> Attribute
See UsdLuxLightAPI::GetNormalizeAttr() .
"""
result["NonboundableLightBase"].CreateNormalizeAttr.func_doc = """CreateNormalizeAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateNormalizeAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NonboundableLightBase"].GetColorAttr.func_doc = """GetColorAttr() -> Attribute
See UsdLuxLightAPI::GetColorAttr() .
"""
result["NonboundableLightBase"].CreateColorAttr.func_doc = """CreateColorAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateColorAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NonboundableLightBase"].GetEnableColorTemperatureAttr.func_doc = """GetEnableColorTemperatureAttr() -> Attribute
See UsdLuxLightAPI::GetEnableColorTemperatureAttr() .
"""
result["NonboundableLightBase"].CreateEnableColorTemperatureAttr.func_doc = """CreateEnableColorTemperatureAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateEnableColorTemperatureAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NonboundableLightBase"].GetColorTemperatureAttr.func_doc = """GetColorTemperatureAttr() -> Attribute
See UsdLuxLightAPI::GetColorTemperatureAttr() .
"""
result["NonboundableLightBase"].CreateColorTemperatureAttr.func_doc = """CreateColorTemperatureAttr(defaultValue, writeSparsely) -> Attribute
See UsdLuxLightAPI::CreateColorTemperatureAttr() .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NonboundableLightBase"].GetFiltersRel.func_doc = """GetFiltersRel() -> Relationship
See UsdLuxLightAPI::GetFiltersRel() .
"""
result["NonboundableLightBase"].CreateFiltersRel.func_doc = """CreateFiltersRel() -> Relationship
See UsdLuxLightAPI::CreateFiltersRel() .
"""
result["NonboundableLightBase"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxNonboundableLightBase on UsdPrim ``prim`` .
Equivalent to UsdLuxNonboundableLightBase::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxNonboundableLightBase on the prim held by
``schemaObj`` .
Should be preferred over UsdLuxNonboundableLightBase
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["NonboundableLightBase"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["NonboundableLightBase"].Get.func_doc = """**classmethod** Get(stage, path) -> NonboundableLightBase
Return a UsdLuxNonboundableLightBase holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxNonboundableLightBase(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["NonboundableLightBase"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["PluginLight"].__doc__ = """
Light that provides properties that allow it to identify an external
SdrShadingNode definition, through UsdShadeNodeDefAPI, that can be
provided to render delegates without the need to provide a schema
definition for the light's type.
Plugin Lights and Light Filters
"""
result["PluginLight"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxPluginLight on UsdPrim ``prim`` .
Equivalent to UsdLuxPluginLight::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxPluginLight on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxPluginLight (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["PluginLight"].GetNodeDefAPI.func_doc = """GetNodeDefAPI() -> NodeDefAPI
Convenience method for accessing the UsdShadeNodeDefAPI functionality
for this prim.
One can also construct a UsdShadeNodeDefAPI directly from a UsdPrim.
"""
result["PluginLight"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["PluginLight"].Get.func_doc = """**classmethod** Get(stage, path) -> PluginLight
Return a UsdLuxPluginLight holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxPluginLight(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["PluginLight"].Define.func_doc = """**classmethod** Define(stage, path) -> PluginLight
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["PluginLight"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["PluginLightFilter"].__doc__ = """
Light filter that provides properties that allow it to identify an
external SdrShadingNode definition, through UsdShadeNodeDefAPI, that
can be provided to render delegates without the need to provide a
schema definition for the light filter's type.
Plugin Lights and Light Filters
"""
result["PluginLightFilter"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxPluginLightFilter on UsdPrim ``prim`` .
Equivalent to UsdLuxPluginLightFilter::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxPluginLightFilter on the prim held by ``schemaObj``
.
Should be preferred over UsdLuxPluginLightFilter
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["PluginLightFilter"].GetNodeDefAPI.func_doc = """GetNodeDefAPI() -> NodeDefAPI
Convenience method for accessing the UsdShadeNodeDefAPI functionality
for this prim.
One can also construct a UsdShadeNodeDefAPI directly from a UsdPrim.
"""
result["PluginLightFilter"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["PluginLightFilter"].Get.func_doc = """**classmethod** Get(stage, path) -> PluginLightFilter
Return a UsdLuxPluginLightFilter holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxPluginLightFilter(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["PluginLightFilter"].Define.func_doc = """**classmethod** Define(stage, path) -> PluginLightFilter
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["PluginLightFilter"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["PortalLight"].__doc__ = """
A rectangular portal in the local XY plane that guides sampling of a
dome light. Transmits light in the -Z direction. The rectangle is 1
unit in length.
"""
result["PortalLight"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxPortalLight on UsdPrim ``prim`` .
Equivalent to UsdLuxPortalLight::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxPortalLight on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxPortalLight (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["PortalLight"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["PortalLight"].Get.func_doc = """**classmethod** Get(stage, path) -> PortalLight
Return a UsdLuxPortalLight holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxPortalLight(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["PortalLight"].Define.func_doc = """**classmethod** Define(stage, path) -> PortalLight
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["PortalLight"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["RectLight"].__doc__ = """
Light emitted from one side of a rectangle. The rectangle is centered
in the XY plane and emits light along the -Z axis. The rectangle is 1
unit in length in the X and Y axis. In the default position, a texture
file's min coordinates should be at (+X, +Y) and max coordinates at
(-X, -Y).
"""
result["RectLight"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxRectLight on UsdPrim ``prim`` .
Equivalent to UsdLuxRectLight::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxRectLight on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxRectLight (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["RectLight"].GetWidthAttr.func_doc = """GetWidthAttr() -> Attribute
Width of the rectangle, in the local X axis.
Declaration
``float inputs:width = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["RectLight"].CreateWidthAttr.func_doc = """CreateWidthAttr(defaultValue, writeSparsely) -> Attribute
See GetWidthAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RectLight"].GetHeightAttr.func_doc = """GetHeightAttr() -> Attribute
Height of the rectangle, in the local Y axis.
Declaration
``float inputs:height = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["RectLight"].CreateHeightAttr.func_doc = """CreateHeightAttr(defaultValue, writeSparsely) -> Attribute
See GetHeightAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RectLight"].GetTextureFileAttr.func_doc = """GetTextureFileAttr() -> Attribute
A color texture to use on the rectangle.
Declaration
``asset inputs:texture:file``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
"""
result["RectLight"].CreateTextureFileAttr.func_doc = """CreateTextureFileAttr(defaultValue, writeSparsely) -> Attribute
See GetTextureFileAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["RectLight"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["RectLight"].Get.func_doc = """**classmethod** Get(stage, path) -> RectLight
Return a UsdLuxRectLight holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxRectLight(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["RectLight"].Define.func_doc = """**classmethod** Define(stage, path) -> RectLight
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["RectLight"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["ShadowAPI"].__doc__ = """
Controls to refine a light's shadow behavior. These are non-physical
controls that are valuable for visual lighting work.
"""
result["ShadowAPI"].__init__.func_doc = """__init__(connectable)
Constructor that takes a ConnectableAPI object.
Allow implicit conversion of UsdShadeConnectableAPI to
UsdLuxShadowAPI.
Parameters
----------
connectable : ConnectableAPI
----------------------------------------------------------------------
__init__(prim)
Construct a UsdLuxShadowAPI on UsdPrim ``prim`` .
Equivalent to UsdLuxShadowAPI::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxShadowAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxShadowAPI (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["ShadowAPI"].ConnectableAPI.func_doc = """ConnectableAPI() -> ConnectableAPI
Contructs and returns a UsdShadeConnectableAPI object with this shadow
API prim.
Note that a valid UsdLuxShadowAPI will only return a valid
UsdShadeConnectableAPI if the its prim's Typed schema type is actually
connectable.
"""
result["ShadowAPI"].CreateOutput.func_doc = """CreateOutput(name, typeName) -> Output
Create an output which can either have a value or can be connected.
The attribute representing the output is created in
the"outputs:"namespace. Outputs on a shadow API cannot be connected,
as their value is assumed to be computed externally.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["ShadowAPI"].GetOutput.func_doc = """GetOutput(name) -> Output
Return the requested output if it exists.
Parameters
----------
name : str
"""
result["ShadowAPI"].GetOutputs.func_doc = """GetOutputs(onlyAuthored) -> list[Output]
Outputs are represented by attributes in the"outputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["ShadowAPI"].CreateInput.func_doc = """CreateInput(name, typeName) -> Input
Create an input which can either have a value or can be connected.
The attribute representing the input is created in
the"inputs:"namespace. Inputs on shadow API are connectable.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["ShadowAPI"].GetInput.func_doc = """GetInput(name) -> Input
Return the requested input if it exists.
Parameters
----------
name : str
"""
result["ShadowAPI"].GetInputs.func_doc = """GetInputs(onlyAuthored) -> list[Input]
Inputs are represented by attributes in the"inputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["ShadowAPI"].GetShadowEnableAttr.func_doc = """GetShadowEnableAttr() -> Attribute
Enables shadows to be cast by this light.
Declaration
``bool inputs:shadow:enable = 1``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["ShadowAPI"].CreateShadowEnableAttr.func_doc = """CreateShadowEnableAttr(defaultValue, writeSparsely) -> Attribute
See GetShadowEnableAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShadowAPI"].GetShadowColorAttr.func_doc = """GetShadowColorAttr() -> Attribute
The color of shadows cast by the light.
This is a non-physical control. The default is to cast black shadows.
Declaration
``color3f inputs:shadow:color = (0, 0, 0)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Color3f
"""
result["ShadowAPI"].CreateShadowColorAttr.func_doc = """CreateShadowColorAttr(defaultValue, writeSparsely) -> Attribute
See GetShadowColorAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShadowAPI"].GetShadowDistanceAttr.func_doc = """GetShadowDistanceAttr() -> Attribute
The maximum distance shadows are cast.
The default value (-1) indicates no limit.
Declaration
``float inputs:shadow:distance = -1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["ShadowAPI"].CreateShadowDistanceAttr.func_doc = """CreateShadowDistanceAttr(defaultValue, writeSparsely) -> Attribute
See GetShadowDistanceAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShadowAPI"].GetShadowFalloffAttr.func_doc = """GetShadowFalloffAttr() -> Attribute
The near distance at which shadow falloff begins.
The default value (-1) indicates no falloff.
Declaration
``float inputs:shadow:falloff = -1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["ShadowAPI"].CreateShadowFalloffAttr.func_doc = """CreateShadowFalloffAttr(defaultValue, writeSparsely) -> Attribute
See GetShadowFalloffAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShadowAPI"].GetShadowFalloffGammaAttr.func_doc = """GetShadowFalloffGammaAttr() -> Attribute
A gamma (i.e., exponential) control over shadow strength with linear
distance within the falloff zone.
This requires the use of shadowDistance and shadowFalloff.
Declaration
``float inputs:shadow:falloffGamma = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["ShadowAPI"].CreateShadowFalloffGammaAttr.func_doc = """CreateShadowFalloffGammaAttr(defaultValue, writeSparsely) -> Attribute
See GetShadowFalloffGammaAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShadowAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["ShadowAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> ShadowAPI
Return a UsdLuxShadowAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxShadowAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["ShadowAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["ShadowAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> ShadowAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"ShadowAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdLuxShadowAPI object is returned upon success. An invalid
(or empty) UsdLuxShadowAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["ShadowAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["ShapingAPI"].__doc__ = """
Controls for shaping a light's emission.
"""
result["ShapingAPI"].__init__.func_doc = """__init__(connectable)
Constructor that takes a ConnectableAPI object.
Allow implicit conversion of UsdShadeConnectableAPI to
UsdLuxShapingAPI.
Parameters
----------
connectable : ConnectableAPI
----------------------------------------------------------------------
__init__(prim)
Construct a UsdLuxShapingAPI on UsdPrim ``prim`` .
Equivalent to UsdLuxShapingAPI::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxShapingAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxShapingAPI (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["ShapingAPI"].ConnectableAPI.func_doc = """ConnectableAPI() -> ConnectableAPI
Contructs and returns a UsdShadeConnectableAPI object with this
shaping API prim.
Note that a valid UsdLuxShapingAPI will only return a valid
UsdShadeConnectableAPI if the its prim's Typed schema type is actually
connectable.
"""
result["ShapingAPI"].CreateOutput.func_doc = """CreateOutput(name, typeName) -> Output
Create an output which can either have a value or can be connected.
The attribute representing the output is created in
the"outputs:"namespace. Outputs on a shaping API cannot be connected,
as their value is assumed to be computed externally.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["ShapingAPI"].GetOutput.func_doc = """GetOutput(name) -> Output
Return the requested output if it exists.
Parameters
----------
name : str
"""
result["ShapingAPI"].GetOutputs.func_doc = """GetOutputs(onlyAuthored) -> list[Output]
Outputs are represented by attributes in the"outputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["ShapingAPI"].CreateInput.func_doc = """CreateInput(name, typeName) -> Input
Create an input which can either have a value or can be connected.
The attribute representing the input is created in
the"inputs:"namespace. Inputs on shaping API are connectable.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["ShapingAPI"].GetInput.func_doc = """GetInput(name) -> Input
Return the requested input if it exists.
Parameters
----------
name : str
"""
result["ShapingAPI"].GetInputs.func_doc = """GetInputs(onlyAuthored) -> list[Input]
Inputs are represented by attributes in the"inputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["ShapingAPI"].GetShapingFocusAttr.func_doc = """GetShapingFocusAttr() -> Attribute
A control to shape the spread of light.
Higher focus values pull light towards the center and narrow the
spread. Implemented as an off-axis cosine power exponent. TODO:
clarify semantics
Declaration
``float inputs:shaping:focus = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["ShapingAPI"].CreateShapingFocusAttr.func_doc = """CreateShapingFocusAttr(defaultValue, writeSparsely) -> Attribute
See GetShapingFocusAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShapingAPI"].GetShapingFocusTintAttr.func_doc = """GetShapingFocusTintAttr() -> Attribute
Off-axis color tint.
This tints the emission in the falloff region. The default tint is
black. TODO: clarify semantics
Declaration
``color3f inputs:shaping:focusTint = (0, 0, 0)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Color3f
"""
result["ShapingAPI"].CreateShapingFocusTintAttr.func_doc = """CreateShapingFocusTintAttr(defaultValue, writeSparsely) -> Attribute
See GetShapingFocusTintAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShapingAPI"].GetShapingConeAngleAttr.func_doc = """GetShapingConeAngleAttr() -> Attribute
Angular limit off the primary axis to restrict the light spread.
Declaration
``float inputs:shaping:cone:angle = 90``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["ShapingAPI"].CreateShapingConeAngleAttr.func_doc = """CreateShapingConeAngleAttr(defaultValue, writeSparsely) -> Attribute
See GetShapingConeAngleAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShapingAPI"].GetShapingConeSoftnessAttr.func_doc = """GetShapingConeSoftnessAttr() -> Attribute
Controls the cutoff softness for cone angle.
TODO: clarify semantics
Declaration
``float inputs:shaping:cone:softness = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["ShapingAPI"].CreateShapingConeSoftnessAttr.func_doc = """CreateShapingConeSoftnessAttr(defaultValue, writeSparsely) -> Attribute
See GetShapingConeSoftnessAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShapingAPI"].GetShapingIesFileAttr.func_doc = """GetShapingIesFileAttr() -> Attribute
An IES (Illumination Engineering Society) light profile describing the
angular distribution of light.
Declaration
``asset inputs:shaping:ies:file``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
"""
result["ShapingAPI"].CreateShapingIesFileAttr.func_doc = """CreateShapingIesFileAttr(defaultValue, writeSparsely) -> Attribute
See GetShapingIesFileAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShapingAPI"].GetShapingIesAngleScaleAttr.func_doc = """GetShapingIesAngleScaleAttr() -> Attribute
Rescales the angular distribution of the IES profile.
TODO: clarify semantics
Declaration
``float inputs:shaping:ies:angleScale = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["ShapingAPI"].CreateShapingIesAngleScaleAttr.func_doc = """CreateShapingIesAngleScaleAttr(defaultValue, writeSparsely) -> Attribute
See GetShapingIesAngleScaleAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShapingAPI"].GetShapingIesNormalizeAttr.func_doc = """GetShapingIesNormalizeAttr() -> Attribute
Normalizes the IES profile so that it affects the shaping of the light
while preserving the overall energy output.
Declaration
``bool inputs:shaping:ies:normalize = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["ShapingAPI"].CreateShapingIesNormalizeAttr.func_doc = """CreateShapingIesNormalizeAttr(defaultValue, writeSparsely) -> Attribute
See GetShapingIesNormalizeAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ShapingAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["ShapingAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> ShapingAPI
Return a UsdLuxShapingAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxShapingAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["ShapingAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["ShapingAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> ShapingAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"ShapingAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdLuxShapingAPI object is returned upon success. An invalid
(or empty) UsdLuxShapingAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["ShapingAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["SphereLight"].__doc__ = """
Light emitted outward from a sphere.
"""
result["SphereLight"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxSphereLight on UsdPrim ``prim`` .
Equivalent to UsdLuxSphereLight::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxSphereLight on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxSphereLight (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["SphereLight"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute
Radius of the sphere.
Declaration
``float inputs:radius = 0.5``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["SphereLight"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute
See GetRadiusAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SphereLight"].GetTreatAsPointAttr.func_doc = """GetTreatAsPointAttr() -> Attribute
A hint that this light can be treated as a'point'light (effectively, a
zero-radius sphere) by renderers that benefit from non-area lighting.
Renderers that only support area lights can disregard this.
Declaration
``bool treatAsPoint = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
"""
result["SphereLight"].CreateTreatAsPointAttr.func_doc = """CreateTreatAsPointAttr(defaultValue, writeSparsely) -> Attribute
See GetTreatAsPointAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SphereLight"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["SphereLight"].Get.func_doc = """**classmethod** Get(stage, path) -> SphereLight
Return a UsdLuxSphereLight holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxSphereLight(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["SphereLight"].Define.func_doc = """**classmethod** Define(stage, path) -> SphereLight
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["SphereLight"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["VolumeLightAPI"].__doc__ = """
This is the preferred API schema to apply to Volume type prims when
adding light behaviors to a volume. At its base, this API schema has
the built-in behavior of applying LightAPI to the volume and
overriding the default materialSyncMode to allow the emission/glow of
the bound material to affect the color of the light. But, it
additionally serves as a hook for plugins to attach additional
properties to"volume lights"through the creation of API schemas which
are authored to auto-apply to VolumeLightAPI.
Auto applied API schemas
"""
result["VolumeLightAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdLuxVolumeLightAPI on UsdPrim ``prim`` .
Equivalent to UsdLuxVolumeLightAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdLuxVolumeLightAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdLuxVolumeLightAPI (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["VolumeLightAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["VolumeLightAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> VolumeLightAPI
Return a UsdLuxVolumeLightAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdLuxVolumeLightAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["VolumeLightAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["VolumeLightAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> VolumeLightAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"VolumeLightAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdLuxVolumeLightAPI object is returned upon success. An
invalid (or empty) UsdLuxVolumeLightAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["VolumeLightAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
""" | 131,321 | Python | 21.171535 | 165 | 0.726403 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Gf/__DOC.py | def Execute(result):
result["BBox3d"].__init__.func_doc = """__init__()
The default constructor leaves the box empty, the transformation
matrix identity, and the zero-area primitives flag" ``false`` .
----------------------------------------------------------------------
__init__(rhs)
Copy constructor.
Parameters
----------
rhs : BBox3d
----------------------------------------------------------------------
__init__(box)
This constructor takes a box and sets the matrix to identity.
Parameters
----------
box : Range3d
----------------------------------------------------------------------
__init__(box, matrix)
This constructor takes a box and a transformation matrix.
Parameters
----------
box : Range3d
matrix : Matrix4d
"""
result["BBox3d"].Set.func_doc = """Set(box, matrix) -> None
Sets the axis-aligned box and transformation matrix.
Parameters
----------
box : Range3d
matrix : Matrix4d
"""
result["BBox3d"].SetMatrix.func_doc = """SetMatrix(matrix) -> None
Sets the transformation matrix only.
The axis-aligned box is not modified.
Parameters
----------
matrix : Matrix4d
"""
result["BBox3d"].SetRange.func_doc = """SetRange(box) -> None
Sets the range of the axis-aligned box only.
The transformation matrix is not modified.
Parameters
----------
box : Range3d
"""
result["BBox3d"].GetRange.func_doc = """GetRange() -> Range3d
Returns the range of the axis-aligned untransformed box.
"""
result["BBox3d"].GetBox.func_doc = """GetBox() -> Range3d
Returns the range of the axis-aligned untransformed box.
This synonym of ``GetRange`` exists for compatibility purposes.
"""
result["BBox3d"].GetMatrix.func_doc = """GetMatrix() -> Matrix4d
Returns the transformation matrix.
"""
result["BBox3d"].GetInverseMatrix.func_doc = """GetInverseMatrix() -> Matrix4d
Returns the inverse of the transformation matrix.
This will be the identity matrix if the transformation matrix is not
invertible.
"""
result["BBox3d"].SetHasZeroAreaPrimitives.func_doc = """SetHasZeroAreaPrimitives(hasThem) -> None
Sets the zero-area primitives flag to the given value.
Parameters
----------
hasThem : bool
"""
result["BBox3d"].HasZeroAreaPrimitives.func_doc = """HasZeroAreaPrimitives() -> bool
Returns the current state of the zero-area primitives flag".
"""
result["BBox3d"].GetVolume.func_doc = """GetVolume() -> float
Returns the volume of the box (0 for an empty box).
"""
result["BBox3d"].Transform.func_doc = """Transform(matrix) -> None
Transforms the bounding box by the given matrix, which is assumed to
be a global transformation to apply to the box.
Therefore, this just post-multiplies the box's matrix by ``matrix`` .
Parameters
----------
matrix : Matrix4d
"""
result["BBox3d"].ComputeAlignedRange.func_doc = """ComputeAlignedRange() -> Range3d
Returns the axis-aligned range (as a ``GfRange3d`` ) that results from
applying the transformation matrix to the wxis-aligned box and
aligning the result.
"""
result["BBox3d"].ComputeAlignedBox.func_doc = """ComputeAlignedBox() -> Range3d
Returns the axis-aligned range (as a ``GfRange3d`` ) that results from
applying the transformation matrix to the axis-aligned box and
aligning the result.
This synonym for ``ComputeAlignedRange`` exists for compatibility
purposes.
"""
result["BBox3d"].ComputeCentroid.func_doc = """ComputeCentroid() -> Vec3d
Returns the centroid of the bounding box.
The centroid is computed as the transformed centroid of the range.
"""
result["BBox3d"].Combine.func_doc = """**classmethod** Combine(b1, b2) -> BBox3d
Combines two bboxes, returning a new bbox that contains both.
This uses the coordinate space of one of the two original boxes as the
space of the result; it uses the one that produces whe smaller of the
two resulting boxes.
Parameters
----------
b1 : BBox3d
b2 : BBox3d
"""
result["Camera"].__doc__ = """
Object-based representation of a camera.
This class provides a thin wrapper on the camera data model, with a
small number of computations.
"""
result["Camera"].SetPerspectiveFromAspectRatioAndFieldOfView.func_doc = """SetPerspectiveFromAspectRatioAndFieldOfView(aspectRatio, fieldOfView, direction, horizontalAperture) -> None
Sets the frustum to be projective with the given ``aspectRatio`` and
horizontal, respectively, vertical field of view ``fieldOfView``
(similar to gluPerspective when direction = FOVVertical).
Do not pass values for ``horionztalAperture`` unless you care about
DepthOfField.
Parameters
----------
aspectRatio : float
fieldOfView : float
direction : FOVDirection
horizontalAperture : float
"""
result["Camera"].SetOrthographicFromAspectRatioAndSize.func_doc = """SetOrthographicFromAspectRatioAndSize(aspectRatio, orthographicSize, direction) -> None
Sets the frustum to be orthographic such that it has the given
``aspectRatio`` and such that the orthographic width, respectively,
orthographic height (in cm) is equal to ``orthographicSize``
(depending on direction).
Parameters
----------
aspectRatio : float
orthographicSize : float
direction : FOVDirection
"""
result["Camera"].SetFromViewAndProjectionMatrix.func_doc = """SetFromViewAndProjectionMatrix(viewMatrix, projMatix, focalLength) -> None
Sets the camera from a view and projection matrix.
Note that the projection matrix does only determine the ratio of
aperture to focal length, so there is a choice which defaults to 50mm
(or more accurately, 50 tenths of a world unit).
Parameters
----------
viewMatrix : Matrix4d
projMatix : Matrix4d
focalLength : float
"""
result["Camera"].Projection.__doc__ = """
Projection type.
"""
result["Camera"].FOVDirection.__doc__ = """
Direction used for Field of View or orthographic size.
"""
result["Camera"].__init__.func_doc = """__init__(transform, projection, horizontalAperture, verticalAperture, horizontalApertureOffset, verticalApertureOffset, focalLength, clippingRange, clippingPlanes, fStop, focusDistance)
Parameters
----------
transform : Matrix4d
projection : Projection
horizontalAperture : float
verticalAperture : float
horizontalApertureOffset : float
verticalApertureOffset : float
focalLength : float
clippingRange : Range1f
clippingPlanes : list[Vec4f]
fStop : float
focusDistance : float
"""
result["Camera"].GetFieldOfView.func_doc = """GetFieldOfView(direction) -> float
Returns the horizontal or vertical field of view in degrees.
Parameters
----------
direction : FOVDirection
"""
result["DualQuatd"].__doc__ = """
Basic type: a real part quaternion and a dual part quaternion.
This class represents a generalized dual quaternion that has a real
part and a dual part quaternions. Dual quaternions are used to
represent a combination of rotation and translation.
References:
https://www.cs.utah.edu/~ladislav/kavan06dual/kavan06dual.pdf
http://web.cs.iastate.edu/~cs577/handouts/dual-quaternion.pdf
"""
result["DualQuatd"].__init__.func_doc = """__init__()
The default constructor leaves the dual quaternion undefined.
----------------------------------------------------------------------
__init__(realVal)
Initialize the real part to ``realVal`` and the imaginary part to zero
quaternion.
Since quaternions typically must be normalized, reasonable values for
``realVal`` are -1, 0, or 1. Other values are legal but are likely to
be meaningless.
Parameters
----------
realVal : float
----------------------------------------------------------------------
__init__(real)
Initialize the real part to ``real`` quaternion and the imaginary part
to zero quaternion.
Parameters
----------
real : Quatd
----------------------------------------------------------------------
__init__(real, dual)
This constructor initializes the real and dual parts.
Parameters
----------
real : Quatd
dual : Quatd
----------------------------------------------------------------------
__init__(rotation, translation)
This constructor initializes from a rotation and a translation
components.
Parameters
----------
rotation : Quatd
translation : Vec3d
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfDualQuatf.
Parameters
----------
other : DualQuatf
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfDualQuath.
Parameters
----------
other : DualQuath
"""
result["DualQuatd"].SetReal.func_doc = """SetReal(real) -> None
Sets the real part of the dual quaternion.
Parameters
----------
real : Quatd
"""
result["DualQuatd"].SetDual.func_doc = """SetDual(dual) -> None
Sets the dual part of the dual quaternion.
Parameters
----------
dual : Quatd
"""
result["DualQuatd"].GetReal.func_doc = """GetReal() -> Quatd
Returns the real part of the dual quaternion.
"""
result["DualQuatd"].GetDual.func_doc = """GetDual() -> Quatd
Returns the dual part of the dual quaternion.
"""
result["DualQuatd"].GetLength.func_doc = """GetLength() -> tuple[float, float]
Returns geometric length of this dual quaternion.
"""
result["DualQuatd"].GetNormalized.func_doc = """GetNormalized(eps) -> DualQuatd
Returns a normalized (unit-length) version of this dual quaternion.
If the length of this dual quaternion is smaller than ``eps`` , this
returns the identity dual quaternion.
Parameters
----------
eps : float
"""
result["DualQuatd"].Normalize.func_doc = """Normalize(eps) -> tuple[float, float]
Normalizes this dual quaternion in place.
Normalizes this dual quaternion in place to unit length, returning the
length before normalization. If the length of this dual quaternion is
smaller than ``eps`` , this sets the dual quaternion to identity.
Parameters
----------
eps : float
"""
result["DualQuatd"].GetConjugate.func_doc = """GetConjugate() -> DualQuatd
Returns the conjugate of this dual quaternion.
"""
result["DualQuatd"].GetInverse.func_doc = """GetInverse() -> DualQuatd
Returns the inverse of this dual quaternion.
"""
result["DualQuatd"].SetTranslation.func_doc = """SetTranslation(translation) -> None
Set the translation component of this dual quaternion.
Parameters
----------
translation : Vec3d
"""
result["DualQuatd"].GetTranslation.func_doc = """GetTranslation() -> Vec3d
Get the translation component of this dual quaternion.
"""
result["DualQuatd"].Transform.func_doc = """Transform(vec) -> Vec3d
Transforms the row vector *vec* by the dual quaternion.
Parameters
----------
vec : Vec3d
"""
result["DualQuatd"].GetZero.func_doc = """**classmethod** GetZero() -> DualQuatd
Returns the zero dual quaternion, which has a real part of (0,0,0,0)
and a dual part of (0,0,0,0).
"""
result["DualQuatd"].GetIdentity.func_doc = """**classmethod** GetIdentity() -> DualQuatd
Returns the identity dual quaternion, which has a real part of
(1,0,0,0) and a dual part of (0,0,0,0).
"""
result["DualQuatf"].__doc__ = """
Basic type: a real part quaternion and a dual part quaternion.
This class represents a generalized dual quaternion that has a real
part and a dual part quaternions. Dual quaternions are used to
represent a combination of rotation and translation.
References:
https://www.cs.utah.edu/~ladislav/kavan06dual/kavan06dual.pdf
http://web.cs.iastate.edu/~cs577/handouts/dual-quaternion.pdf
"""
result["DualQuatf"].__init__.func_doc = """__init__()
The default constructor leaves the dual quaternion undefined.
----------------------------------------------------------------------
__init__(realVal)
Initialize the real part to ``realVal`` and the imaginary part to zero
quaternion.
Since quaternions typically must be normalized, reasonable values for
``realVal`` are -1, 0, or 1. Other values are legal but are likely to
be meaningless.
Parameters
----------
realVal : float
----------------------------------------------------------------------
__init__(real)
Initialize the real part to ``real`` quaternion and the imaginary part
to zero quaternion.
Parameters
----------
real : Quatf
----------------------------------------------------------------------
__init__(real, dual)
This constructor initializes the real and dual parts.
Parameters
----------
real : Quatf
dual : Quatf
----------------------------------------------------------------------
__init__(rotation, translation)
This constructor initializes from a rotation and a translation
components.
Parameters
----------
rotation : Quatf
translation : Vec3f
----------------------------------------------------------------------
__init__(other)
Construct from GfDualQuatd.
Parameters
----------
other : DualQuatd
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfDualQuath.
Parameters
----------
other : DualQuath
"""
result["DualQuatf"].SetReal.func_doc = """SetReal(real) -> None
Sets the real part of the dual quaternion.
Parameters
----------
real : Quatf
"""
result["DualQuatf"].SetDual.func_doc = """SetDual(dual) -> None
Sets the dual part of the dual quaternion.
Parameters
----------
dual : Quatf
"""
result["DualQuatf"].GetReal.func_doc = """GetReal() -> Quatf
Returns the real part of the dual quaternion.
"""
result["DualQuatf"].GetDual.func_doc = """GetDual() -> Quatf
Returns the dual part of the dual quaternion.
"""
result["DualQuatf"].GetLength.func_doc = """GetLength() -> tuple[float, float]
Returns geometric length of this dual quaternion.
"""
result["DualQuatf"].GetNormalized.func_doc = """GetNormalized(eps) -> DualQuatf
Returns a normalized (unit-length) version of this dual quaternion.
If the length of this dual quaternion is smaller than ``eps`` , this
returns the identity dual quaternion.
Parameters
----------
eps : float
"""
result["DualQuatf"].Normalize.func_doc = """Normalize(eps) -> tuple[float, float]
Normalizes this dual quaternion in place.
Normalizes this dual quaternion in place to unit length, returning the
length before normalization. If the length of this dual quaternion is
smaller than ``eps`` , this sets the dual quaternion to identity.
Parameters
----------
eps : float
"""
result["DualQuatf"].GetConjugate.func_doc = """GetConjugate() -> DualQuatf
Returns the conjugate of this dual quaternion.
"""
result["DualQuatf"].GetInverse.func_doc = """GetInverse() -> DualQuatf
Returns the inverse of this dual quaternion.
"""
result["DualQuatf"].SetTranslation.func_doc = """SetTranslation(translation) -> None
Set the translation component of this dual quaternion.
Parameters
----------
translation : Vec3f
"""
result["DualQuatf"].GetTranslation.func_doc = """GetTranslation() -> Vec3f
Get the translation component of this dual quaternion.
"""
result["DualQuatf"].Transform.func_doc = """Transform(vec) -> Vec3f
Transforms the row vector *vec* by the dual quaternion.
Parameters
----------
vec : Vec3f
"""
result["DualQuatf"].GetZero.func_doc = """**classmethod** GetZero() -> DualQuatf
Returns the zero dual quaternion, which has a real part of (0,0,0,0)
and a dual part of (0,0,0,0).
"""
result["DualQuatf"].GetIdentity.func_doc = """**classmethod** GetIdentity() -> DualQuatf
Returns the identity dual quaternion, which has a real part of
(1,0,0,0) and a dual part of (0,0,0,0).
"""
result["DualQuath"].__doc__ = """
Basic type: a real part quaternion and a dual part quaternion.
This class represents a generalized dual quaternion that has a real
part and a dual part quaternions. Dual quaternions are used to
represent a combination of rotation and translation.
References:
https://www.cs.utah.edu/~ladislav/kavan06dual/kavan06dual.pdf
http://web.cs.iastate.edu/~cs577/handouts/dual-quaternion.pdf
"""
result["DualQuath"].__init__.func_doc = """__init__()
The default constructor leaves the dual quaternion undefined.
----------------------------------------------------------------------
__init__(realVal)
Initialize the real part to ``realVal`` and the imaginary part to zero
quaternion.
Since quaternions typically must be normalized, reasonable values for
``realVal`` are -1, 0, or 1. Other values are legal but are likely to
be meaningless.
Parameters
----------
realVal : GfHalf
----------------------------------------------------------------------
__init__(real)
Initialize the real part to ``real`` quaternion and the imaginary part
to zero quaternion.
Parameters
----------
real : Quath
----------------------------------------------------------------------
__init__(real, dual)
This constructor initializes the real and dual parts.
Parameters
----------
real : Quath
dual : Quath
----------------------------------------------------------------------
__init__(rotation, translation)
This constructor initializes from a rotation and a translation
components.
Parameters
----------
rotation : Quath
translation : Vec3h
----------------------------------------------------------------------
__init__(other)
Construct from GfDualQuatd.
Parameters
----------
other : DualQuatd
----------------------------------------------------------------------
__init__(other)
Construct from GfDualQuatf.
Parameters
----------
other : DualQuatf
"""
result["DualQuath"].SetReal.func_doc = """SetReal(real) -> None
Sets the real part of the dual quaternion.
Parameters
----------
real : Quath
"""
result["DualQuath"].SetDual.func_doc = """SetDual(dual) -> None
Sets the dual part of the dual quaternion.
Parameters
----------
dual : Quath
"""
result["DualQuath"].GetReal.func_doc = """GetReal() -> Quath
Returns the real part of the dual quaternion.
"""
result["DualQuath"].GetDual.func_doc = """GetDual() -> Quath
Returns the dual part of the dual quaternion.
"""
result["DualQuath"].GetLength.func_doc = """GetLength() -> tuple[GfHalf, GfHalf]
Returns geometric length of this dual quaternion.
"""
result["DualQuath"].GetNormalized.func_doc = """GetNormalized(eps) -> DualQuath
Returns a normalized (unit-length) version of this dual quaternion.
If the length of this dual quaternion is smaller than ``eps`` , this
returns the identity dual quaternion.
Parameters
----------
eps : GfHalf
"""
result["DualQuath"].Normalize.func_doc = """Normalize(eps) -> tuple[GfHalf, GfHalf]
Normalizes this dual quaternion in place.
Normalizes this dual quaternion in place to unit length, returning the
length before normalization. If the length of this dual quaternion is
smaller than ``eps`` , this sets the dual quaternion to identity.
Parameters
----------
eps : GfHalf
"""
result["DualQuath"].GetConjugate.func_doc = """GetConjugate() -> DualQuath
Returns the conjugate of this dual quaternion.
"""
result["DualQuath"].GetInverse.func_doc = """GetInverse() -> DualQuath
Returns the inverse of this dual quaternion.
"""
result["DualQuath"].SetTranslation.func_doc = """SetTranslation(translation) -> None
Set the translation component of this dual quaternion.
Parameters
----------
translation : Vec3h
"""
result["DualQuath"].GetTranslation.func_doc = """GetTranslation() -> Vec3h
Get the translation component of this dual quaternion.
"""
result["DualQuath"].Transform.func_doc = """Transform(vec) -> Vec3h
Transforms the row vector *vec* by the dual quaternion.
Parameters
----------
vec : Vec3h
"""
result["DualQuath"].GetZero.func_doc = """**classmethod** GetZero() -> DualQuath
Returns the zero dual quaternion, which has a real part of (0,0,0,0)
and a dual part of (0,0,0,0).
"""
result["DualQuath"].GetIdentity.func_doc = """**classmethod** GetIdentity() -> DualQuath
Returns the identity dual quaternion, which has a real part of
(1,0,0,0) and a dual part of (0,0,0,0).
"""
result["Frustum"].SetPosition.func_doc = """SetPosition(position) -> None
Sets the position of the frustum in world space.
Parameters
----------
position : Vec3d
"""
result["Frustum"].GetPosition.func_doc = """GetPosition() -> Vec3d
Returns the position of the frustum in world space.
"""
result["Frustum"].SetRotation.func_doc = """SetRotation(rotation) -> None
Sets the orientation of the frustum in world space as a rotation to
apply to the default frame: looking along the -z axis with the +y axis
as"up".
Parameters
----------
rotation : Rotation
"""
result["Frustum"].GetRotation.func_doc = """GetRotation() -> Rotation
Returns the orientation of the frustum in world space as a rotation to
apply to the -z axis.
"""
result["Frustum"].SetPositionAndRotationFromMatrix.func_doc = """SetPositionAndRotationFromMatrix(camToWorldXf) -> None
Sets the position and rotation of the frustum from a camera matrix
(always from a y-Up camera).
The resulting frustum's transform will always represent a right-handed
and orthonormal coordinate sytem (scale, shear, and projection are
removed from the given ``camToWorldXf`` ).
Parameters
----------
camToWorldXf : Matrix4d
"""
result["Frustum"].SetWindow.func_doc = """SetWindow(window) -> None
Sets the window rectangle in the reference plane that defines the
left, right, top, and bottom planes of the frustum.
Parameters
----------
window : Range2d
"""
result["Frustum"].GetWindow.func_doc = """GetWindow() -> Range2d
Returns the window rectangle in the reference plane.
"""
result["Frustum"].SetNearFar.func_doc = """SetNearFar(nearFar) -> None
Sets the near/far interval.
Parameters
----------
nearFar : Range1d
"""
result["Frustum"].GetNearFar.func_doc = """GetNearFar() -> Range1d
Returns the near/far interval.
"""
result["Frustum"].SetViewDistance.func_doc = """SetViewDistance(viewDistance) -> None
Sets the view distance.
Parameters
----------
viewDistance : float
"""
result["Frustum"].GetViewDistance.func_doc = """GetViewDistance() -> float
Returns the view distance.
"""
result["Frustum"].SetProjectionType.func_doc = """SetProjectionType(projectionType) -> None
Sets the projection type.
Parameters
----------
projectionType : Frustum.ProjectionType
"""
result["Frustum"].GetProjectionType.func_doc = """GetProjectionType() -> Frustum.ProjectionType
Returns the projection type.
"""
result["Frustum"].GetReferencePlaneDepth.func_doc = """**classmethod** GetReferencePlaneDepth() -> float
Returns the depth of the reference plane.
"""
result["Frustum"].SetPerspective.func_doc = """SetPerspective(fieldOfViewHeight, aspectRatio, nearDistance, farDistance) -> None
Sets up the frustum in a manner similar to ``gluPerspective()`` .
It sets the projection type to ``GfFrustum::Perspective`` and sets the
window specification so that the resulting symmetric frustum encloses
an angle of ``fieldOfViewHeight`` degrees in the vertical direction,
with ``aspectRatio`` used to figure the angle in the horizontal
direction. The near and far distances are specified as well. The
window coordinates are computed as:
.. code-block:: text
top = tan(fieldOfViewHeight / 2)
bottom = -top
right = top \\* aspectRatio
left = -right
near = nearDistance
far = farDistance
Parameters
----------
fieldOfViewHeight : float
aspectRatio : float
nearDistance : float
farDistance : float
----------------------------------------------------------------------
SetPerspective(fieldOfView, isFovVertical, aspectRatio, nearDistance, farDistance) -> None
Sets up the frustum in a manner similar to gluPerspective().
It sets the projection type to ``GfFrustum::Perspective`` and sets the
window specification so that:
If *isFovVertical* is true, the resulting symmetric frustum encloses
an angle of ``fieldOfView`` degrees in the vertical direction, with
``aspectRatio`` used to figure the angle in the horizontal direction.
If *isFovVertical* is false, the resulting symmetric frustum encloses
an angle of ``fieldOfView`` degrees in the horizontal direction, with
``aspectRatio`` used to figure the angle in the vertical direction.
The near and far distances are specified as well. The window
coordinates are computed as follows:
- if isFovVertical:
- top = tan(fieldOfView / 2)
- right = top \\* aspectRatio
- if NOT isFovVertical:
- right = tan(fieldOfView / 2)
- top = right / aspectRation
- bottom = -top
- left = -right
- near = nearDistance
- far = farDistance
Parameters
----------
fieldOfView : float
isFovVertical : bool
aspectRatio : float
nearDistance : float
farDistance : float
"""
result["Frustum"].SetOrthographic.func_doc = """SetOrthographic(left, right, bottom, top, nearPlane, farPlane) -> None
Sets up the frustum in a manner similar to ``glOrtho()`` .
Sets the projection to ``GfFrustum::Orthographic`` and sets the window
and near/far specifications based on the given values.
Parameters
----------
left : float
right : float
bottom : float
top : float
nearPlane : float
farPlane : float
"""
result["Frustum"].GetOrthographic.func_doc = """GetOrthographic(left, right, bottom, top, nearPlane, farPlane) -> bool
Returns the current frustum in the format used by
``SetOrthographic()`` .
If the current frustum is not an orthographic projection, this returns
``false`` and leaves the parameters untouched.
Parameters
----------
left : float
right : float
bottom : float
top : float
nearPlane : float
farPlane : float
"""
result["Frustum"].FitToSphere.func_doc = """FitToSphere(center, radius, slack) -> None
Modifies the frustum to tightly enclose a sphere with the given center
and radius, using the current view direction.
The planes of the frustum are adjusted as necessary. The given amount
of slack is added to the sphere's radius is used around the sphere to
avoid boundary problems.
Parameters
----------
center : Vec3d
radius : float
slack : float
"""
result["Frustum"].Transform.func_doc = """Transform(matrix) -> Frustum
Transforms the frustum by the given matrix.
The transformation matrix is applied as follows: the position and the
direction vector are transformed with the given matrix. Then the
length of the new direction vector is used to rescale the near and far
plane and the view distance. Finally, the points that define the
reference plane are transformed by the matrix. This method assures
that the frustum will not be sheared or perspective-projected.
Note that this definition means that the transformed frustum does not
preserve scales very well. Do *not* use this function to transform a
frustum that is to be used for precise operations such as intersection
testing.
Parameters
----------
matrix : Matrix4d
"""
result["Frustum"].ComputeViewDirection.func_doc = """ComputeViewDirection() -> Vec3d
Returns the normalized world-space view direction vector, which is
computed by rotating the -z axis by the frustum's rotation.
"""
result["Frustum"].ComputeUpVector.func_doc = """ComputeUpVector() -> Vec3d
Returns the normalized world-space up vector, which is computed by
rotating the y axis by the frustum's rotation.
"""
result["Frustum"].ComputeViewFrame.func_doc = """ComputeViewFrame(side, up, view) -> None
Computes the view frame defined by this frustum.
The frame consists of the view direction, up vector and side vector,
as shown in this diagram.
.. code-block:: text
up
^ ^
| /
| / view
|/
+- - - - > side
Parameters
----------
side : Vec3d
up : Vec3d
view : Vec3d
"""
result["Frustum"].ComputeLookAtPoint.func_doc = """ComputeLookAtPoint() -> Vec3d
Computes and returns the world-space look-at point from the eye point
(position), view direction (rotation), and view distance.
"""
result["Frustum"].ComputeViewMatrix.func_doc = """ComputeViewMatrix() -> Matrix4d
Returns a matrix that represents the viewing transformation for this
frustum.
That is, it returns the matrix that converts points from world space
to eye (frustum) space.
"""
result["Frustum"].ComputeViewInverse.func_doc = """ComputeViewInverse() -> Matrix4d
Returns a matrix that represents the inverse viewing transformation
for this frustum.
That is, it returns the matrix that converts points from eye (frustum)
space to world space.
"""
result["Frustum"].ComputeProjectionMatrix.func_doc = """ComputeProjectionMatrix() -> Matrix4d
Returns a GL-style projection matrix corresponding to the frustum's
projection.
"""
result["Frustum"].ComputeAspectRatio.func_doc = """ComputeAspectRatio() -> float
Returns the aspect ratio of the frustum, defined as the width of the
window divided by the height.
If the height is zero or negative, this returns 0.
"""
result["Frustum"].ComputeCorners.func_doc = """ComputeCorners() -> list[Vec3d]
Returns the world-space corners of the frustum as a vector of 8
points, ordered as:
- Left bottom near
- Right bottom near
- Left top near
- Right top near
- Left bottom far
- Right bottom far
- Left top far
- Right top far
"""
result["Frustum"].ComputeCornersAtDistance.func_doc = """ComputeCornersAtDistance(d) -> list[Vec3d]
Returns the world-space corners of the intersection of the frustum
with a plane parallel to the near/far plane at distance d from the
apex, ordered as:
- Left bottom
- Right bottom
- Left top
- Right top In particular, it gives the partial result of
ComputeCorners when given near or far distance.
Parameters
----------
d : float
"""
result["Frustum"].ComputeNarrowedFrustum.func_doc = """ComputeNarrowedFrustum(windowPos, size) -> Frustum
Returns a frustum that is a narrowed-down version of this frustum.
The new frustum has the same near and far planes, but the other planes
are adjusted to be centered on ``windowPos`` with the new width and
height obtained from the existing width and height by multiplying by
``size`` [0] and ``size`` [1], respectively. Finally, the new frustum
is clipped against this frustum so that it is completely contained in
the existing frustum.
``windowPos`` is given in normalized coords (-1 to +1 in both
dimensions). ``size`` is given as a scalar (0 to 1 in both
dimensions).
If the ``windowPos`` or ``size`` given is outside these ranges, it may
result in returning a collapsed frustum.
This method is useful for computing a volume to use for interactive
picking.
Parameters
----------
windowPos : Vec2d
size : Vec2d
----------------------------------------------------------------------
ComputeNarrowedFrustum(worldPoint, size) -> Frustum
Returns a frustum that is a narrowed-down version of this frustum.
The new frustum has the same near and far planes, but the other planes
are adjusted to be centered on ``worldPoint`` with the new width and
height obtained from the existing width and height by multiplying by
``size`` [0] and ``size`` [1], respectively. Finally, the new frustum
is clipped against this frustum so that it is completely contained in
the existing frustum.
``worldPoint`` is given in world space coordinates. ``size`` is given
as a scalar (0 to 1 in both dimensions).
If the ``size`` given is outside this range, it may result in
returning a collapsed frustum.
If the ``worldPoint`` is at or behind the eye of the frustum, it will
return a frustum equal to this frustum.
This method is useful for computing a volume to use for interactive
picking.
Parameters
----------
worldPoint : Vec3d
size : Vec2d
"""
result["Frustum"].ComputePickRay.func_doc = """ComputePickRay(windowPos) -> Ray
Builds and returns a ``GfRay`` that can be used for picking at the
given normalized (-1 to +1 in both dimensions) window position.
Contrasted with ComputeRay() , that method returns a ray whose origin
is the eyepoint, while this method returns a ray whose origin is on
the near plane.
Parameters
----------
windowPos : Vec2d
----------------------------------------------------------------------
ComputePickRay(worldSpacePos) -> Ray
Builds and returns a ``GfRay`` that can be used for picking that
connects the viewpoint to the given 3d point in worldspace.
Parameters
----------
worldSpacePos : Vec3d
"""
result["Frustum"].Intersects.func_doc = """Intersects(bbox) -> bool
Returns true if the given axis-aligned bbox is inside or intersecting
the frustum.
Otherwise, it returns false. Useful when doing picking or frustum
culling.
Parameters
----------
bbox : BBox3d
----------------------------------------------------------------------
Intersects(point) -> bool
Returns true if the given point is inside or intersecting the frustum.
Otherwise, it returns false.
Parameters
----------
point : Vec3d
----------------------------------------------------------------------
Intersects(p0, p1) -> bool
Returns ``true`` if the line segment formed by the given points is
inside or intersecting the frustum.
Otherwise, it returns false.
Parameters
----------
p0 : Vec3d
p1 : Vec3d
----------------------------------------------------------------------
Intersects(p0, p1, p2) -> bool
Returns ``true`` if the triangle formed by the given points is inside
or intersecting the frustum.
Otherwise, it returns false.
Parameters
----------
p0 : Vec3d
p1 : Vec3d
p2 : Vec3d
"""
result["Frustum"].IntersectsViewVolume.func_doc = """**classmethod** IntersectsViewVolume(bbox, vpMat) -> bool
Returns ``true`` if the bbox volume intersects the view volume given
by the view-projection matrix, erring on the side of false positives
for efficiency.
This method is intended for cases where a GfFrustum is not available
or when the view-projection matrix yields a view volume that is not
expressable as a GfFrustum.
Because it errs on the side of false positives, it is suitable for
early-out tests such as draw or intersection culling.
Parameters
----------
bbox : BBox3d
vpMat : Matrix4d
"""
result["Frustum"].ProjectionType.__doc__ = """
This enum is used to determine the type of projection represented by a
frustum.
"""
result["Frustum"].__init__.func_doc = """__init__()
This constructor creates an instance with default viewing parameters:
- The position is the origin.
- The rotation is the identity rotation. (The view is along the -z
axis, with the +y axis as"up").
- The window is -1 to +1 in both dimensions.
- The near/far interval is (1, 10).
- The view distance is 5.0.
- The projection type is ``GfFrustum::Perspective`` .
----------------------------------------------------------------------
__init__(o)
Copy constructor.
Parameters
----------
o : Frustum
----------------------------------------------------------------------
__init__(o)
Move constructor.
Parameters
----------
o : Frustum
----------------------------------------------------------------------
__init__(position, rotation, window, nearFar, projectionType, viewDistance)
This constructor creates an instance with the given viewing
parameters.
Parameters
----------
position : Vec3d
rotation : Rotation
window : Range2d
nearFar : Range1d
projectionType : Frustum.ProjectionType
viewDistance : float
----------------------------------------------------------------------
__init__(camToWorldXf, window, nearFar, projectionType, viewDistance)
This constructor creates an instance from a camera matrix (always of a
y-Up camera, also see SetPositionAndRotationFromMatrix) and the given
viewing parameters.
Parameters
----------
camToWorldXf : Matrix4d
window : Range2d
nearFar : Range1d
projectionType : Frustum.ProjectionType
viewDistance : float
"""
result["Interval"].IsMinClosed.func_doc = """IsMinClosed() -> bool
Minimum boundary condition.
"""
result["Interval"].IsMaxClosed.func_doc = """IsMaxClosed() -> bool
Maximum boundary condition.
"""
result["Interval"].IsMinOpen.func_doc = """IsMinOpen() -> bool
Minimum boundary condition.
"""
result["Interval"].IsMaxOpen.func_doc = """IsMaxOpen() -> bool
Maximum boundary condition.
"""
result["Interval"].IsMaxFinite.func_doc = """IsMaxFinite() -> bool
Returns true if the maximum value is finite.
"""
result["Interval"].IsMinFinite.func_doc = """IsMinFinite() -> bool
Returns true if the minimum value is finite.
"""
result["Interval"].IsFinite.func_doc = """IsFinite() -> bool
Returns true if both the maximum and minimum value are finite.
"""
result["Interval"].Intersects.func_doc = """Intersects(i) -> bool
Return true iff the given interval i intersects this interval.
Parameters
----------
i : Interval
"""
result["Interval"].GetFullInterval.func_doc = """**classmethod** GetFullInterval() -> Interval
Returns the full interval (-inf, inf).
"""
result["Line"].__init__.func_doc = """__init__()
The default constructor leaves line parameters undefined.
----------------------------------------------------------------------
__init__(p0, dir)
Construct a line from a point and a direction.
Parameters
----------
p0 : Vec3d
dir : Vec3d
"""
result["Line"].Set.func_doc = """Set(p0, dir) -> float
Parameters
----------
p0 : Vec3d
dir : Vec3d
"""
result["Line"].GetPoint.func_doc = """GetPoint(t) -> Vec3d
Return the point on the line at ```` ( p0 + t \\* dir).
Remember dir has been normalized so t represents a unit distance.
Parameters
----------
t : float
"""
result["Line"].GetDirection.func_doc = """GetDirection() -> Vec3d
Return the normalized direction of the line.
"""
result["Line"].FindClosestPoint.func_doc = """FindClosestPoint(point, t) -> Vec3d
Returns the point on the line that is closest to ``point`` .
If ``t`` is not ``None`` , it will be set to the parametric distance
along the line of the returned point.
Parameters
----------
point : Vec3d
t : float
"""
result["LineSeg"].__init__.func_doc = """__init__()
The default constructor leaves line parameters undefined.
----------------------------------------------------------------------
__init__(p0, p1)
Construct a line segment that spans two points.
Parameters
----------
p0 : Vec3d
p1 : Vec3d
"""
result["LineSeg"].GetPoint.func_doc = """GetPoint(t) -> Vec3d
Return the point on the segment specified by the parameter t.
p = p0 + t \\* (p1 - p0)
Parameters
----------
t : float
"""
result["LineSeg"].GetDirection.func_doc = """GetDirection() -> Vec3d
Return the normalized direction of the line.
"""
result["LineSeg"].GetLength.func_doc = """GetLength() -> float
Return the length of the line.
"""
result["LineSeg"].FindClosestPoint.func_doc = """FindClosestPoint(point, t) -> Vec3d
Returns the point on the line that is closest to ``point`` .
If ``t`` is not ``None`` , it will be set to the parametric distance
along the line of the closest point.
Parameters
----------
point : Vec3d
t : float
"""
result["Matrix2d"].__doc__ = """
Stores a 2x2 matrix of ``double`` elements. A basic type.
Matrices are defined to be in row-major order, so ``matrix[i][j]``
indexes the element in the *i* th row and the *j* th column.
"""
result["Matrix2d"].__init__.func_doc = """__init__()
Default constructor. Leaves the matrix component values undefined.
----------------------------------------------------------------------
__init__(m00, m01, m10, m11)
Constructor.
Initializes the matrix from 4 independent ``double`` values, specified
in row-major order. For example, parameter *m10* specifies the value
in row 1 and column 0.
Parameters
----------
m00 : float
m01 : float
m10 : float
m11 : float
----------------------------------------------------------------------
__init__(m)
Constructor.
Initializes the matrix from a 2x2 array of ``double`` values,
specified in row-major order.
Parameters
----------
m : float
----------------------------------------------------------------------
__init__(s)
Constructor.
Explicitly initializes the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
__init__(s)
This explicit constructor initializes the matrix to ``s`` times the
identity matrix.
Parameters
----------
s : int
----------------------------------------------------------------------
__init__(v)
Constructor.
Explicitly initializes the matrix to diagonal form, with the *i* th
element on the diagonal set to ``v[i]`` .
Parameters
----------
v : Vec2d
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of double. The vector
is expected to be 2x2. If it is too big, only the first 2 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of float. The vector is
expected to be 2x2. If it is too big, only the first 2 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(m)
This explicit constructor converts a"float"matrix to a"double"matrix.
Parameters
----------
m : Matrix2f
"""
result["Matrix2d"].SetRow.func_doc = """SetRow(i, v) -> None
Sets a row of the matrix from a Vec2.
Parameters
----------
i : int
v : Vec2d
"""
result["Matrix2d"].SetColumn.func_doc = """SetColumn(i, v) -> None
Sets a column of the matrix from a Vec2.
Parameters
----------
i : int
v : Vec2d
"""
result["Matrix2d"].GetRow.func_doc = """GetRow(i) -> Vec2d
Gets a row of the matrix as a Vec2.
Parameters
----------
i : int
"""
result["Matrix2d"].GetColumn.func_doc = """GetColumn(i) -> Vec2d
Gets a column of the matrix as a Vec2.
Parameters
----------
i : int
"""
result["Matrix2d"].Set.func_doc = """Set(m00, m01, m10, m11) -> Matrix2d
Sets the matrix from 4 independent ``double`` values, specified in
row-major order.
For example, parameter *m10* specifies the value in row 1 and column
0.
Parameters
----------
m00 : float
m01 : float
m10 : float
m11 : float
----------------------------------------------------------------------
Set(m) -> Matrix2d
Sets the matrix from a 2x2 array of ``double`` values, specified in
row-major order.
Parameters
----------
m : float
"""
result["Matrix2d"].SetIdentity.func_doc = """SetIdentity() -> Matrix2d
Sets the matrix to the identity matrix.
"""
result["Matrix2d"].SetZero.func_doc = """SetZero() -> Matrix2d
Sets the matrix to zero.
"""
result["Matrix2d"].SetDiagonal.func_doc = """SetDiagonal(s) -> Matrix2d
Sets the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
SetDiagonal(arg1) -> Matrix2d
Sets the matrix to have diagonal ( ``v[0], v[1]`` ).
Parameters
----------
arg1 : Vec2d
"""
result["Matrix2d"].GetTranspose.func_doc = """GetTranspose() -> Matrix2d
Returns the transpose of the matrix.
"""
result["Matrix2d"].GetInverse.func_doc = """GetInverse(det, eps) -> Matrix2d
Returns the inverse of the matrix, or FLT_MAX \\* SetIdentity() if the
matrix is singular.
(FLT_MAX is the largest value a ``float`` can have, as defined by the
system.) The matrix is considered singular if the determinant is less
than or equal to the optional parameter *eps*. If *det* is non-null,
``\\*det`` is set to the determinant.
Parameters
----------
det : float
eps : float
"""
result["Matrix2d"].GetDeterminant.func_doc = """GetDeterminant() -> float
Returns the determinant of the matrix.
"""
result["Matrix2f"].__doc__ = """
Stores a 2x2 matrix of ``float`` elements. A basic type.
Matrices are defined to be in row-major order, so ``matrix[i][j]``
indexes the element in the *i* th row and the *j* th column.
"""
result["Matrix2f"].__init__.func_doc = """__init__()
Default constructor. Leaves the matrix component values undefined.
----------------------------------------------------------------------
__init__(m00, m01, m10, m11)
Constructor.
Initializes the matrix from 4 independent ``float`` values, specified
in row-major order. For example, parameter *m10* specifies the value
in row 1 and column 0.
Parameters
----------
m00 : float
m01 : float
m10 : float
m11 : float
----------------------------------------------------------------------
__init__(m)
Constructor.
Initializes the matrix from a 2x2 array of ``float`` values, specified
in row-major order.
Parameters
----------
m : float
----------------------------------------------------------------------
__init__(s)
Constructor.
Explicitly initializes the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
__init__(s)
This explicit constructor initializes the matrix to ``s`` times the
identity matrix.
Parameters
----------
s : int
----------------------------------------------------------------------
__init__(v)
Constructor.
Explicitly initializes the matrix to diagonal form, with the *i* th
element on the diagonal set to ``v[i]`` .
Parameters
----------
v : Vec2f
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of double. The vector
is expected to be 2x2. If it is too big, only the first 2 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of float. The vector is
expected to be 2x2. If it is too big, only the first 2 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(m)
This explicit constructor converts a"double"matrix to a"float"matrix.
Parameters
----------
m : Matrix2d
"""
result["Matrix2f"].SetRow.func_doc = """SetRow(i, v) -> None
Sets a row of the matrix from a Vec2.
Parameters
----------
i : int
v : Vec2f
"""
result["Matrix2f"].SetColumn.func_doc = """SetColumn(i, v) -> None
Sets a column of the matrix from a Vec2.
Parameters
----------
i : int
v : Vec2f
"""
result["Matrix2f"].GetRow.func_doc = """GetRow(i) -> Vec2f
Gets a row of the matrix as a Vec2.
Parameters
----------
i : int
"""
result["Matrix2f"].GetColumn.func_doc = """GetColumn(i) -> Vec2f
Gets a column of the matrix as a Vec2.
Parameters
----------
i : int
"""
result["Matrix2f"].Set.func_doc = """Set(m00, m01, m10, m11) -> Matrix2f
Sets the matrix from 4 independent ``float`` values, specified in row-
major order.
For example, parameter *m10* specifies the value in row 1 and column
0.
Parameters
----------
m00 : float
m01 : float
m10 : float
m11 : float
----------------------------------------------------------------------
Set(m) -> Matrix2f
Sets the matrix from a 2x2 array of ``float`` values, specified in
row-major order.
Parameters
----------
m : float
"""
result["Matrix2f"].SetIdentity.func_doc = """SetIdentity() -> Matrix2f
Sets the matrix to the identity matrix.
"""
result["Matrix2f"].SetZero.func_doc = """SetZero() -> Matrix2f
Sets the matrix to zero.
"""
result["Matrix2f"].SetDiagonal.func_doc = """SetDiagonal(s) -> Matrix2f
Sets the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
SetDiagonal(arg1) -> Matrix2f
Sets the matrix to have diagonal ( ``v[0], v[1]`` ).
Parameters
----------
arg1 : Vec2f
"""
result["Matrix2f"].GetTranspose.func_doc = """GetTranspose() -> Matrix2f
Returns the transpose of the matrix.
"""
result["Matrix2f"].GetInverse.func_doc = """GetInverse(det, eps) -> Matrix2f
Returns the inverse of the matrix, or FLT_MAX \\* SetIdentity() if the
matrix is singular.
(FLT_MAX is the largest value a ``float`` can have, as defined by the
system.) The matrix is considered singular if the determinant is less
than or equal to the optional parameter *eps*. If *det* is non-null,
``\\*det`` is set to the determinant.
Parameters
----------
det : float
eps : float
"""
result["Matrix2f"].GetDeterminant.func_doc = """GetDeterminant() -> float
Returns the determinant of the matrix.
"""
result["Matrix3d"].__doc__ = """
Stores a 3x3 matrix of ``double`` elements. A basic type.
Matrices are defined to be in row-major order, so ``matrix[i][j]``
indexes the element in the *i* th row and the *j* th column.
3D Transformations
==================
Three methods, SetRotate() , SetScale() , and ExtractRotation() ,
interpret a GfMatrix3d as a 3D transformation. By convention, vectors
are treated primarily as row vectors, implying the following:
- Transformation matrices are organized to deal with row vectors,
not column vectors.
- Each of the Set() methods in this class completely rewrites the
matrix; for example, SetRotate() yields a matrix which does nothing
but rotate.
- When multiplying two transformation matrices, the matrix on the
left applies a more local transformation to a row vector. For example,
if R represents a rotation matrix and S represents a scale matrix, the
product R\\*S will rotate a row vector, then scale it.
"""
result["Matrix3d"].SetRotate.func_doc = """SetRotate(rot) -> Matrix3d
Sets the matrix to specify a rotation equivalent to *rot*.
Parameters
----------
rot : Quatd
----------------------------------------------------------------------
SetRotate(rot) -> Matrix3d
Sets the matrix to specify a rotation equivalent to *rot*.
Parameters
----------
rot : Rotation
"""
result["Matrix3d"].SetScale.func_doc = """SetScale(scaleFactors) -> Matrix3d
Sets the matrix to specify a nonuniform scaling in x, y, and z by the
factors in vector *scaleFactors*.
Parameters
----------
scaleFactors : Vec3d
----------------------------------------------------------------------
SetScale(scaleFactor) -> Matrix3d
Sets matrix to specify a uniform scaling by *scaleFactor*.
Parameters
----------
scaleFactor : float
"""
result["Matrix3d"].ExtractRotation.func_doc = """ExtractRotation() -> Rotation
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling
this method.
"""
result["Matrix3d"].__init__.func_doc = """__init__()
Default constructor. Leaves the matrix component values undefined.
----------------------------------------------------------------------
__init__(m00, m01, m02, m10, m11, m12, m20, m21, m22)
Constructor.
Initializes the matrix from 9 independent ``double`` values, specified
in row-major order. For example, parameter *m10* specifies the value
in row 1 and column 0.
Parameters
----------
m00 : float
m01 : float
m02 : float
m10 : float
m11 : float
m12 : float
m20 : float
m21 : float
m22 : float
----------------------------------------------------------------------
__init__(m)
Constructor.
Initializes the matrix from a 3x3 array of ``double`` values,
specified in row-major order.
Parameters
----------
m : float
----------------------------------------------------------------------
__init__(s)
Constructor.
Explicitly initializes the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
__init__(s)
This explicit constructor initializes the matrix to ``s`` times the
identity matrix.
Parameters
----------
s : int
----------------------------------------------------------------------
__init__(v)
Constructor.
Explicitly initializes the matrix to diagonal form, with the *i* th
element on the diagonal set to ``v[i]`` .
Parameters
----------
v : Vec3d
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of double. The vector
is expected to be 3x3. If it is too big, only the first 3 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of float. The vector is
expected to be 3x3. If it is too big, only the first 3 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(rot)
Constructor. Initialize matrix from rotation.
Parameters
----------
rot : Rotation
----------------------------------------------------------------------
__init__(rot)
Constructor. Initialize matrix from a quaternion.
Parameters
----------
rot : Quatd
----------------------------------------------------------------------
__init__(m)
This explicit constructor converts a"float"matrix to a"double"matrix.
Parameters
----------
m : Matrix3f
"""
result["Matrix3d"].SetRow.func_doc = """SetRow(i, v) -> None
Sets a row of the matrix from a Vec3.
Parameters
----------
i : int
v : Vec3d
"""
result["Matrix3d"].SetColumn.func_doc = """SetColumn(i, v) -> None
Sets a column of the matrix from a Vec3.
Parameters
----------
i : int
v : Vec3d
"""
result["Matrix3d"].GetRow.func_doc = """GetRow(i) -> Vec3d
Gets a row of the matrix as a Vec3.
Parameters
----------
i : int
"""
result["Matrix3d"].GetColumn.func_doc = """GetColumn(i) -> Vec3d
Gets a column of the matrix as a Vec3.
Parameters
----------
i : int
"""
result["Matrix3d"].Set.func_doc = """Set(m00, m01, m02, m10, m11, m12, m20, m21, m22) -> Matrix3d
Sets the matrix from 9 independent ``double`` values, specified in
row-major order.
For example, parameter *m10* specifies the value in row 1 and column
0.
Parameters
----------
m00 : float
m01 : float
m02 : float
m10 : float
m11 : float
m12 : float
m20 : float
m21 : float
m22 : float
----------------------------------------------------------------------
Set(m) -> Matrix3d
Sets the matrix from a 3x3 array of ``double`` values, specified in
row-major order.
Parameters
----------
m : float
"""
result["Matrix3d"].SetIdentity.func_doc = """SetIdentity() -> Matrix3d
Sets the matrix to the identity matrix.
"""
result["Matrix3d"].SetZero.func_doc = """SetZero() -> Matrix3d
Sets the matrix to zero.
"""
result["Matrix3d"].SetDiagonal.func_doc = """SetDiagonal(s) -> Matrix3d
Sets the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
SetDiagonal(arg1) -> Matrix3d
Sets the matrix to have diagonal ( ``v[0], v[1], v[2]`` ).
Parameters
----------
arg1 : Vec3d
"""
result["Matrix3d"].GetTranspose.func_doc = """GetTranspose() -> Matrix3d
Returns the transpose of the matrix.
"""
result["Matrix3d"].GetInverse.func_doc = """GetInverse(det, eps) -> Matrix3d
Returns the inverse of the matrix, or FLT_MAX \\* SetIdentity() if the
matrix is singular.
(FLT_MAX is the largest value a ``float`` can have, as defined by the
system.) The matrix is considered singular if the determinant is less
than or equal to the optional parameter *eps*. If *det* is non-null,
``\\*det`` is set to the determinant.
Parameters
----------
det : float
eps : float
"""
result["Matrix3d"].GetDeterminant.func_doc = """GetDeterminant() -> float
Returns the determinant of the matrix.
"""
result["Matrix3d"].Orthonormalize.func_doc = """Orthonormalize(issueWarning) -> bool
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous
cross/cross method. If the iterative method does not converge, a
warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any
translation part of the matrix unchanged. If *issueWarning* is true,
this method will issue a warning if the iteration does not converge,
otherwise it will be silent.
Parameters
----------
issueWarning : bool
"""
result["Matrix3d"].GetOrthonormalized.func_doc = """GetOrthonormalized(issueWarning) -> Matrix3d
Returns an orthonormalized copy of the matrix.
Parameters
----------
issueWarning : bool
"""
result["Matrix3d"].GetHandedness.func_doc = """GetHandedness() -> float
Returns the sign of the determinant of the matrix, i.e.
1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a
singular matrix.
"""
result["Matrix3d"].IsRightHanded.func_doc = """IsRightHanded() -> bool
Returns true if the vectors in the matrix form a right-handed
coordinate system.
"""
result["Matrix3d"].IsLeftHanded.func_doc = """IsLeftHanded() -> bool
Returns true if the vectors in matrix form a left-handed coordinate
system.
"""
result["Matrix3f"].__doc__ = """
Stores a 3x3 matrix of ``float`` elements. A basic type.
Matrices are defined to be in row-major order, so ``matrix[i][j]``
indexes the element in the *i* th row and the *j* th column.
3D Transformations
==================
Three methods, SetRotate() , SetScale() , and ExtractRotation() ,
interpret a GfMatrix3f as a 3D transformation. By convention, vectors
are treated primarily as row vectors, implying the following:
- Transformation matrices are organized to deal with row vectors,
not column vectors.
- Each of the Set() methods in this class completely rewrites the
matrix; for example, SetRotate() yields a matrix which does nothing
but rotate.
- When multiplying two transformation matrices, the matrix on the
left applies a more local transformation to a row vector. For example,
if R represents a rotation matrix and S represents a scale matrix, the
product R\\*S will rotate a row vector, then scale it.
"""
result["Matrix3f"].SetRotate.func_doc = """SetRotate(rot) -> Matrix3f
Sets the matrix to specify a rotation equivalent to *rot*.
Parameters
----------
rot : Quatf
----------------------------------------------------------------------
SetRotate(rot) -> Matrix3f
Sets the matrix to specify a rotation equivalent to *rot*.
Parameters
----------
rot : Rotation
"""
result["Matrix3f"].SetScale.func_doc = """SetScale(scaleFactors) -> Matrix3f
Sets the matrix to specify a nonuniform scaling in x, y, and z by the
factors in vector *scaleFactors*.
Parameters
----------
scaleFactors : Vec3f
----------------------------------------------------------------------
SetScale(scaleFactor) -> Matrix3f
Sets matrix to specify a uniform scaling by *scaleFactor*.
Parameters
----------
scaleFactor : float
"""
result["Matrix3f"].ExtractRotation.func_doc = """ExtractRotation() -> Rotation
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling
this method.
"""
result["Matrix3f"].__init__.func_doc = """__init__()
Default constructor. Leaves the matrix component values undefined.
----------------------------------------------------------------------
__init__(m00, m01, m02, m10, m11, m12, m20, m21, m22)
Constructor.
Initializes the matrix from 9 independent ``float`` values, specified
in row-major order. For example, parameter *m10* specifies the value
in row 1 and column 0.
Parameters
----------
m00 : float
m01 : float
m02 : float
m10 : float
m11 : float
m12 : float
m20 : float
m21 : float
m22 : float
----------------------------------------------------------------------
__init__(m)
Constructor.
Initializes the matrix from a 3x3 array of ``float`` values, specified
in row-major order.
Parameters
----------
m : float
----------------------------------------------------------------------
__init__(s)
Constructor.
Explicitly initializes the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
__init__(s)
This explicit constructor initializes the matrix to ``s`` times the
identity matrix.
Parameters
----------
s : int
----------------------------------------------------------------------
__init__(v)
Constructor.
Explicitly initializes the matrix to diagonal form, with the *i* th
element on the diagonal set to ``v[i]`` .
Parameters
----------
v : Vec3f
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of double. The vector
is expected to be 3x3. If it is too big, only the first 3 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of float. The vector is
expected to be 3x3. If it is too big, only the first 3 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(rot)
Constructor. Initialize matrix from rotation.
Parameters
----------
rot : Rotation
----------------------------------------------------------------------
__init__(rot)
Constructor. Initialize matrix from a quaternion.
Parameters
----------
rot : Quatf
----------------------------------------------------------------------
__init__(m)
This explicit constructor converts a"double"matrix to a"float"matrix.
Parameters
----------
m : Matrix3d
"""
result["Matrix3f"].SetRow.func_doc = """SetRow(i, v) -> None
Sets a row of the matrix from a Vec3.
Parameters
----------
i : int
v : Vec3f
"""
result["Matrix3f"].SetColumn.func_doc = """SetColumn(i, v) -> None
Sets a column of the matrix from a Vec3.
Parameters
----------
i : int
v : Vec3f
"""
result["Matrix3f"].GetRow.func_doc = """GetRow(i) -> Vec3f
Gets a row of the matrix as a Vec3.
Parameters
----------
i : int
"""
result["Matrix3f"].GetColumn.func_doc = """GetColumn(i) -> Vec3f
Gets a column of the matrix as a Vec3.
Parameters
----------
i : int
"""
result["Matrix3f"].Set.func_doc = """Set(m00, m01, m02, m10, m11, m12, m20, m21, m22) -> Matrix3f
Sets the matrix from 9 independent ``float`` values, specified in row-
major order.
For example, parameter *m10* specifies the value in row 1 and column
0.
Parameters
----------
m00 : float
m01 : float
m02 : float
m10 : float
m11 : float
m12 : float
m20 : float
m21 : float
m22 : float
----------------------------------------------------------------------
Set(m) -> Matrix3f
Sets the matrix from a 3x3 array of ``float`` values, specified in
row-major order.
Parameters
----------
m : float
"""
result["Matrix3f"].SetIdentity.func_doc = """SetIdentity() -> Matrix3f
Sets the matrix to the identity matrix.
"""
result["Matrix3f"].SetZero.func_doc = """SetZero() -> Matrix3f
Sets the matrix to zero.
"""
result["Matrix3f"].SetDiagonal.func_doc = """SetDiagonal(s) -> Matrix3f
Sets the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
SetDiagonal(arg1) -> Matrix3f
Sets the matrix to have diagonal ( ``v[0], v[1], v[2]`` ).
Parameters
----------
arg1 : Vec3f
"""
result["Matrix3f"].GetTranspose.func_doc = """GetTranspose() -> Matrix3f
Returns the transpose of the matrix.
"""
result["Matrix3f"].GetInverse.func_doc = """GetInverse(det, eps) -> Matrix3f
Returns the inverse of the matrix, or FLT_MAX \\* SetIdentity() if the
matrix is singular.
(FLT_MAX is the largest value a ``float`` can have, as defined by the
system.) The matrix is considered singular if the determinant is less
than or equal to the optional parameter *eps*. If *det* is non-null,
``\\*det`` is set to the determinant.
Parameters
----------
det : float
eps : float
"""
result["Matrix3f"].GetDeterminant.func_doc = """GetDeterminant() -> float
Returns the determinant of the matrix.
"""
result["Matrix3f"].Orthonormalize.func_doc = """Orthonormalize(issueWarning) -> bool
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous
cross/cross method. If the iterative method does not converge, a
warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any
translation part of the matrix unchanged. If *issueWarning* is true,
this method will issue a warning if the iteration does not converge,
otherwise it will be silent.
Parameters
----------
issueWarning : bool
"""
result["Matrix3f"].GetOrthonormalized.func_doc = """GetOrthonormalized(issueWarning) -> Matrix3f
Returns an orthonormalized copy of the matrix.
Parameters
----------
issueWarning : bool
"""
result["Matrix3f"].GetHandedness.func_doc = """GetHandedness() -> float
Returns the sign of the determinant of the matrix, i.e.
1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a
singular matrix.
"""
result["Matrix3f"].IsRightHanded.func_doc = """IsRightHanded() -> bool
Returns true if the vectors in the matrix form a right-handed
coordinate system.
"""
result["Matrix3f"].IsLeftHanded.func_doc = """IsLeftHanded() -> bool
Returns true if the vectors in matrix form a left-handed coordinate
system.
"""
result["Matrix4d"].__doc__ = """
Stores a 4x4 matrix of ``double`` elements. A basic type.
Matrices are defined to be in row-major order, so ``matrix[i][j]``
indexes the element in the *i* th row and the *j* th column.
3D Transformations
==================
The following methods interpret a GfMatrix4d as a 3D transformation:
SetRotate() , SetScale() , SetTranslate() , SetLookAt() , Factor() ,
ExtractTranslation() , ExtractRotation() , Transform() ,
TransformDir() . By convention, vectors are treated primarily as row
vectors, implying the following:
- Transformation matrices are organized to deal with row vectors,
not column vectors. For example, the last row of a matrix contains the
translation amounts.
- Each of the Set() methods below completely rewrites the matrix;
for example, SetTranslate() yields a matrix which does nothing but
translate.
- When multiplying two transformation matrices, the matrix on the
left applies a more local transformation to a row vector. For example,
if R represents a rotation matrix and T represents a translation
matrix, the product R\\*T will rotate a row vector, then translate it.
"""
result["Matrix4d"].SetRotate.func_doc = """SetRotate(rot) -> Matrix4d
Sets the matrix to specify a rotation equivalent to *rot*, and clears
the translation.
Parameters
----------
rot : Quatd
----------------------------------------------------------------------
SetRotate(rot) -> Matrix4d
Sets the matrix to specify a rotation equivalent to *rot*, and clears
the translation.
Parameters
----------
rot : Rotation
----------------------------------------------------------------------
SetRotate(mx) -> Matrix4d
Sets the matrix to specify a rotation equivalent to *mx*, and clears
the translation.
Parameters
----------
mx : Matrix3d
"""
result["Matrix4d"].SetRotateOnly.func_doc = """SetRotateOnly(rot) -> Matrix4d
Sets the matrix to specify a rotation equivalent to *rot*, without
clearing the translation.
Parameters
----------
rot : Quatd
----------------------------------------------------------------------
SetRotateOnly(rot) -> Matrix4d
Sets the matrix to specify a rotation equivalent to *rot*, without
clearing the translation.
Parameters
----------
rot : Rotation
----------------------------------------------------------------------
SetRotateOnly(mx) -> Matrix4d
Sets the matrix to specify a rotation equivalent to *mx*, without
clearing the translation.
Parameters
----------
mx : Matrix3d
"""
result["Matrix4d"].SetScale.func_doc = """SetScale(scaleFactors) -> Matrix4d
Sets the matrix to specify a nonuniform scaling in x, y, and z by the
factors in vector *scaleFactors*.
Parameters
----------
scaleFactors : Vec3d
----------------------------------------------------------------------
SetScale(scaleFactor) -> Matrix4d
Sets matrix to specify a uniform scaling by *scaleFactor*.
Parameters
----------
scaleFactor : float
"""
result["Matrix4d"].SetTranslate.func_doc = """SetTranslate(trans) -> Matrix4d
Sets matrix to specify a translation by the vector *trans*, and clears
the rotation.
Parameters
----------
trans : Vec3d
"""
result["Matrix4d"].SetTranslateOnly.func_doc = """SetTranslateOnly(t) -> Matrix4d
Sets matrix to specify a translation by the vector *trans*, without
clearing the rotation.
Parameters
----------
t : Vec3d
"""
result["Matrix4d"].SetTransform.func_doc = """SetTransform(rotate, translate) -> Matrix4d
Sets matrix to specify a rotation by *rotate* and a translation by
*translate*.
Parameters
----------
rotate : Rotation
translate : Vec3d
----------------------------------------------------------------------
SetTransform(rotmx, translate) -> Matrix4d
Sets matrix to specify a rotation by *rotmx* and a translation by
*translate*.
Parameters
----------
rotmx : Matrix3d
translate : Vec3d
"""
result["Matrix4d"].SetLookAt.func_doc = """SetLookAt(eyePoint, centerPoint, upDirection) -> Matrix4d
Sets the matrix to specify a viewing matrix from parameters similar to
those used by ``gluLookAt(3G)`` .
*eyePoint* represents the eye point in world space. *centerPoint*
represents the world-space center of attention. *upDirection* is a
vector indicating which way is up.
Parameters
----------
eyePoint : Vec3d
centerPoint : Vec3d
upDirection : Vec3d
----------------------------------------------------------------------
SetLookAt(eyePoint, orientation) -> Matrix4d
Sets the matrix to specify a viewing matrix from a world-space
*eyePoint* and a world-space rotation that rigidly rotates the
orientation from its canonical frame, which is defined to be looking
along the ``-z`` axis with the ``+y`` axis as the up direction.
Parameters
----------
eyePoint : Vec3d
orientation : Rotation
"""
result["Matrix4d"].Factor.func_doc = """Factor(r, s, u, t, p, eps) -> bool
Factors the matrix into 5 components:
- ``*M* = r \\* s \\* -r \\* u \\* t`` where
- *t* is a translation.
- *u* and *r* are rotations, and *-r* is the transpose (inverse) of
*r*. The *u* matrix may contain shear information.
- *s* is a scale. Any projection information could be returned in
matrix *p*, but currently p is never modified.
Returns ``false`` if the matrix is singular (as determined by *eps*).
In that case, any zero scales in *s* are clamped to *eps* to allow
computation of *u*.
Parameters
----------
r : Matrix4d
s : Vec3d
u : Matrix4d
t : Vec3d
p : Matrix4d
eps : float
"""
result["Matrix4d"].ExtractTranslation.func_doc = """ExtractTranslation() -> Vec3d
Returns the translation part of the matrix, defined as the first three
elements of the last row.
"""
result["Matrix4d"].ExtractRotation.func_doc = """ExtractRotation() -> Rotation
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling
this method.
"""
result["Matrix4d"].ExtractRotationQuat.func_doc = """ExtractRotationQuat() -> Quatd
Return the rotation corresponding to this matrix as a quaternion.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling
this method.
"""
result["Matrix4d"].ExtractRotationMatrix.func_doc = """ExtractRotationMatrix() -> Matrix3d
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling
this method.
"""
result["Matrix4d"].Transform.func_doc = """Transform(vec) -> Vec3d
Transforms the row vector *vec* by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component
is 1.
Parameters
----------
vec : Vec3d
----------------------------------------------------------------------
Transform(vec) -> Vec3f
Transforms the row vector *vec* by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component
is 1. This is an overloaded method; it differs from the other version
in that it returns a different value type.
Parameters
----------
vec : Vec3f
"""
result["Matrix4d"].TransformDir.func_doc = """TransformDir(vec) -> Vec3d
Transforms row vector *vec* by the matrix, returning the result.
This treats the vector as a direction vector, so the translation
information in the matrix is ignored. That is, it treats the vector as
a 4-component vector whose fourth component is 0.
Parameters
----------
vec : Vec3d
----------------------------------------------------------------------
TransformDir(vec) -> Vec3f
Transforms row vector *vec* by the matrix, returning the result.
This treats the vector as a direction vector, so the translation
information in the matrix is ignored. That is, it treats the vector as
a 4-component vector whose fourth component is 0. This is an
overloaded method; it differs from the other version in that it
returns a different value type.
Parameters
----------
vec : Vec3f
"""
result["Matrix4d"].TransformAffine.func_doc = """TransformAffine(vec) -> Vec3d
Transforms the row vector *vec* by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component
is 1 and ignores the fourth column of the matrix (i.e. assumes it is
(0, 0, 0, 1)).
Parameters
----------
vec : Vec3d
----------------------------------------------------------------------
TransformAffine(vec) -> Vec3f
Transforms the row vector *vec* by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component
is 1 and ignores the fourth column of the matrix (i.e. assumes it is
(0, 0, 0, 1)).
Parameters
----------
vec : Vec3f
"""
result["Matrix4d"].__init__.func_doc = """__init__()
Default constructor. Leaves the matrix component values undefined.
----------------------------------------------------------------------
__init__(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33)
Constructor.
Initializes the matrix from 16 independent ``double`` values,
specified in row-major order. For example, parameter *m10* specifies
the value in row 1 and column 0.
Parameters
----------
m00 : float
m01 : float
m02 : float
m03 : float
m10 : float
m11 : float
m12 : float
m13 : float
m20 : float
m21 : float
m22 : float
m23 : float
m30 : float
m31 : float
m32 : float
m33 : float
----------------------------------------------------------------------
__init__(m)
Constructor.
Initializes the matrix from a 4x4 array of ``double`` values,
specified in row-major order.
Parameters
----------
m : float
----------------------------------------------------------------------
__init__(s)
Constructor.
Explicitly initializes the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
__init__(v)
Constructor.
Explicitly initializes the matrix to diagonal form, with the *i* th
element on the diagonal set to ``v[i]`` .
Parameters
----------
v : Vec4d
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of double. The vector
is expected to be 4x4. If it is too big, only the first 4 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of float. The vector is
expected to be 4x4. If it is too big, only the first 4 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(r0, r1, r2, r3)
Constructor.
Initialize the matrix from 4 row vectors of double. Each vector is
expected to length 4. If it is too big, only the first 4 items will be
used. If it is too small, uninitialized elements will be filled in
with the corresponding elements from an identity matrix.
Parameters
----------
r0 : list[float]
r1 : list[float]
r2 : list[float]
r3 : list[float]
----------------------------------------------------------------------
__init__(r0, r1, r2, r3)
Constructor.
Initialize the matrix from 4 row vectors of float. Each vector is
expected to length 4. If it is too big, only the first 4 items will be
used. If it is too small, uninitialized elements will be filled in
with the corresponding elements from an identity matrix.
Parameters
----------
r0 : list[float]
r1 : list[float]
r2 : list[float]
r3 : list[float]
----------------------------------------------------------------------
__init__(rotate, translate)
Constructor.
Initializes a transformation matrix to perform the indicated rotation
and translation.
Parameters
----------
rotate : Rotation
translate : Vec3d
----------------------------------------------------------------------
__init__(rotmx, translate)
Constructor.
Initializes a transformation matrix to perform the indicated rotation
and translation.
Parameters
----------
rotmx : Matrix3d
translate : Vec3d
----------------------------------------------------------------------
__init__(m)
This explicit constructor converts a"float"matrix to a"double"matrix.
Parameters
----------
m : Matrix4f
"""
result["Matrix4d"].SetRow.func_doc = """SetRow(i, v) -> None
Sets a row of the matrix from a Vec4.
Parameters
----------
i : int
v : Vec4d
"""
result["Matrix4d"].SetColumn.func_doc = """SetColumn(i, v) -> None
Sets a column of the matrix from a Vec4.
Parameters
----------
i : int
v : Vec4d
"""
result["Matrix4d"].GetRow.func_doc = """GetRow(i) -> Vec4d
Gets a row of the matrix as a Vec4.
Parameters
----------
i : int
"""
result["Matrix4d"].GetColumn.func_doc = """GetColumn(i) -> Vec4d
Gets a column of the matrix as a Vec4.
Parameters
----------
i : int
"""
result["Matrix4d"].Set.func_doc = """Set(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) -> Matrix4d
Sets the matrix from 16 independent ``double`` values, specified in
row-major order.
For example, parameter *m10* specifies the value in row 1 and column
0.
Parameters
----------
m00 : float
m01 : float
m02 : float
m03 : float
m10 : float
m11 : float
m12 : float
m13 : float
m20 : float
m21 : float
m22 : float
m23 : float
m30 : float
m31 : float
m32 : float
m33 : float
----------------------------------------------------------------------
Set(m) -> Matrix4d
Sets the matrix from a 4x4 array of ``double`` values, specified in
row-major order.
Parameters
----------
m : float
"""
result["Matrix4d"].SetIdentity.func_doc = """SetIdentity() -> Matrix4d
Sets the matrix to the identity matrix.
"""
result["Matrix4d"].SetZero.func_doc = """SetZero() -> Matrix4d
Sets the matrix to zero.
"""
result["Matrix4d"].SetDiagonal.func_doc = """SetDiagonal(s) -> Matrix4d
Sets the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
SetDiagonal(arg1) -> Matrix4d
Sets the matrix to have diagonal ( ``v[0], v[1], v[2], v[3]`` ).
Parameters
----------
arg1 : Vec4d
"""
result["Matrix4d"].GetTranspose.func_doc = """GetTranspose() -> Matrix4d
Returns the transpose of the matrix.
"""
result["Matrix4d"].GetInverse.func_doc = """GetInverse(det, eps) -> Matrix4d
Returns the inverse of the matrix, or FLT_MAX \\* SetIdentity() if the
matrix is singular.
(FLT_MAX is the largest value a ``float`` can have, as defined by the
system.) The matrix is considered singular if the determinant is less
than or equal to the optional parameter *eps*. If *det* is non-null,
``\\*det`` is set to the determinant.
Parameters
----------
det : float
eps : float
"""
result["Matrix4d"].GetDeterminant.func_doc = """GetDeterminant() -> float
Returns the determinant of the matrix.
"""
result["Matrix4d"].SetRow3.func_doc = """SetRow3(i, v) -> None
Sets a row of the matrix from a Vec3.
The fourth element of the row is ignored.
Parameters
----------
i : int
v : Vec3d
"""
result["Matrix4d"].GetRow3.func_doc = """GetRow3(i) -> Vec3d
Gets a row of the matrix as a Vec3.
Parameters
----------
i : int
"""
result["Matrix4d"].GetDeterminant3.func_doc = """GetDeterminant3() -> float
Returns the determinant of the upper 3x3 matrix.
This method is useful when the matrix describes a linear
transformation such as a rotation or scale because the other values in
the 4x4 matrix are not important.
"""
result["Matrix4d"].HasOrthogonalRows3.func_doc = """HasOrthogonalRows3() -> bool
Returns true, if the row vectors of the upper 3x3 matrix form an
orthogonal basis.
Note they do not have to be unit length for this test to return true.
"""
result["Matrix4d"].Orthonormalize.func_doc = """Orthonormalize(issueWarning) -> bool
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous
cross/cross method. If the iterative method does not converge, a
warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any
translation part of the matrix unchanged. If *issueWarning* is true,
this method will issue a warning if the iteration does not converge,
otherwise it will be silent.
Parameters
----------
issueWarning : bool
"""
result["Matrix4d"].GetOrthonormalized.func_doc = """GetOrthonormalized(issueWarning) -> Matrix4d
Returns an orthonormalized copy of the matrix.
Parameters
----------
issueWarning : bool
"""
result["Matrix4d"].GetHandedness.func_doc = """GetHandedness() -> float
Returns the sign of the determinant of the upper 3x3 matrix, i.e.
1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a
singular matrix.
"""
result["Matrix4d"].IsRightHanded.func_doc = """IsRightHanded() -> bool
Returns true if the vectors in the upper 3x3 matrix form a right-
handed coordinate system.
"""
result["Matrix4d"].IsLeftHanded.func_doc = """IsLeftHanded() -> bool
Returns true if the vectors in the upper 3x3 matrix form a left-handed
coordinate system.
"""
result["Matrix4d"].RemoveScaleShear.func_doc = """RemoveScaleShear() -> Matrix4d
Returns the matrix with any scaling or shearing removed, leaving only
the rotation and translation.
If the matrix cannot be decomposed, returns the original matrix.
"""
result["Matrix4f"].__doc__ = """
Stores a 4x4 matrix of ``float`` elements. A basic type.
Matrices are defined to be in row-major order, so ``matrix[i][j]``
indexes the element in the *i* th row and the *j* th column.
3D Transformations
==================
The following methods interpret a GfMatrix4f as a 3D transformation:
SetRotate() , SetScale() , SetTranslate() , SetLookAt() , Factor() ,
ExtractTranslation() , ExtractRotation() , Transform() ,
TransformDir() . By convention, vectors are treated primarily as row
vectors, implying the following:
- Transformation matrices are organized to deal with row vectors,
not column vectors. For example, the last row of a matrix contains the
translation amounts.
- Each of the Set() methods below completely rewrites the matrix;
for example, SetTranslate() yields a matrix which does nothing but
translate.
- When multiplying two transformation matrices, the matrix on the
left applies a more local transformation to a row vector. For example,
if R represents a rotation matrix and T represents a translation
matrix, the product R\\*T will rotate a row vector, then translate it.
"""
result["Matrix4f"].SetRotate.func_doc = """SetRotate(rot) -> Matrix4f
Sets the matrix to specify a rotation equivalent to *rot*, and clears
the translation.
Parameters
----------
rot : Quatf
----------------------------------------------------------------------
SetRotate(rot) -> Matrix4f
Sets the matrix to specify a rotation equivalent to *rot*, and clears
the translation.
Parameters
----------
rot : Rotation
----------------------------------------------------------------------
SetRotate(mx) -> Matrix4f
Sets the matrix to specify a rotation equivalent to *mx*, and clears
the translation.
Parameters
----------
mx : Matrix3f
"""
result["Matrix4f"].SetRotateOnly.func_doc = """SetRotateOnly(rot) -> Matrix4f
Sets the matrix to specify a rotation equivalent to *rot*, without
clearing the translation.
Parameters
----------
rot : Quatf
----------------------------------------------------------------------
SetRotateOnly(rot) -> Matrix4f
Sets the matrix to specify a rotation equivalent to *rot*, without
clearing the translation.
Parameters
----------
rot : Rotation
----------------------------------------------------------------------
SetRotateOnly(mx) -> Matrix4f
Sets the matrix to specify a rotation equivalent to *mx*, without
clearing the translation.
Parameters
----------
mx : Matrix3f
"""
result["Matrix4f"].SetScale.func_doc = """SetScale(scaleFactors) -> Matrix4f
Sets the matrix to specify a nonuniform scaling in x, y, and z by the
factors in vector *scaleFactors*.
Parameters
----------
scaleFactors : Vec3f
----------------------------------------------------------------------
SetScale(scaleFactor) -> Matrix4f
Sets matrix to specify a uniform scaling by *scaleFactor*.
Parameters
----------
scaleFactor : float
"""
result["Matrix4f"].SetTranslate.func_doc = """SetTranslate(trans) -> Matrix4f
Sets matrix to specify a translation by the vector *trans*, and clears
the rotation.
Parameters
----------
trans : Vec3f
"""
result["Matrix4f"].SetTranslateOnly.func_doc = """SetTranslateOnly(t) -> Matrix4f
Sets matrix to specify a translation by the vector *trans*, without
clearing the rotation.
Parameters
----------
t : Vec3f
"""
result["Matrix4f"].SetTransform.func_doc = """SetTransform(rotate, translate) -> Matrix4f
Sets matrix to specify a rotation by *rotate* and a translation by
*translate*.
Parameters
----------
rotate : Rotation
translate : Vec3f
----------------------------------------------------------------------
SetTransform(rotmx, translate) -> Matrix4f
Sets matrix to specify a rotation by *rotmx* and a translation by
*translate*.
Parameters
----------
rotmx : Matrix3f
translate : Vec3f
"""
result["Matrix4f"].SetLookAt.func_doc = """SetLookAt(eyePoint, centerPoint, upDirection) -> Matrix4f
Sets the matrix to specify a viewing matrix from parameters similar to
those used by ``gluLookAt(3G)`` .
*eyePoint* represents the eye point in world space. *centerPoint*
represents the world-space center of attention. *upDirection* is a
vector indicating which way is up.
Parameters
----------
eyePoint : Vec3f
centerPoint : Vec3f
upDirection : Vec3f
----------------------------------------------------------------------
SetLookAt(eyePoint, orientation) -> Matrix4f
Sets the matrix to specify a viewing matrix from a world-space
*eyePoint* and a world-space rotation that rigidly rotates the
orientation from its canonical frame, which is defined to be looking
along the ``-z`` axis with the ``+y`` axis as the up direction.
Parameters
----------
eyePoint : Vec3f
orientation : Rotation
"""
result["Matrix4f"].Factor.func_doc = """Factor(r, s, u, t, p, eps) -> bool
Factors the matrix into 5 components:
- ``*M* = r \\* s \\* -r \\* u \\* t`` where
- *t* is a translation.
- *u* and *r* are rotations, and *-r* is the transpose (inverse) of
*r*. The *u* matrix may contain shear information.
- *s* is a scale. Any projection information could be returned in
matrix *p*, but currently p is never modified.
Returns ``false`` if the matrix is singular (as determined by *eps*).
In that case, any zero scales in *s* are clamped to *eps* to allow
computation of *u*.
Parameters
----------
r : Matrix4f
s : Vec3f
u : Matrix4f
t : Vec3f
p : Matrix4f
eps : float
"""
result["Matrix4f"].ExtractTranslation.func_doc = """ExtractTranslation() -> Vec3f
Returns the translation part of the matrix, defined as the first three
elements of the last row.
"""
result["Matrix4f"].ExtractRotation.func_doc = """ExtractRotation() -> Rotation
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling
this method.
"""
result["Matrix4f"].ExtractRotationQuat.func_doc = """ExtractRotationQuat() -> Quatf
Return the rotation corresponding to this matrix as a quaternion.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling
this method.
"""
result["Matrix4f"].ExtractRotationMatrix.func_doc = """ExtractRotationMatrix() -> Matrix3f
Returns the rotation corresponding to this matrix.
This works well only if the matrix represents a rotation.
For good results, consider calling Orthonormalize() before calling
this method.
"""
result["Matrix4f"].Transform.func_doc = """Transform(vec) -> Vec3d
Transforms the row vector *vec* by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component
is 1.
Parameters
----------
vec : Vec3d
----------------------------------------------------------------------
Transform(vec) -> Vec3f
Transforms the row vector *vec* by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component
is 1. This is an overloaded method; it differs from the other version
in that it returns a different value type.
Parameters
----------
vec : Vec3f
"""
result["Matrix4f"].TransformDir.func_doc = """TransformDir(vec) -> Vec3d
Transforms row vector *vec* by the matrix, returning the result.
This treats the vector as a direction vector, so the translation
information in the matrix is ignored. That is, it treats the vector as
a 4-component vector whose fourth component is 0.
Parameters
----------
vec : Vec3d
----------------------------------------------------------------------
TransformDir(vec) -> Vec3f
Transforms row vector *vec* by the matrix, returning the result.
This treats the vector as a direction vector, so the translation
information in the matrix is ignored. That is, it treats the vector as
a 4-component vector whose fourth component is 0. This is an
overloaded method; it differs from the other version in that it
returns a different value type.
Parameters
----------
vec : Vec3f
"""
result["Matrix4f"].TransformAffine.func_doc = """TransformAffine(vec) -> Vec3d
Transforms the row vector *vec* by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component
is 1 and ignores the fourth column of the matrix (i.e. assumes it is
(0, 0, 0, 1)).
Parameters
----------
vec : Vec3d
----------------------------------------------------------------------
TransformAffine(vec) -> Vec3f
Transforms the row vector *vec* by the matrix, returning the result.
This treats the vector as a 4-component vector whose fourth component
is 1 and ignores the fourth column of the matrix (i.e. assumes it is
(0, 0, 0, 1)).
Parameters
----------
vec : Vec3f
"""
result["Matrix4f"].__init__.func_doc = """__init__()
Default constructor. Leaves the matrix component values undefined.
----------------------------------------------------------------------
__init__(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33)
Constructor.
Initializes the matrix from 16 independent ``float`` values, specified
in row-major order. For example, parameter *m10* specifies the value
in row 1 and column 0.
Parameters
----------
m00 : float
m01 : float
m02 : float
m03 : float
m10 : float
m11 : float
m12 : float
m13 : float
m20 : float
m21 : float
m22 : float
m23 : float
m30 : float
m31 : float
m32 : float
m33 : float
----------------------------------------------------------------------
__init__(m)
Constructor.
Initializes the matrix from a 4x4 array of ``float`` values, specified
in row-major order.
Parameters
----------
m : float
----------------------------------------------------------------------
__init__(s)
Constructor.
Explicitly initializes the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
__init__(v)
Constructor.
Explicitly initializes the matrix to diagonal form, with the *i* th
element on the diagonal set to ``v[i]`` .
Parameters
----------
v : Vec4f
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of double. The vector
is expected to be 4x4. If it is too big, only the first 4 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(v)
Constructor.
Initialize the matrix from a vector of vectors of float. The vector is
expected to be 4x4. If it is too big, only the first 4 rows and/or
columns will be used. If it is too small, uninitialized elements will
be filled in with the corresponding elements from an identity matrix.
Parameters
----------
v : list[list[float]]
----------------------------------------------------------------------
__init__(r0, r1, r2, r3)
Constructor.
Initialize the matrix from 4 row vectors of double. Each vector is
expected to length 4. If it is too big, only the first 4 items will be
used. If it is too small, uninitialized elements will be filled in
with the corresponding elements from an identity matrix.
Parameters
----------
r0 : list[float]
r1 : list[float]
r2 : list[float]
r3 : list[float]
----------------------------------------------------------------------
__init__(r0, r1, r2, r3)
Constructor.
Initialize the matrix from 4 row vectors of float. Each vector is
expected to length 4. If it is too big, only the first 4 items will be
used. If it is too small, uninitialized elements will be filled in
with the corresponding elements from an identity matrix.
Parameters
----------
r0 : list[float]
r1 : list[float]
r2 : list[float]
r3 : list[float]
----------------------------------------------------------------------
__init__(rotate, translate)
Constructor.
Initializes a transformation matrix to perform the indicated rotation
and translation.
Parameters
----------
rotate : Rotation
translate : Vec3f
----------------------------------------------------------------------
__init__(rotmx, translate)
Constructor.
Initializes a transformation matrix to perform the indicated rotation
and translation.
Parameters
----------
rotmx : Matrix3f
translate : Vec3f
----------------------------------------------------------------------
__init__(m)
This explicit constructor converts a"double"matrix to a"float"matrix.
Parameters
----------
m : Matrix4d
"""
result["Matrix4f"].SetRow.func_doc = """SetRow(i, v) -> None
Sets a row of the matrix from a Vec4.
Parameters
----------
i : int
v : Vec4f
"""
result["Matrix4f"].SetColumn.func_doc = """SetColumn(i, v) -> None
Sets a column of the matrix from a Vec4.
Parameters
----------
i : int
v : Vec4f
"""
result["Matrix4f"].GetRow.func_doc = """GetRow(i) -> Vec4f
Gets a row of the matrix as a Vec4.
Parameters
----------
i : int
"""
result["Matrix4f"].GetColumn.func_doc = """GetColumn(i) -> Vec4f
Gets a column of the matrix as a Vec4.
Parameters
----------
i : int
"""
result["Matrix4f"].Set.func_doc = """Set(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) -> Matrix4f
Sets the matrix from 16 independent ``float`` values, specified in
row-major order.
For example, parameter *m10* specifies the value in row1 and column 0.
Parameters
----------
m00 : float
m01 : float
m02 : float
m03 : float
m10 : float
m11 : float
m12 : float
m13 : float
m20 : float
m21 : float
m22 : float
m23 : float
m30 : float
m31 : float
m32 : float
m33 : float
----------------------------------------------------------------------
Set(m) -> Matrix4f
Sets the matrix from a 4x4 array of ``float`` values, specified in
row-major order.
Parameters
----------
m : float
"""
result["Matrix4f"].SetIdentity.func_doc = """SetIdentity() -> Matrix4f
Sets the matrix to the identity matrix.
"""
result["Matrix4f"].SetZero.func_doc = """SetZero() -> Matrix4f
Sets the matrix to zero.
"""
result["Matrix4f"].SetDiagonal.func_doc = """SetDiagonal(s) -> Matrix4f
Sets the matrix to *s* times the identity matrix.
Parameters
----------
s : float
----------------------------------------------------------------------
SetDiagonal(arg1) -> Matrix4f
Sets the matrix to have diagonal ( ``v[0], v[1], v[2], v[3]`` ).
Parameters
----------
arg1 : Vec4f
"""
result["Matrix4f"].GetTranspose.func_doc = """GetTranspose() -> Matrix4f
Returns the transpose of the matrix.
"""
result["Matrix4f"].GetInverse.func_doc = """GetInverse(det, eps) -> Matrix4f
Returns the inverse of the matrix, or FLT_MAX \\* SetIdentity() if the
matrix is singular.
(FLT_MAX is the largest value a ``float`` can have, as defined by the
system.) The matrix is considered singular if the determinant is less
than or equal to the optional parameter *eps*. If *det* is non-null,
``\\*det`` is set to the determinant.
Parameters
----------
det : float
eps : float
"""
result["Matrix4f"].GetDeterminant.func_doc = """GetDeterminant() -> float
Returns the determinant of the matrix.
"""
result["Matrix4f"].SetRow3.func_doc = """SetRow3(i, v) -> None
Sets a row of the matrix from a Vec3.
The fourth element of the row is ignored.
Parameters
----------
i : int
v : Vec3f
"""
result["Matrix4f"].GetRow3.func_doc = """GetRow3(i) -> Vec3f
Gets a row of the matrix as a Vec3.
Parameters
----------
i : int
"""
result["Matrix4f"].GetDeterminant3.func_doc = """GetDeterminant3() -> float
Returns the determinant of the upper 3x3 matrix.
This method is useful when the matrix describes a linear
transformation such as a rotation or scale because the other values in
the 4x4 matrix are not important.
"""
result["Matrix4f"].HasOrthogonalRows3.func_doc = """HasOrthogonalRows3() -> bool
Returns true, if the row vectors of the upper 3x3 matrix form an
orthogonal basis.
Note they do not have to be unit length for this test to return true.
"""
result["Matrix4f"].Orthonormalize.func_doc = """Orthonormalize(issueWarning) -> bool
Makes the matrix orthonormal in place.
This is an iterative method that is much more stable than the previous
cross/cross method. If the iterative method does not converge, a
warning is issued.
Returns true if the iteration converged, false otherwise. Leaves any
translation part of the matrix unchanged. If *issueWarning* is true,
this method will issue a warning if the iteration does not converge,
otherwise it will be silent.
Parameters
----------
issueWarning : bool
"""
result["Matrix4f"].GetOrthonormalized.func_doc = """GetOrthonormalized(issueWarning) -> Matrix4f
Returns an orthonormalized copy of the matrix.
Parameters
----------
issueWarning : bool
"""
result["Matrix4f"].GetHandedness.func_doc = """GetHandedness() -> float
Returns the sign of the determinant of the upper 3x3 matrix, i.e.
1 for a right-handed matrix, -1 for a left-handed matrix, and 0 for a
singular matrix.
"""
result["Matrix4f"].IsRightHanded.func_doc = """IsRightHanded() -> bool
Returns true if the vectors in the upper 3x3 matrix form a right-
handed coordinate system.
"""
result["Matrix4f"].IsLeftHanded.func_doc = """IsLeftHanded() -> bool
Returns true if the vectors in the upper 3x3 matrix form a left-handed
coordinate system.
"""
result["Matrix4f"].RemoveScaleShear.func_doc = """RemoveScaleShear() -> Matrix4f
Returns the matrix with any scaling or shearing removed, leaving only
the rotation and translation.
If the matrix cannot be decomposed, returns the original matrix.
"""
result["MultiInterval"].__doc__ = """
GfMultiInterval represents a subset of the real number line as an
ordered set of non-intersecting GfIntervals.
"""
result["MultiInterval"].__init__.func_doc = """__init__()
----------------------------------------------------------------------
__init__(i)
Constructs an multi-interval with the single given interval.
Parameters
----------
i : Interval
----------------------------------------------------------------------
__init__(intervals)
Constructs an multi-interval containing the given input intervals.
Parameters
----------
intervals : list[Interval]
"""
result["MultiInterval"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns true if the multi-interval is empty.
"""
result["MultiInterval"].GetSize.func_doc = """GetSize() -> int
Returns the number of intervals in the set.
"""
result["MultiInterval"].GetBounds.func_doc = """GetBounds() -> Interval
Returns an interval bounding the entire multi-interval.
Returns an empty interval if the multi-interval is empty.
"""
result["MultiInterval"].Clear.func_doc = """Clear() -> None
Clear the multi-interval.
"""
result["MultiInterval"].Add.func_doc = """Add(i) -> None
Add the given interval to the multi-interval.
Parameters
----------
i : Interval
----------------------------------------------------------------------
Add(s) -> None
Add the given multi-interval to the multi-interval.
Sets this object to the union of the two sets.
Parameters
----------
s : MultiInterval
"""
result["MultiInterval"].ArithmeticAdd.func_doc = """ArithmeticAdd(i) -> None
Uses the given interval to extend the multi-interval in the interval
arithmetic sense.
Parameters
----------
i : Interval
"""
result["MultiInterval"].Remove.func_doc = """Remove(i) -> None
Remove the given interval from this multi-interval.
Parameters
----------
i : Interval
----------------------------------------------------------------------
Remove(s) -> None
Remove the given multi-interval from this multi-interval.
Parameters
----------
s : MultiInterval
"""
result["MultiInterval"].Intersect.func_doc = """Intersect(i) -> None
Parameters
----------
i : Interval
----------------------------------------------------------------------
Intersect(s) -> None
Parameters
----------
s : MultiInterval
"""
result["MultiInterval"].GetComplement.func_doc = """GetComplement() -> MultiInterval
Return the complement of this set.
"""
result["MultiInterval"].GetFullInterval.func_doc = """**classmethod** GetFullInterval() -> MultiInterval
Returns the full interval (-inf, inf).
"""
result["Plane"].__doc__ = """
Basic type: 3-dimensional plane
This class represents a three-dimensional plane as a normal vector and
the distance of the plane from the origin, measured along the normal.
The plane can also be used to represent a half-space: the side of the
plane in the direction of the normal.
"""
result["Plane"].__init__.func_doc = """__init__()
The default constructor leaves the plane parameters undefined.
----------------------------------------------------------------------
__init__(normal, distanceToOrigin)
This constructor sets this to the plane perpendicular to ``normal``
and at ``distance`` units from the origin.
The passed-in normal is normalized to unit length first.
Parameters
----------
normal : Vec3d
distanceToOrigin : float
----------------------------------------------------------------------
__init__(normal, point)
This constructor sets this to the plane perpendicular to ``normal``
and that passes through ``point`` .
The passed-in normal is normalized to unit length first.
Parameters
----------
normal : Vec3d
point : Vec3d
----------------------------------------------------------------------
__init__(p0, p1, p2)
This constructor sets this to the plane that contains the three given
points.
The normal is constructed from the cross product of ( ``p1`` - ``p0``
) ( ``p2`` - ``p0`` ). Results are undefined if the points are
collinear.
Parameters
----------
p0 : Vec3d
p1 : Vec3d
p2 : Vec3d
----------------------------------------------------------------------
__init__(eqn)
This constructor creates a plane given by the equation ``eqn`` [0] \\*
x + ``eqn`` [1] \\* y + ``eqn`` [2] \\* z + ``eqn`` [3] = 0.
Parameters
----------
eqn : Vec4d
"""
result["Plane"].Set.func_doc = """Set(normal, distanceToOrigin) -> None
Sets this to the plane perpendicular to ``normal`` and at ``distance``
units from the origin.
The passed-in normal is normalized to unit length first.
Parameters
----------
normal : Vec3d
distanceToOrigin : float
----------------------------------------------------------------------
Set(normal, point) -> None
This constructor sets this to the plane perpendicular to ``normal``
and that passes through ``point`` .
The passed-in normal is normalized to unit length first.
Parameters
----------
normal : Vec3d
point : Vec3d
----------------------------------------------------------------------
Set(p0, p1, p2) -> None
This constructor sets this to the plane that contains the three given
points.
The normal is constructed from the cross product of ( ``p1`` - ``p0``
) ( ``p2`` - ``p0`` ). Results are undefined if the points are
collinear.
Parameters
----------
p0 : Vec3d
p1 : Vec3d
p2 : Vec3d
----------------------------------------------------------------------
Set(eqn) -> None
This method sets this to the plane given by the equation ``eqn`` [0]
\\* x + ``eqn`` [1] \\* y + ``eqn`` [2] \\* z + ``eqn`` [3] = 0.
Parameters
----------
eqn : Vec4d
"""
result["Plane"].GetNormal.func_doc = """GetNormal() -> Vec3d
Returns the unit-length normal vector of the plane.
"""
result["Plane"].GetDistanceFromOrigin.func_doc = """GetDistanceFromOrigin() -> float
Returns the distance of the plane from the origin.
"""
result["Plane"].GetEquation.func_doc = """GetEquation() -> Vec4d
Give the coefficients of the equation of the plane.
Suitable to OpenGL calls to set the clipping plane.
"""
result["Plane"].GetDistance.func_doc = """GetDistance(p) -> float
Returns the distance of point ``from`` the plane.
This distance will be positive if the point is on the side of the
plane containing the normal.
Parameters
----------
p : Vec3d
"""
result["Plane"].Project.func_doc = """Project(p) -> Vec3d
Return the projection of ``p`` onto the plane.
Parameters
----------
p : Vec3d
"""
result["Plane"].Transform.func_doc = """Transform(matrix) -> Plane
Transforms the plane by the given matrix.
Parameters
----------
matrix : Matrix4d
"""
result["Plane"].Reorient.func_doc = """Reorient(p) -> None
Flip the plane normal (if necessary) so that ``p`` is in the positive
halfspace.
Parameters
----------
p : Vec3d
"""
result["Plane"].IntersectsPositiveHalfSpace.func_doc = """IntersectsPositiveHalfSpace(box) -> bool
Returns ``true`` if the given aligned bounding box is at least
partially on the positive side (the one the normal points into) of the
plane.
Parameters
----------
box : Range3d
----------------------------------------------------------------------
IntersectsPositiveHalfSpace(pt) -> bool
Returns true if the given point is on the plane or within its positive
half space.
Parameters
----------
pt : Vec3d
"""
result["Quatd"].__doc__ = """
Basic type: a quaternion, a complex number with a real coefficient and
three imaginary coefficients, stored as a 3-vector.
"""
result["Quatd"].__init__.func_doc = """__init__()
Default constructor leaves the quaternion undefined.
----------------------------------------------------------------------
__init__(realVal)
Initialize the real coefficient to ``realVal`` and the imaginary
coefficients to zero.
Since quaternions typically must be normalized, reasonable values for
``realVal`` are -1, 0, or 1. Other values are legal but are likely to
be meaningless.
Parameters
----------
realVal : float
----------------------------------------------------------------------
__init__(real, i, j, k)
Initialize the real and imaginary coefficients.
Parameters
----------
real : float
i : float
j : float
k : float
----------------------------------------------------------------------
__init__(real, imaginary)
Initialize the real and imaginary coefficients.
Parameters
----------
real : float
imaginary : Vec3d
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfQuatf.
Parameters
----------
other : Quatf
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfQuath.
Parameters
----------
other : Quath
"""
result["Quatd"].GetReal.func_doc = """GetReal() -> float
Return the real coefficient.
"""
result["Quatd"].SetReal.func_doc = """SetReal(real) -> None
Set the real coefficient.
Parameters
----------
real : float
"""
result["Quatd"].GetImaginary.func_doc = """GetImaginary() -> Vec3d
Return the imaginary coefficient.
"""
result["Quatd"].SetImaginary.func_doc = """SetImaginary(imaginary) -> None
Set the imaginary coefficients.
Parameters
----------
imaginary : Vec3d
----------------------------------------------------------------------
SetImaginary(i, j, k) -> None
Set the imaginary coefficients.
Parameters
----------
i : float
j : float
k : float
"""
result["Quatd"].GetLength.func_doc = """GetLength() -> float
Return geometric length of this quaternion.
"""
result["Quatd"].GetNormalized.func_doc = """GetNormalized(eps) -> Quatd
length of this quaternion is smaller than ``eps`` , return the
identity quaternion.
Parameters
----------
eps : float
"""
result["Quatd"].Normalize.func_doc = """Normalize(eps) -> float
Normalizes this quaternion in place to unit length, returning the
length before normalization.
If the length of this quaternion is smaller than ``eps`` , this sets
the quaternion to identity.
Parameters
----------
eps : float
"""
result["Quatd"].GetConjugate.func_doc = """GetConjugate() -> Quatd
Return this quaternion's conjugate, which is the quaternion with the
same real coefficient and negated imaginary coefficients.
"""
result["Quatd"].GetInverse.func_doc = """GetInverse() -> Quatd
Return this quaternion's inverse, or reciprocal.
This is the quaternion's conjugate divided by it's squared length.
"""
result["Quatd"].Transform.func_doc = """Transform(point) -> Vec3d
Transform the GfVec3d point.
If the quaternion is normalized, the transformation is a rotation.
Given a GfQuatd q, q.Transform(point) is equivalent to: (q \\*
GfQuatd(0, point) \\* q.GetInverse()).GetImaginary()
but is more efficient.
Parameters
----------
point : Vec3d
"""
result["Quatd"].GetZero.func_doc = """**classmethod** GetZero() -> Quatd
Return the zero quaternion, with real coefficient 0 and an imaginary
coefficients all zero.
"""
result["Quatd"].GetIdentity.func_doc = """**classmethod** GetIdentity() -> Quatd
Return the identity quaternion, with real coefficient 1 and an
imaginary coefficients all zero.
"""
result["Quaternion"].__init__.func_doc = """__init__()
The default constructor leaves the quaternion undefined.
----------------------------------------------------------------------
__init__(realVal)
This constructor initializes the real part to the argument and the
imaginary parts to zero.
Since quaternions typically need to be normalized, the only reasonable
values for ``realVal`` are -1, 0, or 1. Other values are legal but are
likely to be meaningless.
Parameters
----------
realVal : int
----------------------------------------------------------------------
__init__(real, imaginary)
This constructor initializes the real and imaginary parts.
Parameters
----------
real : float
imaginary : Vec3d
"""
result["Quaternion"].GetReal.func_doc = """GetReal() -> float
Returns the real part of the quaternion.
"""
result["Quaternion"].GetImaginary.func_doc = """GetImaginary() -> Vec3d
Returns the imaginary part of the quaternion.
"""
result["Quaternion"].GetLength.func_doc = """GetLength() -> float
Returns geometric length of this quaternion.
"""
result["Quaternion"].GetNormalized.func_doc = """GetNormalized(eps) -> Quaternion
Returns a normalized (unit-length) version of this quaternion.
direction as this. If the length of this quaternion is smaller than
``eps`` , this returns the identity quaternion.
Parameters
----------
eps : float
"""
result["Quaternion"].Normalize.func_doc = """Normalize(eps) -> float
Normalizes this quaternion in place to unit length, returning the
length before normalization.
If the length of this quaternion is smaller than ``eps`` , this sets
the quaternion to identity.
Parameters
----------
eps : float
"""
result["Quaternion"].GetInverse.func_doc = """GetInverse() -> Quaternion
Returns the inverse of this quaternion.
"""
result["Quaternion"].GetZero.func_doc = """**classmethod** GetZero() -> Quaternion
Returns the zero quaternion, which has a real part of 0 and an
imaginary part of (0,0,0).
"""
result["Quaternion"].GetIdentity.func_doc = """**classmethod** GetIdentity() -> Quaternion
Returns the identity quaternion, which has a real part of 1 and an
imaginary part of (0,0,0).
"""
result["Quatf"].__doc__ = """
Basic type: a quaternion, a complex number with a real coefficient and
three imaginary coefficients, stored as a 3-vector.
"""
result["Quatf"].__init__.func_doc = """__init__()
Default constructor leaves the quaternion undefined.
----------------------------------------------------------------------
__init__(realVal)
Initialize the real coefficient to ``realVal`` and the imaginary
coefficients to zero.
Since quaternions typically must be normalized, reasonable values for
``realVal`` are -1, 0, or 1. Other values are legal but are likely to
be meaningless.
Parameters
----------
realVal : float
----------------------------------------------------------------------
__init__(real, i, j, k)
Initialize the real and imaginary coefficients.
Parameters
----------
real : float
i : float
j : float
k : float
----------------------------------------------------------------------
__init__(real, imaginary)
Initialize the real and imaginary coefficients.
Parameters
----------
real : float
imaginary : Vec3f
----------------------------------------------------------------------
__init__(other)
Construct from GfQuatd.
Parameters
----------
other : Quatd
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfQuath.
Parameters
----------
other : Quath
"""
result["Quatf"].GetReal.func_doc = """GetReal() -> float
Return the real coefficient.
"""
result["Quatf"].SetReal.func_doc = """SetReal(real) -> None
Set the real coefficient.
Parameters
----------
real : float
"""
result["Quatf"].GetImaginary.func_doc = """GetImaginary() -> Vec3f
Return the imaginary coefficient.
"""
result["Quatf"].SetImaginary.func_doc = """SetImaginary(imaginary) -> None
Set the imaginary coefficients.
Parameters
----------
imaginary : Vec3f
----------------------------------------------------------------------
SetImaginary(i, j, k) -> None
Set the imaginary coefficients.
Parameters
----------
i : float
j : float
k : float
"""
result["Quatf"].GetLength.func_doc = """GetLength() -> float
Return geometric length of this quaternion.
"""
result["Quatf"].GetNormalized.func_doc = """GetNormalized(eps) -> Quatf
length of this quaternion is smaller than ``eps`` , return the
identity quaternion.
Parameters
----------
eps : float
"""
result["Quatf"].Normalize.func_doc = """Normalize(eps) -> float
Normalizes this quaternion in place to unit length, returning the
length before normalization.
If the length of this quaternion is smaller than ``eps`` , this sets
the quaternion to identity.
Parameters
----------
eps : float
"""
result["Quatf"].GetConjugate.func_doc = """GetConjugate() -> Quatf
Return this quaternion's conjugate, which is the quaternion with the
same real coefficient and negated imaginary coefficients.
"""
result["Quatf"].GetInverse.func_doc = """GetInverse() -> Quatf
Return this quaternion's inverse, or reciprocal.
This is the quaternion's conjugate divided by it's squared length.
"""
result["Quatf"].Transform.func_doc = """Transform(point) -> Vec3f
Transform the GfVec3f point.
If the quaternion is normalized, the transformation is a rotation.
Given a GfQuatf q, q.Transform(point) is equivalent to: (q \\*
GfQuatf(0, point) \\* q.GetInverse()).GetImaginary()
but is more efficient.
Parameters
----------
point : Vec3f
"""
result["Quatf"].GetZero.func_doc = """**classmethod** GetZero() -> Quatf
Return the zero quaternion, with real coefficient 0 and an imaginary
coefficients all zero.
"""
result["Quatf"].GetIdentity.func_doc = """**classmethod** GetIdentity() -> Quatf
Return the identity quaternion, with real coefficient 1 and an
imaginary coefficients all zero.
"""
result["Quath"].__doc__ = """
Basic type: a quaternion, a complex number with a real coefficient and
three imaginary coefficients, stored as a 3-vector.
"""
result["Quath"].__init__.func_doc = """__init__()
Default constructor leaves the quaternion undefined.
----------------------------------------------------------------------
__init__(realVal)
Initialize the real coefficient to ``realVal`` and the imaginary
coefficients to zero.
Since quaternions typically must be normalized, reasonable values for
``realVal`` are -1, 0, or 1. Other values are legal but are likely to
be meaningless.
Parameters
----------
realVal : GfHalf
----------------------------------------------------------------------
__init__(real, i, j, k)
Initialize the real and imaginary coefficients.
Parameters
----------
real : GfHalf
i : GfHalf
j : GfHalf
k : GfHalf
----------------------------------------------------------------------
__init__(real, imaginary)
Initialize the real and imaginary coefficients.
Parameters
----------
real : GfHalf
imaginary : Vec3h
----------------------------------------------------------------------
__init__(other)
Construct from GfQuatd.
Parameters
----------
other : Quatd
----------------------------------------------------------------------
__init__(other)
Construct from GfQuatf.
Parameters
----------
other : Quatf
"""
result["Quath"].GetReal.func_doc = """GetReal() -> GfHalf
Return the real coefficient.
"""
result["Quath"].SetReal.func_doc = """SetReal(real) -> None
Set the real coefficient.
Parameters
----------
real : GfHalf
"""
result["Quath"].GetImaginary.func_doc = """GetImaginary() -> Vec3h
Return the imaginary coefficient.
"""
result["Quath"].SetImaginary.func_doc = """SetImaginary(imaginary) -> None
Set the imaginary coefficients.
Parameters
----------
imaginary : Vec3h
----------------------------------------------------------------------
SetImaginary(i, j, k) -> None
Set the imaginary coefficients.
Parameters
----------
i : GfHalf
j : GfHalf
k : GfHalf
"""
result["Quath"].GetLength.func_doc = """GetLength() -> GfHalf
Return geometric length of this quaternion.
"""
result["Quath"].GetNormalized.func_doc = """GetNormalized(eps) -> Quath
length of this quaternion is smaller than ``eps`` , return the
identity quaternion.
Parameters
----------
eps : GfHalf
"""
result["Quath"].Normalize.func_doc = """Normalize(eps) -> GfHalf
Normalizes this quaternion in place to unit length, returning the
length before normalization.
If the length of this quaternion is smaller than ``eps`` , this sets
the quaternion to identity.
Parameters
----------
eps : GfHalf
"""
result["Quath"].GetConjugate.func_doc = """GetConjugate() -> Quath
Return this quaternion's conjugate, which is the quaternion with the
same real coefficient and negated imaginary coefficients.
"""
result["Quath"].GetInverse.func_doc = """GetInverse() -> Quath
Return this quaternion's inverse, or reciprocal.
This is the quaternion's conjugate divided by it's squared length.
"""
result["Quath"].Transform.func_doc = """Transform(point) -> Vec3h
Transform the GfVec3h point.
If the quaternion is normalized, the transformation is a rotation.
Given a GfQuath q, q.Transform(point) is equivalent to: (q \\*
GfQuath(0, point) \\* q.GetInverse()).GetImaginary()
but is more efficient.
Parameters
----------
point : Vec3h
"""
result["Quath"].GetZero.func_doc = """**classmethod** GetZero() -> Quath
Return the zero quaternion, with real coefficient 0 and an imaginary
coefficients all zero.
"""
result["Quath"].GetIdentity.func_doc = """**classmethod** GetIdentity() -> Quath
Return the identity quaternion, with real coefficient 1 and an
imaginary coefficients all zero.
"""
result["Range1d"].__doc__ = """
Basic type: 1-dimensional floating point range.
This class represents a 1-dimensional range (or interval) All
operations are component-wise and conform to interval mathematics. An
empty range is one where max<min. The default empty is
[FLT_MAX,-FLT_MAX]
"""
result["Range1d"].SetEmpty.func_doc = """SetEmpty() -> None
Sets the range to an empty interval.
"""
result["Range1d"].__init__.func_doc = """__init__()
The default constructor creates an empty range.
----------------------------------------------------------------------
__init__(min, max)
This constructor initializes the minimum and maximum points.
Parameters
----------
min : float
max : float
"""
result["Range1d"].GetMin.func_doc = """GetMin() -> float
Returns the minimum value of the range.
"""
result["Range1d"].GetMax.func_doc = """GetMax() -> float
Returns the maximum value of the range.
"""
result["Range1d"].GetSize.func_doc = """GetSize() -> float
Returns the size of the range.
"""
result["Range1d"].GetMidpoint.func_doc = """GetMidpoint() -> float
Returns the midpoint of the range, that is, 0.5\\*(min+max).
Note: this returns zero in the case of default-constructed ranges, or
ranges set via SetEmpty() .
"""
result["Range1d"].SetMin.func_doc = """SetMin(min) -> None
Sets the minimum value of the range.
Parameters
----------
min : float
"""
result["Range1d"].SetMax.func_doc = """SetMax(max) -> None
Sets the maximum value of the range.
Parameters
----------
max : float
"""
result["Range1d"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns whether the range is empty (max<min).
"""
result["Range1d"].Contains.func_doc = """Contains(point) -> bool
Returns true if the ``point`` is located inside the range.
As with all operations of this type, the range is assumed to include
its extrema.
Parameters
----------
point : float
----------------------------------------------------------------------
Contains(range) -> bool
Returns true if the ``range`` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include
their extrema.
Parameters
----------
range : Range1d
"""
result["Range1d"].UnionWith.func_doc = """UnionWith(b) -> Range1d
Extend ``this`` to include ``b`` .
Parameters
----------
b : Range1d
----------------------------------------------------------------------
UnionWith(b) -> Range1d
Extend ``this`` to include ``b`` .
Parameters
----------
b : float
"""
result["Range1d"].IntersectWith.func_doc = """IntersectWith(b) -> Range1d
Modifies this range to hold its intersection with ``b`` and returns
the result.
Parameters
----------
b : Range1d
"""
result["Range1d"].GetDistanceSquared.func_doc = """GetDistanceSquared(p) -> float
Compute the squared distance from a point to the range.
Parameters
----------
p : float
"""
result["Range1d"].GetUnion.func_doc = """**classmethod** GetUnion(a, b) -> Range1d
Returns the smallest ``GfRange1d`` which contains both ``a`` and ``b``
.
Parameters
----------
a : Range1d
b : Range1d
"""
result["Range1d"].GetIntersection.func_doc = """**classmethod** GetIntersection(a, b) -> Range1d
Returns a ``GfRange1d`` that describes the intersection of ``a`` and
``b`` .
Parameters
----------
a : Range1d
b : Range1d
"""
result["Range1f"].__doc__ = """
Basic type: 1-dimensional floating point range.
This class represents a 1-dimensional range (or interval) All
operations are component-wise and conform to interval mathematics. An
empty range is one where max<min. The default empty is
[FLT_MAX,-FLT_MAX]
"""
result["Range1f"].SetEmpty.func_doc = """SetEmpty() -> None
Sets the range to an empty interval.
"""
result["Range1f"].__init__.func_doc = """__init__()
The default constructor creates an empty range.
----------------------------------------------------------------------
__init__(min, max)
This constructor initializes the minimum and maximum points.
Parameters
----------
min : float
max : float
"""
result["Range1f"].GetMin.func_doc = """GetMin() -> float
Returns the minimum value of the range.
"""
result["Range1f"].GetMax.func_doc = """GetMax() -> float
Returns the maximum value of the range.
"""
result["Range1f"].GetSize.func_doc = """GetSize() -> float
Returns the size of the range.
"""
result["Range1f"].GetMidpoint.func_doc = """GetMidpoint() -> float
Returns the midpoint of the range, that is, 0.5\\*(min+max).
Note: this returns zero in the case of default-constructed ranges, or
ranges set via SetEmpty() .
"""
result["Range1f"].SetMin.func_doc = """SetMin(min) -> None
Sets the minimum value of the range.
Parameters
----------
min : float
"""
result["Range1f"].SetMax.func_doc = """SetMax(max) -> None
Sets the maximum value of the range.
Parameters
----------
max : float
"""
result["Range1f"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns whether the range is empty (max<min).
"""
result["Range1f"].Contains.func_doc = """Contains(point) -> bool
Returns true if the ``point`` is located inside the range.
As with all operations of this type, the range is assumed to include
its extrema.
Parameters
----------
point : float
----------------------------------------------------------------------
Contains(range) -> bool
Returns true if the ``range`` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include
their extrema.
Parameters
----------
range : Range1f
"""
result["Range1f"].UnionWith.func_doc = """UnionWith(b) -> Range1f
Extend ``this`` to include ``b`` .
Parameters
----------
b : Range1f
----------------------------------------------------------------------
UnionWith(b) -> Range1f
Extend ``this`` to include ``b`` .
Parameters
----------
b : float
"""
result["Range1f"].IntersectWith.func_doc = """IntersectWith(b) -> Range1f
Modifies this range to hold its intersection with ``b`` and returns
the result.
Parameters
----------
b : Range1f
"""
result["Range1f"].GetDistanceSquared.func_doc = """GetDistanceSquared(p) -> float
Compute the squared distance from a point to the range.
Parameters
----------
p : float
"""
result["Range1f"].GetUnion.func_doc = """**classmethod** GetUnion(a, b) -> Range1f
Returns the smallest ``GfRange1f`` which contains both ``a`` and ``b``
.
Parameters
----------
a : Range1f
b : Range1f
"""
result["Range1f"].GetIntersection.func_doc = """**classmethod** GetIntersection(a, b) -> Range1f
Returns a ``GfRange1f`` that describes the intersection of ``a`` and
``b`` .
Parameters
----------
a : Range1f
b : Range1f
"""
result["Range2d"].__doc__ = """
Basic type: 2-dimensional floating point range.
This class represents a 2-dimensional range (or interval) All
operations are component-wise and conform to interval mathematics. An
empty range is one where max<min. The default empty is
[FLT_MAX,-FLT_MAX]
"""
result["Range2d"].SetEmpty.func_doc = """SetEmpty() -> None
Sets the range to an empty interval.
"""
result["Range2d"].__init__.func_doc = """__init__()
The default constructor creates an empty range.
----------------------------------------------------------------------
__init__(min, max)
This constructor initializes the minimum and maximum points.
Parameters
----------
min : Vec2d
max : Vec2d
"""
result["Range2d"].GetMin.func_doc = """GetMin() -> Vec2d
Returns the minimum value of the range.
"""
result["Range2d"].GetMax.func_doc = """GetMax() -> Vec2d
Returns the maximum value of the range.
"""
result["Range2d"].GetSize.func_doc = """GetSize() -> Vec2d
Returns the size of the range.
"""
result["Range2d"].GetMidpoint.func_doc = """GetMidpoint() -> Vec2d
Returns the midpoint of the range, that is, 0.5\\*(min+max).
Note: this returns zero in the case of default-constructed ranges, or
ranges set via SetEmpty() .
"""
result["Range2d"].SetMin.func_doc = """SetMin(min) -> None
Sets the minimum value of the range.
Parameters
----------
min : Vec2d
"""
result["Range2d"].SetMax.func_doc = """SetMax(max) -> None
Sets the maximum value of the range.
Parameters
----------
max : Vec2d
"""
result["Range2d"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns whether the range is empty (max<min).
"""
result["Range2d"].Contains.func_doc = """Contains(point) -> bool
Returns true if the ``point`` is located inside the range.
As with all operations of this type, the range is assumed to include
its extrema.
Parameters
----------
point : Vec2d
----------------------------------------------------------------------
Contains(range) -> bool
Returns true if the ``range`` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include
their extrema.
Parameters
----------
range : Range2d
"""
result["Range2d"].UnionWith.func_doc = """UnionWith(b) -> Range2d
Extend ``this`` to include ``b`` .
Parameters
----------
b : Range2d
----------------------------------------------------------------------
UnionWith(b) -> Range2d
Extend ``this`` to include ``b`` .
Parameters
----------
b : Vec2d
"""
result["Range2d"].IntersectWith.func_doc = """IntersectWith(b) -> Range2d
Modifies this range to hold its intersection with ``b`` and returns
the result.
Parameters
----------
b : Range2d
"""
result["Range2d"].GetDistanceSquared.func_doc = """GetDistanceSquared(p) -> float
Compute the squared distance from a point to the range.
Parameters
----------
p : Vec2d
"""
result["Range2d"].GetCorner.func_doc = """GetCorner(i) -> Vec2d
Returns the ith corner of the range, in the following order: SW, SE,
NW, NE.
Parameters
----------
i : int
"""
result["Range2d"].GetQuadrant.func_doc = """GetQuadrant(i) -> Range2d
Returns the ith quadrant of the range, in the following order: SW, SE,
NW, NE.
Parameters
----------
i : int
"""
result["Range2d"].GetUnion.func_doc = """**classmethod** GetUnion(a, b) -> Range2d
Returns the smallest ``GfRange2d`` which contains both ``a`` and ``b``
.
Parameters
----------
a : Range2d
b : Range2d
"""
result["Range2d"].GetIntersection.func_doc = """**classmethod** GetIntersection(a, b) -> Range2d
Returns a ``GfRange2d`` that describes the intersection of ``a`` and
``b`` .
Parameters
----------
a : Range2d
b : Range2d
"""
result["Range2f"].__doc__ = """
Basic type: 2-dimensional floating point range.
This class represents a 2-dimensional range (or interval) All
operations are component-wise and conform to interval mathematics. An
empty range is one where max<min. The default empty is
[FLT_MAX,-FLT_MAX]
"""
result["Range2f"].SetEmpty.func_doc = """SetEmpty() -> None
Sets the range to an empty interval.
"""
result["Range2f"].__init__.func_doc = """__init__()
The default constructor creates an empty range.
----------------------------------------------------------------------
__init__(min, max)
This constructor initializes the minimum and maximum points.
Parameters
----------
min : Vec2f
max : Vec2f
"""
result["Range2f"].GetMin.func_doc = """GetMin() -> Vec2f
Returns the minimum value of the range.
"""
result["Range2f"].GetMax.func_doc = """GetMax() -> Vec2f
Returns the maximum value of the range.
"""
result["Range2f"].GetSize.func_doc = """GetSize() -> Vec2f
Returns the size of the range.
"""
result["Range2f"].GetMidpoint.func_doc = """GetMidpoint() -> Vec2f
Returns the midpoint of the range, that is, 0.5\\*(min+max).
Note: this returns zero in the case of default-constructed ranges, or
ranges set via SetEmpty() .
"""
result["Range2f"].SetMin.func_doc = """SetMin(min) -> None
Sets the minimum value of the range.
Parameters
----------
min : Vec2f
"""
result["Range2f"].SetMax.func_doc = """SetMax(max) -> None
Sets the maximum value of the range.
Parameters
----------
max : Vec2f
"""
result["Range2f"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns whether the range is empty (max<min).
"""
result["Range2f"].Contains.func_doc = """Contains(point) -> bool
Returns true if the ``point`` is located inside the range.
As with all operations of this type, the range is assumed to include
its extrema.
Parameters
----------
point : Vec2f
----------------------------------------------------------------------
Contains(range) -> bool
Returns true if the ``range`` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include
their extrema.
Parameters
----------
range : Range2f
"""
result["Range2f"].UnionWith.func_doc = """UnionWith(b) -> Range2f
Extend ``this`` to include ``b`` .
Parameters
----------
b : Range2f
----------------------------------------------------------------------
UnionWith(b) -> Range2f
Extend ``this`` to include ``b`` .
Parameters
----------
b : Vec2f
"""
result["Range2f"].IntersectWith.func_doc = """IntersectWith(b) -> Range2f
Modifies this range to hold its intersection with ``b`` and returns
the result.
Parameters
----------
b : Range2f
"""
result["Range2f"].GetDistanceSquared.func_doc = """GetDistanceSquared(p) -> float
Compute the squared distance from a point to the range.
Parameters
----------
p : Vec2f
"""
result["Range2f"].GetCorner.func_doc = """GetCorner(i) -> Vec2f
Returns the ith corner of the range, in the following order: SW, SE,
NW, NE.
Parameters
----------
i : int
"""
result["Range2f"].GetQuadrant.func_doc = """GetQuadrant(i) -> Range2f
Returns the ith quadrant of the range, in the following order: SW, SE,
NW, NE.
Parameters
----------
i : int
"""
result["Range2f"].GetUnion.func_doc = """**classmethod** GetUnion(a, b) -> Range2f
Returns the smallest ``GfRange2f`` which contains both ``a`` and ``b``
.
Parameters
----------
a : Range2f
b : Range2f
"""
result["Range2f"].GetIntersection.func_doc = """**classmethod** GetIntersection(a, b) -> Range2f
Returns a ``GfRange2f`` that describes the intersection of ``a`` and
``b`` .
Parameters
----------
a : Range2f
b : Range2f
"""
result["Range3d"].__doc__ = """
Basic type: 3-dimensional floating point range.
This class represents a 3-dimensional range (or interval) All
operations are component-wise and conform to interval mathematics. An
empty range is one where max<min. The default empty is
[FLT_MAX,-FLT_MAX]
"""
result["Range3d"].SetEmpty.func_doc = """SetEmpty() -> None
Sets the range to an empty interval.
"""
result["Range3d"].__init__.func_doc = """__init__()
The default constructor creates an empty range.
----------------------------------------------------------------------
__init__(min, max)
This constructor initializes the minimum and maximum points.
Parameters
----------
min : Vec3d
max : Vec3d
"""
result["Range3d"].GetMin.func_doc = """GetMin() -> Vec3d
Returns the minimum value of the range.
"""
result["Range3d"].GetMax.func_doc = """GetMax() -> Vec3d
Returns the maximum value of the range.
"""
result["Range3d"].GetSize.func_doc = """GetSize() -> Vec3d
Returns the size of the range.
"""
result["Range3d"].GetMidpoint.func_doc = """GetMidpoint() -> Vec3d
Returns the midpoint of the range, that is, 0.5\\*(min+max).
Note: this returns zero in the case of default-constructed ranges, or
ranges set via SetEmpty() .
"""
result["Range3d"].SetMin.func_doc = """SetMin(min) -> None
Sets the minimum value of the range.
Parameters
----------
min : Vec3d
"""
result["Range3d"].SetMax.func_doc = """SetMax(max) -> None
Sets the maximum value of the range.
Parameters
----------
max : Vec3d
"""
result["Range3d"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns whether the range is empty (max<min).
"""
result["Range3d"].Contains.func_doc = """Contains(point) -> bool
Returns true if the ``point`` is located inside the range.
As with all operations of this type, the range is assumed to include
its extrema.
Parameters
----------
point : Vec3d
----------------------------------------------------------------------
Contains(range) -> bool
Returns true if the ``range`` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include
their extrema.
Parameters
----------
range : Range3d
"""
result["Range3d"].UnionWith.func_doc = """UnionWith(b) -> Range3d
Extend ``this`` to include ``b`` .
Parameters
----------
b : Range3d
----------------------------------------------------------------------
UnionWith(b) -> Range3d
Extend ``this`` to include ``b`` .
Parameters
----------
b : Vec3d
"""
result["Range3d"].IntersectWith.func_doc = """IntersectWith(b) -> Range3d
Modifies this range to hold its intersection with ``b`` and returns
the result.
Parameters
----------
b : Range3d
"""
result["Range3d"].GetDistanceSquared.func_doc = """GetDistanceSquared(p) -> float
Compute the squared distance from a point to the range.
Parameters
----------
p : Vec3d
"""
result["Range3d"].GetCorner.func_doc = """GetCorner(i) -> Vec3d
Returns the ith corner of the range, in the following order: LDB, RDB,
LUB, RUB, LDF, RDF, LUF, RUF.
Where L/R is left/right, D/U is down/up, and B/F is back/front.
Parameters
----------
i : int
"""
result["Range3d"].GetOctant.func_doc = """GetOctant(i) -> Range3d
Returns the ith octant of the range, in the following order: LDB, RDB,
LUB, RUB, LDF, RDF, LUF, RUF.
Where L/R is left/right, D/U is down/up, and B/F is back/front.
Parameters
----------
i : int
"""
result["Range3d"].GetUnion.func_doc = """**classmethod** GetUnion(a, b) -> Range3d
Returns the smallest ``GfRange3d`` which contains both ``a`` and ``b``
.
Parameters
----------
a : Range3d
b : Range3d
"""
result["Range3d"].GetIntersection.func_doc = """**classmethod** GetIntersection(a, b) -> Range3d
Returns a ``GfRange3d`` that describes the intersection of ``a`` and
``b`` .
Parameters
----------
a : Range3d
b : Range3d
"""
result["Range3f"].__doc__ = """
Basic type: 3-dimensional floating point range.
This class represents a 3-dimensional range (or interval) All
operations are component-wise and conform to interval mathematics. An
empty range is one where max<min. The default empty is
[FLT_MAX,-FLT_MAX]
"""
result["Range3f"].SetEmpty.func_doc = """SetEmpty() -> None
Sets the range to an empty interval.
"""
result["Range3f"].__init__.func_doc = """__init__()
The default constructor creates an empty range.
----------------------------------------------------------------------
__init__(min, max)
This constructor initializes the minimum and maximum points.
Parameters
----------
min : Vec3f
max : Vec3f
"""
result["Range3f"].GetMin.func_doc = """GetMin() -> Vec3f
Returns the minimum value of the range.
"""
result["Range3f"].GetMax.func_doc = """GetMax() -> Vec3f
Returns the maximum value of the range.
"""
result["Range3f"].GetSize.func_doc = """GetSize() -> Vec3f
Returns the size of the range.
"""
result["Range3f"].GetMidpoint.func_doc = """GetMidpoint() -> Vec3f
Returns the midpoint of the range, that is, 0.5\\*(min+max).
Note: this returns zero in the case of default-constructed ranges, or
ranges set via SetEmpty() .
"""
result["Range3f"].SetMin.func_doc = """SetMin(min) -> None
Sets the minimum value of the range.
Parameters
----------
min : Vec3f
"""
result["Range3f"].SetMax.func_doc = """SetMax(max) -> None
Sets the maximum value of the range.
Parameters
----------
max : Vec3f
"""
result["Range3f"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns whether the range is empty (max<min).
"""
result["Range3f"].Contains.func_doc = """Contains(point) -> bool
Returns true if the ``point`` is located inside the range.
As with all operations of this type, the range is assumed to include
its extrema.
Parameters
----------
point : Vec3f
----------------------------------------------------------------------
Contains(range) -> bool
Returns true if the ``range`` is located entirely inside the range.
As with all operations of this type, the ranges are assumed to include
their extrema.
Parameters
----------
range : Range3f
"""
result["Range3f"].UnionWith.func_doc = """UnionWith(b) -> Range3f
Extend ``this`` to include ``b`` .
Parameters
----------
b : Range3f
----------------------------------------------------------------------
UnionWith(b) -> Range3f
Extend ``this`` to include ``b`` .
Parameters
----------
b : Vec3f
"""
result["Range3f"].IntersectWith.func_doc = """IntersectWith(b) -> Range3f
Modifies this range to hold its intersection with ``b`` and returns
the result.
Parameters
----------
b : Range3f
"""
result["Range3f"].GetDistanceSquared.func_doc = """GetDistanceSquared(p) -> float
Compute the squared distance from a point to the range.
Parameters
----------
p : Vec3f
"""
result["Range3f"].GetCorner.func_doc = """GetCorner(i) -> Vec3f
Returns the ith corner of the range, in the following order: LDB, RDB,
LUB, RUB, LDF, RDF, LUF, RUF.
Where L/R is left/right, D/U is down/up, and B/F is back/front.
Parameters
----------
i : int
"""
result["Range3f"].GetOctant.func_doc = """GetOctant(i) -> Range3f
Returns the ith octant of the range, in the following order: LDB, RDB,
LUB, RUB, LDF, RDF, LUF, RUF.
Where L/R is left/right, D/U is down/up, and B/F is back/front.
Parameters
----------
i : int
"""
result["Range3f"].GetUnion.func_doc = """**classmethod** GetUnion(a, b) -> Range3f
Returns the smallest ``GfRange3f`` which contains both ``a`` and ``b``
.
Parameters
----------
a : Range3f
b : Range3f
"""
result["Range3f"].GetIntersection.func_doc = """**classmethod** GetIntersection(a, b) -> Range3f
Returns a ``GfRange3f`` that describes the intersection of ``a`` and
``b`` .
Parameters
----------
a : Range3f
b : Range3f
"""
result["Ray"].__doc__ = """
Basic type: Ray used for intersection testing
This class represents a three-dimensional ray in space, typically used
for intersection testing. It consists of an origin and a direction.
Note that by default a ``GfRay`` does not normalize its direction
vector to unit length.
Note for ray intersections, the start point is included in the
computations, i.e., a distance of zero is defined to be intersecting.
"""
result["Ray"].__init__.func_doc = """__init__()
The default constructor leaves the ray parameters undefined.
----------------------------------------------------------------------
__init__(startPoint, direction)
This constructor takes a starting point and a direction.
Parameters
----------
startPoint : Vec3d
direction : Vec3d
"""
result["Ray"].SetPointAndDirection.func_doc = """SetPointAndDirection(startPoint, direction) -> None
Sets the ray by specifying a starting point and a direction.
Parameters
----------
startPoint : Vec3d
direction : Vec3d
"""
result["Ray"].SetEnds.func_doc = """SetEnds(startPoint, endPoint) -> None
Sets the ray by specifying a starting point and an ending point.
Parameters
----------
startPoint : Vec3d
endPoint : Vec3d
"""
result["Ray"].GetPoint.func_doc = """GetPoint(distance) -> Vec3d
Returns the point that is ``distance`` units from the starting point
along the direction vector, expressed in parametic distance.
Parameters
----------
distance : float
"""
result["Ray"].Transform.func_doc = """Transform(matrix) -> Ray
Transforms the ray by the given matrix.
Parameters
----------
matrix : Matrix4d
"""
result["Ray"].FindClosestPoint.func_doc = """FindClosestPoint(point, rayDistance) -> Vec3d
Returns the point on the ray that is closest to ``point`` .
If ``rayDistance`` is not ``None`` , it will be set to the parametric
distance along the ray of the closest point.
Parameters
----------
point : Vec3d
rayDistance : float
"""
result["Rect2i"].__doc__ = """
A 2D rectangle with integer coordinates.
A rectangle is internally represented as two corners. We refer to
these as the min and max corner where the min's x-coordinate and
y-coordinate are assumed to be less than or equal to the max's
corresponding coordinates. Normally, it is expressed as a min corner
and a size.
Note that the max corner is included when computing the size (width
and height) of a rectangle as the number of integral points in the x-
and y-direction. In particular, if the min corner and max corner are
the same, then the width and the height of the rectangle will both be
one since we have exactly one integral point with coordinates greater
or equal to the min corner and less or equal to the max corner.
Specifically, *width = maxX - minX + 1* and *height = maxY - minY +
1.*
"""
result["Rect2i"].__init__.func_doc = """__init__()
Constructs an empty rectangle.
----------------------------------------------------------------------
__init__(min, max)
Constructs a rectangle with ``min`` and ``max`` corners.
Parameters
----------
min : Vec2i
max : Vec2i
----------------------------------------------------------------------
__init__(min, width, height)
Constructs a rectangle with ``min`` corner and the indicated ``width``
and ``height`` .
Parameters
----------
min : Vec2i
width : int
height : int
"""
result["Rect2i"].IsNull.func_doc = """IsNull() -> bool
Returns true if the rectangle is a null rectangle.
A null rectangle has both the width and the height set to 0, that is
.. code-block:: text
GetMaxX() == GetMinX() - 1
and
.. code-block:: text
GetMaxY() == GetMinY() - 1
Remember that if ``GetMinX()`` and ``GetMaxX()`` return the same
value then the rectangle has width 1, and similarly for the height.
A null rectangle is both empty, and not valid.
"""
result["Rect2i"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns true if the rectangle is empty.
An empty rectangle has one or both of its min coordinates strictly
greater than the corresponding max coordinate.
An empty rectangle is not valid.
"""
result["Rect2i"].IsValid.func_doc = """IsValid() -> bool
Return true if the rectangle is valid (equivalently, not empty).
"""
result["Rect2i"].GetNormalized.func_doc = """GetNormalized() -> Rect2i
Returns a normalized rectangle, i.e.
one that has a non-negative width and height.
``GetNormalized()`` swaps the min and max x-coordinates to ensure a
non-negative width, and similarly for the y-coordinates.
"""
result["Rect2i"].GetMin.func_doc = """GetMin() -> Vec2i
Returns the min corner of the rectangle.
"""
result["Rect2i"].GetMax.func_doc = """GetMax() -> Vec2i
Returns the max corner of the rectangle.
"""
result["Rect2i"].GetMinX.func_doc = """GetMinX() -> int
Return the X value of min corner.
"""
result["Rect2i"].SetMinX.func_doc = """SetMinX(x) -> None
Set the X value of the min corner.
Parameters
----------
x : int
"""
result["Rect2i"].GetMaxX.func_doc = """GetMaxX() -> int
Return the X value of the max corner.
"""
result["Rect2i"].SetMaxX.func_doc = """SetMaxX(x) -> None
Set the X value of the max corner.
Parameters
----------
x : int
"""
result["Rect2i"].GetMinY.func_doc = """GetMinY() -> int
Return the Y value of the min corner.
"""
result["Rect2i"].SetMinY.func_doc = """SetMinY(y) -> None
Set the Y value of the min corner.
Parameters
----------
y : int
"""
result["Rect2i"].GetMaxY.func_doc = """GetMaxY() -> int
Return the Y value of the max corner.
"""
result["Rect2i"].SetMaxY.func_doc = """SetMaxY(y) -> None
Set the Y value of the max corner.
Parameters
----------
y : int
"""
result["Rect2i"].SetMin.func_doc = """SetMin(min) -> None
Sets the min corner of the rectangle.
Parameters
----------
min : Vec2i
"""
result["Rect2i"].SetMax.func_doc = """SetMax(max) -> None
Sets the max corner of the rectangle.
Parameters
----------
max : Vec2i
"""
result["Rect2i"].GetCenter.func_doc = """GetCenter() -> Vec2i
Returns the center point of the rectangle.
"""
result["Rect2i"].Translate.func_doc = """Translate(displacement) -> None
Move the rectangle by ``displ`` .
Parameters
----------
displacement : Vec2i
"""
result["Rect2i"].GetArea.func_doc = """GetArea() -> int
Return the area of the rectangle.
"""
result["Rect2i"].GetSize.func_doc = """GetSize() -> Vec2i
Returns the size of the rectangle as a vector (width,height).
"""
result["Rect2i"].GetWidth.func_doc = """GetWidth() -> int
Returns the width of the rectangle.
If the min and max x-coordinates are coincident, the width is one.
"""
result["Rect2i"].GetHeight.func_doc = """GetHeight() -> int
Returns the height of the rectangle.
If the min and max y-coordinates are coincident, the height is one.
"""
result["Rect2i"].GetIntersection.func_doc = """GetIntersection(that) -> Rect2i
Computes the intersection of two rectangles.
Parameters
----------
that : Rect2i
"""
result["Rect2i"].GetUnion.func_doc = """GetUnion(that) -> Rect2i
Computes the union of two rectangles.
Parameters
----------
that : Rect2i
"""
result["Rect2i"].Contains.func_doc = """Contains(p) -> bool
Returns true if the specified point in the rectangle.
Parameters
----------
p : Vec2i
"""
result["Rotation"].__init__.func_doc = """__init__()
The default constructor leaves the rotation undefined.
----------------------------------------------------------------------
__init__(axis, angle)
This constructor initializes the rotation to be ``angle`` degrees
about ``axis`` .
Parameters
----------
axis : Vec3d
angle : float
----------------------------------------------------------------------
__init__(quaternion)
This constructor initializes the rotation from a quaternion.
Parameters
----------
quaternion : Quaternion
----------------------------------------------------------------------
__init__(quat)
This constructor initializes the rotation from a quaternion.
Note that this constructor accepts GfQuatf and GfQuath since they
implicitly convert to GfQuatd.
Parameters
----------
quat : Quatd
----------------------------------------------------------------------
__init__(rotateFrom, rotateTo)
This constructor initializes the rotation to one that brings the
``rotateFrom`` vector to align with ``rotateTo`` .
The passed vectors need not be unit length.
Parameters
----------
rotateFrom : Vec3d
rotateTo : Vec3d
"""
result["Rotation"].SetAxisAngle.func_doc = """SetAxisAngle(axis, angle) -> Rotation
Sets the rotation to be ``angle`` degrees about ``axis`` .
Parameters
----------
axis : Vec3d
angle : float
"""
result["Rotation"].SetQuat.func_doc = """SetQuat(quat) -> Rotation
Sets the rotation from a quaternion.
Note that this method accepts GfQuatf and GfQuath since they
implicitly convert to GfQuatd.
Parameters
----------
quat : Quatd
"""
result["Rotation"].SetQuaternion.func_doc = """SetQuaternion(quat) -> Rotation
Sets the rotation from a quaternion.
Parameters
----------
quat : Quaternion
"""
result["Rotation"].SetRotateInto.func_doc = """SetRotateInto(rotateFrom, rotateTo) -> Rotation
Sets the rotation to one that brings the ``rotateFrom`` vector to
align with ``rotateTo`` .
The passed vectors need not be unit length.
Parameters
----------
rotateFrom : Vec3d
rotateTo : Vec3d
"""
result["Rotation"].SetIdentity.func_doc = """SetIdentity() -> Rotation
Sets the rotation to an identity rotation.
(This is chosen to be 0 degrees around the positive X axis.)
"""
result["Rotation"].GetAxis.func_doc = """GetAxis() -> Vec3d
Returns the axis of rotation.
"""
result["Rotation"].GetAngle.func_doc = """GetAngle() -> float
Returns the rotation angle in degrees.
"""
result["Rotation"].GetQuaternion.func_doc = """GetQuaternion() -> Quaternion
Returns the rotation expressed as a quaternion.
"""
result["Rotation"].GetQuat.func_doc = """GetQuat() -> Quatd
Returns the rotation expressed as a quaternion.
"""
result["Rotation"].GetInverse.func_doc = """GetInverse() -> Rotation
Returns the inverse of this rotation.
"""
result["Rotation"].Decompose.func_doc = """Decompose(axis0, axis1, axis2) -> Vec3d
Decompose rotation about 3 orthogonal axes.
If the axes are not orthogonal, warnings will be spewed.
Parameters
----------
axis0 : Vec3d
axis1 : Vec3d
axis2 : Vec3d
"""
result["Rotation"].TransformDir.func_doc = """TransformDir(vec) -> Vec3f
Transforms row vector ``vec`` by the rotation, returning the result.
Parameters
----------
vec : Vec3f
----------------------------------------------------------------------
TransformDir(vec) -> Vec3d
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
vec : Vec3d
"""
result["Rotation"].DecomposeRotation.func_doc = """**classmethod** DecomposeRotation(rot, TwAxis, FBAxis, LRAxis, handedness, thetaTw, thetaFB, thetaLR, thetaSw, useHint, swShift) -> None
Parameters
----------
rot : Matrix4d
TwAxis : Vec3d
FBAxis : Vec3d
LRAxis : Vec3d
handedness : float
thetaTw : float
thetaFB : float
thetaLR : float
thetaSw : float
useHint : bool
swShift : float
"""
result["Rotation"].RotateOntoProjected.func_doc = """**classmethod** RotateOntoProjected(v1, v2, axis) -> Rotation
Parameters
----------
v1 : Vec3d
v2 : Vec3d
axis : Vec3d
"""
result["Rotation"].MatchClosestEulerRotation.func_doc = """**classmethod** MatchClosestEulerRotation(targetTw, targetFB, targetLR, targetSw, thetaTw, thetaFB, thetaLR, thetaSw) -> None
Replace the hint angles with the closest rotation of the given
rotation to the hint.
Each angle in the rotation will be within Pi of the corresponding hint
angle and the sum of the differences with the hint will be minimized.
If a given rotation value is null then that angle will be treated as
0.0 and ignored in the calculations.
All angles are in radians. The rotation order is Tw/FB/LR/Sw.
Parameters
----------
targetTw : float
targetFB : float
targetLR : float
targetSw : float
thetaTw : float
thetaFB : float
thetaLR : float
thetaSw : float
"""
result["Size2"].__init__.func_doc = """__init__()
Default constructor initializes components to zero.
----------------------------------------------------------------------
__init__(o)
Copy constructor.
Parameters
----------
o : Size2
----------------------------------------------------------------------
__init__(o)
Conversion from GfVec2i.
Parameters
----------
o : Vec2i
----------------------------------------------------------------------
__init__(v)
Construct from an array.
Parameters
----------
v : int
----------------------------------------------------------------------
__init__(v0, v1)
Construct from two values.
Parameters
----------
v0 : int
v1 : int
"""
result["Size2"].Set.func_doc = """Set(v) -> Size2
Set to the values in a given array.
Parameters
----------
v : int
----------------------------------------------------------------------
Set(v0, v1) -> Size2
Set to values passed directly.
Parameters
----------
v0 : int
v1 : int
"""
result["Size3"].__init__.func_doc = """__init__()
Default constructor initializes components to zero.
----------------------------------------------------------------------
__init__(o)
Copy constructor.
Parameters
----------
o : Size3
----------------------------------------------------------------------
__init__(o)
Conversion from GfVec3i.
Parameters
----------
o : Vec3i
----------------------------------------------------------------------
__init__(v)
Construct from an array.
Parameters
----------
v : int
----------------------------------------------------------------------
__init__(v0, v1, v2)
Construct from three values.
Parameters
----------
v0 : int
v1 : int
v2 : int
"""
result["Size3"].Set.func_doc = """Set(v) -> Size3
Set to the values in ``v`` .
Parameters
----------
v : int
----------------------------------------------------------------------
Set(v0, v1, v2) -> Size3
Set to values passed directly.
Parameters
----------
v0 : int
v1 : int
v2 : int
"""
result["Transform"].__doc__ = """
Basic type: Compound linear transformation.
This class represents a linear transformation specified as a series of
individual components: a *translation*, a *rotation*, a *scale*, a
*pivotPosition*, and a *pivotOrientation*. When applied to a point,
the point will be transformed as follows (in order):
- Scaled by the *scale* with respect to *pivotPosition* and the
orientation specified by the *pivotOrientation*.
- Rotated by the *rotation* about *pivotPosition*.
- Translated by *Translation*
That is, the cumulative matrix that this represents looks like this.
.. code-block:: text
M = -P \\* -O \\* S \\* O \\* R \\* P \\* T
where
- *T* is the *translation* matrix
- *P* is the matrix that translates by *pivotPosition*
- *R* is the *rotation* matrix
- *O* is the matrix that rotates to *pivotOrientation*
- *S* is the *scale* matrix
"""
result["Transform"].SetMatrix.func_doc = """SetMatrix(m) -> Transform
Sets the transform components to implement the transformation
represented by matrix ``m`` , ignoring any projection.
This tries to leave the current center unchanged.
Parameters
----------
m : Matrix4d
"""
result["Transform"].SetIdentity.func_doc = """SetIdentity() -> Transform
Sets the transformation to the identity transformation.
"""
result["Transform"].SetScale.func_doc = """SetScale(scale) -> None
Sets the scale component, leaving all others untouched.
Parameters
----------
scale : Vec3d
"""
result["Transform"].SetPivotOrientation.func_doc = """SetPivotOrientation(pivotOrient) -> None
Sets the pivot orientation component, leaving all others untouched.
Parameters
----------
pivotOrient : Rotation
"""
result["Transform"].SetRotation.func_doc = """SetRotation(rotation) -> None
Sets the rotation component, leaving all others untouched.
Parameters
----------
rotation : Rotation
"""
result["Transform"].SetPivotPosition.func_doc = """SetPivotPosition(pivPos) -> None
Sets the pivot position component, leaving all others untouched.
Parameters
----------
pivPos : Vec3d
"""
result["Transform"].SetTranslation.func_doc = """SetTranslation(translation) -> None
Sets the translation component, leaving all others untouched.
Parameters
----------
translation : Vec3d
"""
result["Transform"].GetScale.func_doc = """GetScale() -> Vec3d
Returns the scale component.
"""
result["Transform"].GetPivotOrientation.func_doc = """GetPivotOrientation() -> Rotation
Returns the pivot orientation component.
"""
result["Transform"].GetRotation.func_doc = """GetRotation() -> Rotation
Returns the rotation component.
"""
result["Transform"].GetPivotPosition.func_doc = """GetPivotPosition() -> Vec3d
Returns the pivot position component.
"""
result["Transform"].GetTranslation.func_doc = """GetTranslation() -> Vec3d
Returns the translation component.
"""
result["Transform"].GetMatrix.func_doc = """GetMatrix() -> Matrix4d
Returns a ``GfMatrix4d`` that implements the cumulative
transformation.
"""
result["Vec2d"].__doc__ = """
Basic type for a vector of 2 double components.
Represents a vector of 2 components of type ``double`` . It is
intended to be fast and simple.
"""
result["Vec2d"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : float
----------------------------------------------------------------------
__init__(s0, s1)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : float
s1 : float
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec2f.
Parameters
----------
other : Vec2f
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec2h.
Parameters
----------
other : Vec2h
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec2i.
Parameters
----------
other : Vec2i
"""
result["Vec2d"].GetProjection.func_doc = """GetProjection(v) -> Vec2d
Returns the projection of ``this`` onto ``v`` .
That is:
.. code-block:: text
v \\* (\\*this \\* v)
Parameters
----------
v : Vec2d
"""
result["Vec2d"].GetComplement.func_doc = """GetComplement(b) -> Vec2d
Returns the orthogonal complement of ``this->GetProjection(b)`` .
That is:
.. code-block:: text
\\*this - this->GetProjection(b)
Parameters
----------
b : Vec2d
"""
result["Vec2d"].GetLength.func_doc = """GetLength() -> float
Length.
"""
result["Vec2d"].Normalize.func_doc = """Normalize(eps) -> float
Normalizes the vector in place to unit length, returning the length
before normalization.
If the length of the vector is smaller than ``eps`` , then the vector
is set to vector/ ``eps`` . The original length of the vector is
returned. See also GfNormalize() .
Parameters
----------
eps : float
"""
result["Vec2d"].GetNormalized.func_doc = """GetNormalized(eps) -> Vec2d
Parameters
----------
eps : float
"""
result["Vec2d"].XAxis.func_doc = """**classmethod** XAxis() -> Vec2d
Create a unit vector along the X-axis.
"""
result["Vec2d"].YAxis.func_doc = """**classmethod** YAxis() -> Vec2d
Create a unit vector along the Y-axis.
"""
result["Vec2d"].Axis.func_doc = """**classmethod** Axis(i) -> Vec2d
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 2.
Parameters
----------
i : int
"""
result["Vec2f"].__doc__ = """
Basic type for a vector of 2 float components.
Represents a vector of 2 components of type ``float`` . It is intended
to be fast and simple.
"""
result["Vec2f"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : float
----------------------------------------------------------------------
__init__(s0, s1)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : float
s1 : float
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
----------------------------------------------------------------------
__init__(other)
Construct from GfVec2d.
Parameters
----------
other : Vec2d
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec2h.
Parameters
----------
other : Vec2h
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec2i.
Parameters
----------
other : Vec2i
"""
result["Vec2f"].GetProjection.func_doc = """GetProjection(v) -> Vec2f
Returns the projection of ``this`` onto ``v`` .
That is:
.. code-block:: text
v \\* (\\*this \\* v)
Parameters
----------
v : Vec2f
"""
result["Vec2f"].GetComplement.func_doc = """GetComplement(b) -> Vec2f
Returns the orthogonal complement of ``this->GetProjection(b)`` .
That is:
.. code-block:: text
\\*this - this->GetProjection(b)
Parameters
----------
b : Vec2f
"""
result["Vec2f"].GetLength.func_doc = """GetLength() -> float
Length.
"""
result["Vec2f"].Normalize.func_doc = """Normalize(eps) -> float
Normalizes the vector in place to unit length, returning the length
before normalization.
If the length of the vector is smaller than ``eps`` , then the vector
is set to vector/ ``eps`` . The original length of the vector is
returned. See also GfNormalize() .
Parameters
----------
eps : float
"""
result["Vec2f"].GetNormalized.func_doc = """GetNormalized(eps) -> Vec2f
Parameters
----------
eps : float
"""
result["Vec2f"].XAxis.func_doc = """**classmethod** XAxis() -> Vec2f
Create a unit vector along the X-axis.
"""
result["Vec2f"].YAxis.func_doc = """**classmethod** YAxis() -> Vec2f
Create a unit vector along the Y-axis.
"""
result["Vec2f"].Axis.func_doc = """**classmethod** Axis(i) -> Vec2f
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 2.
Parameters
----------
i : int
"""
result["Vec2h"].__doc__ = """
Basic type for a vector of 2 GfHalf components.
Represents a vector of 2 components of type ``GfHalf`` . It is
intended to be fast and simple.
"""
result["Vec2h"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : GfHalf
----------------------------------------------------------------------
__init__(s0, s1)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : GfHalf
s1 : GfHalf
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
----------------------------------------------------------------------
__init__(other)
Construct from GfVec2d.
Parameters
----------
other : Vec2d
----------------------------------------------------------------------
__init__(other)
Construct from GfVec2f.
Parameters
----------
other : Vec2f
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec2i.
Parameters
----------
other : Vec2i
"""
result["Vec2h"].GetProjection.func_doc = """GetProjection(v) -> Vec2h
Returns the projection of ``this`` onto ``v`` .
That is:
.. code-block:: text
v \\* (\\*this \\* v)
Parameters
----------
v : Vec2h
"""
result["Vec2h"].GetComplement.func_doc = """GetComplement(b) -> Vec2h
Returns the orthogonal complement of ``this->GetProjection(b)`` .
That is:
.. code-block:: text
\\*this - this->GetProjection(b)
Parameters
----------
b : Vec2h
"""
result["Vec2h"].GetLength.func_doc = """GetLength() -> GfHalf
Length.
"""
result["Vec2h"].Normalize.func_doc = """Normalize(eps) -> GfHalf
Normalizes the vector in place to unit length, returning the length
before normalization.
If the length of the vector is smaller than ``eps`` , then the vector
is set to vector/ ``eps`` . The original length of the vector is
returned. See also GfNormalize() .
Parameters
----------
eps : GfHalf
"""
result["Vec2h"].GetNormalized.func_doc = """GetNormalized(eps) -> Vec2h
Parameters
----------
eps : GfHalf
"""
result["Vec2h"].XAxis.func_doc = """**classmethod** XAxis() -> Vec2h
Create a unit vector along the X-axis.
"""
result["Vec2h"].YAxis.func_doc = """**classmethod** YAxis() -> Vec2h
Create a unit vector along the Y-axis.
"""
result["Vec2h"].Axis.func_doc = """**classmethod** Axis(i) -> Vec2h
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 2.
Parameters
----------
i : int
"""
result["Vec2i"].__doc__ = """
Basic type for a vector of 2 int components.
Represents a vector of 2 components of type ``int`` . It is intended
to be fast and simple.
"""
result["Vec2i"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : int
----------------------------------------------------------------------
__init__(s0, s1)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : int
s1 : int
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
"""
result["Vec2i"].XAxis.func_doc = """**classmethod** XAxis() -> Vec2i
Create a unit vector along the X-axis.
"""
result["Vec2i"].YAxis.func_doc = """**classmethod** YAxis() -> Vec2i
Create a unit vector along the Y-axis.
"""
result["Vec2i"].Axis.func_doc = """**classmethod** Axis(i) -> Vec2i
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 2.
Parameters
----------
i : int
"""
result["Vec3d"].__doc__ = """
Basic type for a vector of 3 double components.
Represents a vector of 3 components of type ``double`` . It is
intended to be fast and simple.
"""
result["Vec3d"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : float
----------------------------------------------------------------------
__init__(s0, s1, s2)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : float
s1 : float
s2 : float
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec3f.
Parameters
----------
other : Vec3f
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec3h.
Parameters
----------
other : Vec3h
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec3i.
Parameters
----------
other : Vec3i
"""
result["Vec3d"].GetProjection.func_doc = """GetProjection(v) -> Vec3d
Returns the projection of ``this`` onto ``v`` .
That is:
.. code-block:: text
v \\* (\\*this \\* v)
Parameters
----------
v : Vec3d
"""
result["Vec3d"].GetComplement.func_doc = """GetComplement(b) -> Vec3d
Returns the orthogonal complement of ``this->GetProjection(b)`` .
That is:
.. code-block:: text
\\*this - this->GetProjection(b)
Parameters
----------
b : Vec3d
"""
result["Vec3d"].GetLength.func_doc = """GetLength() -> float
Length.
"""
result["Vec3d"].Normalize.func_doc = """Normalize(eps) -> float
Normalizes the vector in place to unit length, returning the length
before normalization.
If the length of the vector is smaller than ``eps`` , then the vector
is set to vector/ ``eps`` . The original length of the vector is
returned. See also GfNormalize() .
Parameters
----------
eps : float
"""
result["Vec3d"].GetNormalized.func_doc = """GetNormalized(eps) -> Vec3d
Parameters
----------
eps : float
"""
result["Vec3d"].BuildOrthonormalFrame.func_doc = """BuildOrthonormalFrame(v1, v2, eps) -> None
Sets ``v1`` and ``v2`` to unit vectors such that v1, v2 and \\*this
are mutually orthogonal.
If the length L of \\*this is smaller than ``eps`` , then v1 and v2
will have magnitude L/eps. As a result, the function delivers a
continuous result as \\*this shrinks in length.
Parameters
----------
v1 : Vec3d
v2 : Vec3d
eps : float
"""
result["Vec3d"].XAxis.func_doc = """**classmethod** XAxis() -> Vec3d
Create a unit vector along the X-axis.
"""
result["Vec3d"].YAxis.func_doc = """**classmethod** YAxis() -> Vec3d
Create a unit vector along the Y-axis.
"""
result["Vec3d"].ZAxis.func_doc = """**classmethod** ZAxis() -> Vec3d
Create a unit vector along the Z-axis.
"""
result["Vec3d"].Axis.func_doc = """**classmethod** Axis(i) -> Vec3d
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 3.
Parameters
----------
i : int
"""
result["Vec3d"].OrthogonalizeBasis.func_doc = """**classmethod** OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
Orthogonalize and optionally normalize a set of basis vectors.
This uses an iterative method that is very stable even when the
vectors are far from orthogonal (close to colinear). The number of
iterations and thus the computation time does increase as the vectors
become close to colinear, however. Returns a bool specifying whether
the solution converged after a number of iterations. If it did not
converge, the returned vectors will be as close as possible to
orthogonal within the iteration limit. Colinear vectors will be
unaltered, and the method will return false.
Parameters
----------
tx : Vec3d
ty : Vec3d
tz : Vec3d
normalize : bool
eps : float
"""
result["Vec3f"].__doc__ = """
Basic type for a vector of 3 float components.
Represents a vector of 3 components of type ``float`` . It is intended
to be fast and simple.
"""
result["Vec3f"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : float
----------------------------------------------------------------------
__init__(s0, s1, s2)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : float
s1 : float
s2 : float
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
----------------------------------------------------------------------
__init__(other)
Construct from GfVec3d.
Parameters
----------
other : Vec3d
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec3h.
Parameters
----------
other : Vec3h
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec3i.
Parameters
----------
other : Vec3i
"""
result["Vec3f"].GetProjection.func_doc = """GetProjection(v) -> Vec3f
Returns the projection of ``this`` onto ``v`` .
That is:
.. code-block:: text
v \\* (\\*this \\* v)
Parameters
----------
v : Vec3f
"""
result["Vec3f"].GetComplement.func_doc = """GetComplement(b) -> Vec3f
Returns the orthogonal complement of ``this->GetProjection(b)`` .
That is:
.. code-block:: text
\\*this - this->GetProjection(b)
Parameters
----------
b : Vec3f
"""
result["Vec3f"].GetLength.func_doc = """GetLength() -> float
Length.
"""
result["Vec3f"].Normalize.func_doc = """Normalize(eps) -> float
Normalizes the vector in place to unit length, returning the length
before normalization.
If the length of the vector is smaller than ``eps`` , then the vector
is set to vector/ ``eps`` . The original length of the vector is
returned. See also GfNormalize() .
Parameters
----------
eps : float
"""
result["Vec3f"].GetNormalized.func_doc = """GetNormalized(eps) -> Vec3f
Parameters
----------
eps : float
"""
result["Vec3f"].BuildOrthonormalFrame.func_doc = """BuildOrthonormalFrame(v1, v2, eps) -> None
Sets ``v1`` and ``v2`` to unit vectors such that v1, v2 and \\*this
are mutually orthogonal.
If the length L of \\*this is smaller than ``eps`` , then v1 and v2
will have magnitude L/eps. As a result, the function delivers a
continuous result as \\*this shrinks in length.
Parameters
----------
v1 : Vec3f
v2 : Vec3f
eps : float
"""
result["Vec3f"].XAxis.func_doc = """**classmethod** XAxis() -> Vec3f
Create a unit vector along the X-axis.
"""
result["Vec3f"].YAxis.func_doc = """**classmethod** YAxis() -> Vec3f
Create a unit vector along the Y-axis.
"""
result["Vec3f"].ZAxis.func_doc = """**classmethod** ZAxis() -> Vec3f
Create a unit vector along the Z-axis.
"""
result["Vec3f"].Axis.func_doc = """**classmethod** Axis(i) -> Vec3f
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 3.
Parameters
----------
i : int
"""
result["Vec3f"].OrthogonalizeBasis.func_doc = """**classmethod** OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
Orthogonalize and optionally normalize a set of basis vectors.
This uses an iterative method that is very stable even when the
vectors are far from orthogonal (close to colinear). The number of
iterations and thus the computation time does increase as the vectors
become close to colinear, however. Returns a bool specifying whether
the solution converged after a number of iterations. If it did not
converge, the returned vectors will be as close as possible to
orthogonal within the iteration limit. Colinear vectors will be
unaltered, and the method will return false.
Parameters
----------
tx : Vec3f
ty : Vec3f
tz : Vec3f
normalize : bool
eps : float
"""
result["Vec3h"].__doc__ = """
Basic type for a vector of 3 GfHalf components.
Represents a vector of 3 components of type ``GfHalf`` . It is
intended to be fast and simple.
"""
result["Vec3h"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : GfHalf
----------------------------------------------------------------------
__init__(s0, s1, s2)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : GfHalf
s1 : GfHalf
s2 : GfHalf
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
----------------------------------------------------------------------
__init__(other)
Construct from GfVec3d.
Parameters
----------
other : Vec3d
----------------------------------------------------------------------
__init__(other)
Construct from GfVec3f.
Parameters
----------
other : Vec3f
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec3i.
Parameters
----------
other : Vec3i
"""
result["Vec3h"].GetProjection.func_doc = """GetProjection(v) -> Vec3h
Returns the projection of ``this`` onto ``v`` .
That is:
.. code-block:: text
v \\* (\\*this \\* v)
Parameters
----------
v : Vec3h
"""
result["Vec3h"].GetComplement.func_doc = """GetComplement(b) -> Vec3h
Returns the orthogonal complement of ``this->GetProjection(b)`` .
That is:
.. code-block:: text
\\*this - this->GetProjection(b)
Parameters
----------
b : Vec3h
"""
result["Vec3h"].GetLength.func_doc = """GetLength() -> GfHalf
Length.
"""
result["Vec3h"].Normalize.func_doc = """Normalize(eps) -> GfHalf
Normalizes the vector in place to unit length, returning the length
before normalization.
If the length of the vector is smaller than ``eps`` , then the vector
is set to vector/ ``eps`` . The original length of the vector is
returned. See also GfNormalize() .
Parameters
----------
eps : GfHalf
"""
result["Vec3h"].GetNormalized.func_doc = """GetNormalized(eps) -> Vec3h
Parameters
----------
eps : GfHalf
"""
result["Vec3h"].BuildOrthonormalFrame.func_doc = """BuildOrthonormalFrame(v1, v2, eps) -> None
Sets ``v1`` and ``v2`` to unit vectors such that v1, v2 and \\*this
are mutually orthogonal.
If the length L of \\*this is smaller than ``eps`` , then v1 and v2
will have magnitude L/eps. As a result, the function delivers a
continuous result as \\*this shrinks in length.
Parameters
----------
v1 : Vec3h
v2 : Vec3h
eps : GfHalf
"""
result["Vec3h"].XAxis.func_doc = """**classmethod** XAxis() -> Vec3h
Create a unit vector along the X-axis.
"""
result["Vec3h"].YAxis.func_doc = """**classmethod** YAxis() -> Vec3h
Create a unit vector along the Y-axis.
"""
result["Vec3h"].ZAxis.func_doc = """**classmethod** ZAxis() -> Vec3h
Create a unit vector along the Z-axis.
"""
result["Vec3h"].Axis.func_doc = """**classmethod** Axis(i) -> Vec3h
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 3.
Parameters
----------
i : int
"""
result["Vec3h"].OrthogonalizeBasis.func_doc = """**classmethod** OrthogonalizeBasis(tx, ty, tz, normalize, eps) -> bool
Orthogonalize and optionally normalize a set of basis vectors.
This uses an iterative method that is very stable even when the
vectors are far from orthogonal (close to colinear). The number of
iterations and thus the computation time does increase as the vectors
become close to colinear, however. Returns a bool specifying whether
the solution converged after a number of iterations. If it did not
converge, the returned vectors will be as close as possible to
orthogonal within the iteration limit. Colinear vectors will be
unaltered, and the method will return false.
Parameters
----------
tx : Vec3h
ty : Vec3h
tz : Vec3h
normalize : bool
eps : float
"""
result["Vec3i"].__doc__ = """
Basic type for a vector of 3 int components.
Represents a vector of 3 components of type ``int`` . It is intended
to be fast and simple.
"""
result["Vec3i"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : int
----------------------------------------------------------------------
__init__(s0, s1, s2)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : int
s1 : int
s2 : int
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
"""
result["Vec3i"].XAxis.func_doc = """**classmethod** XAxis() -> Vec3i
Create a unit vector along the X-axis.
"""
result["Vec3i"].YAxis.func_doc = """**classmethod** YAxis() -> Vec3i
Create a unit vector along the Y-axis.
"""
result["Vec3i"].ZAxis.func_doc = """**classmethod** ZAxis() -> Vec3i
Create a unit vector along the Z-axis.
"""
result["Vec3i"].Axis.func_doc = """**classmethod** Axis(i) -> Vec3i
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 3.
Parameters
----------
i : int
"""
result["Vec4d"].__doc__ = """
Basic type for a vector of 4 double components.
Represents a vector of 4 components of type ``double`` . It is
intended to be fast and simple.
"""
result["Vec4d"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : float
----------------------------------------------------------------------
__init__(s0, s1, s2, s3)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : float
s1 : float
s2 : float
s3 : float
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec4f.
Parameters
----------
other : Vec4f
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec4h.
Parameters
----------
other : Vec4h
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec4i.
Parameters
----------
other : Vec4i
"""
result["Vec4d"].GetProjection.func_doc = """GetProjection(v) -> Vec4d
Returns the projection of ``this`` onto ``v`` .
That is:
.. code-block:: text
v \\* (\\*this \\* v)
Parameters
----------
v : Vec4d
"""
result["Vec4d"].GetComplement.func_doc = """GetComplement(b) -> Vec4d
Returns the orthogonal complement of ``this->GetProjection(b)`` .
That is:
.. code-block:: text
\\*this - this->GetProjection(b)
Parameters
----------
b : Vec4d
"""
result["Vec4d"].GetLength.func_doc = """GetLength() -> float
Length.
"""
result["Vec4d"].Normalize.func_doc = """Normalize(eps) -> float
Normalizes the vector in place to unit length, returning the length
before normalization.
If the length of the vector is smaller than ``eps`` , then the vector
is set to vector/ ``eps`` . The original length of the vector is
returned. See also GfNormalize() .
Parameters
----------
eps : float
"""
result["Vec4d"].GetNormalized.func_doc = """GetNormalized(eps) -> Vec4d
Parameters
----------
eps : float
"""
result["Vec4d"].XAxis.func_doc = """**classmethod** XAxis() -> Vec4d
Create a unit vector along the X-axis.
"""
result["Vec4d"].YAxis.func_doc = """**classmethod** YAxis() -> Vec4d
Create a unit vector along the Y-axis.
"""
result["Vec4d"].ZAxis.func_doc = """**classmethod** ZAxis() -> Vec4d
Create a unit vector along the Z-axis.
"""
result["Vec4d"].WAxis.func_doc = """**classmethod** WAxis() -> Vec4d
Create a unit vector along the W-axis.
"""
result["Vec4d"].Axis.func_doc = """**classmethod** Axis(i) -> Vec4d
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 4.
Parameters
----------
i : int
"""
result["Vec4f"].__doc__ = """
Basic type for a vector of 4 float components.
Represents a vector of 4 components of type ``float`` . It is intended
to be fast and simple.
"""
result["Vec4f"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : float
----------------------------------------------------------------------
__init__(s0, s1, s2, s3)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : float
s1 : float
s2 : float
s3 : float
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
----------------------------------------------------------------------
__init__(other)
Construct from GfVec4d.
Parameters
----------
other : Vec4d
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec4h.
Parameters
----------
other : Vec4h
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec4i.
Parameters
----------
other : Vec4i
"""
result["Vec4f"].GetProjection.func_doc = """GetProjection(v) -> Vec4f
Returns the projection of ``this`` onto ``v`` .
That is:
.. code-block:: text
v \\* (\\*this \\* v)
Parameters
----------
v : Vec4f
"""
result["Vec4f"].GetComplement.func_doc = """GetComplement(b) -> Vec4f
Returns the orthogonal complement of ``this->GetProjection(b)`` .
That is:
.. code-block:: text
\\*this - this->GetProjection(b)
Parameters
----------
b : Vec4f
"""
result["Vec4f"].GetLength.func_doc = """GetLength() -> float
Length.
"""
result["Vec4f"].Normalize.func_doc = """Normalize(eps) -> float
Normalizes the vector in place to unit length, returning the length
before normalization.
If the length of the vector is smaller than ``eps`` , then the vector
is set to vector/ ``eps`` . The original length of the vector is
returned. See also GfNormalize() .
Parameters
----------
eps : float
"""
result["Vec4f"].GetNormalized.func_doc = """GetNormalized(eps) -> Vec4f
Parameters
----------
eps : float
"""
result["Vec4f"].XAxis.func_doc = """**classmethod** XAxis() -> Vec4f
Create a unit vector along the X-axis.
"""
result["Vec4f"].YAxis.func_doc = """**classmethod** YAxis() -> Vec4f
Create a unit vector along the Y-axis.
"""
result["Vec4f"].ZAxis.func_doc = """**classmethod** ZAxis() -> Vec4f
Create a unit vector along the Z-axis.
"""
result["Vec4f"].WAxis.func_doc = """**classmethod** WAxis() -> Vec4f
Create a unit vector along the W-axis.
"""
result["Vec4f"].Axis.func_doc = """**classmethod** Axis(i) -> Vec4f
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 4.
Parameters
----------
i : int
"""
result["Vec4h"].__doc__ = """
Basic type for a vector of 4 GfHalf components.
Represents a vector of 4 components of type ``GfHalf`` . It is
intended to be fast and simple.
"""
result["Vec4h"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : GfHalf
----------------------------------------------------------------------
__init__(s0, s1, s2, s3)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : GfHalf
s1 : GfHalf
s2 : GfHalf
s3 : GfHalf
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
----------------------------------------------------------------------
__init__(other)
Construct from GfVec4d.
Parameters
----------
other : Vec4d
----------------------------------------------------------------------
__init__(other)
Construct from GfVec4f.
Parameters
----------
other : Vec4f
----------------------------------------------------------------------
__init__(other)
Implicitly convert from GfVec4i.
Parameters
----------
other : Vec4i
"""
result["Vec4h"].GetProjection.func_doc = """GetProjection(v) -> Vec4h
Returns the projection of ``this`` onto ``v`` .
That is:
.. code-block:: text
v \\* (\\*this \\* v)
Parameters
----------
v : Vec4h
"""
result["Vec4h"].GetComplement.func_doc = """GetComplement(b) -> Vec4h
Returns the orthogonal complement of ``this->GetProjection(b)`` .
That is:
.. code-block:: text
\\*this - this->GetProjection(b)
Parameters
----------
b : Vec4h
"""
result["Vec4h"].GetLength.func_doc = """GetLength() -> GfHalf
Length.
"""
result["Vec4h"].Normalize.func_doc = """Normalize(eps) -> GfHalf
Normalizes the vector in place to unit length, returning the length
before normalization.
If the length of the vector is smaller than ``eps`` , then the vector
is set to vector/ ``eps`` . The original length of the vector is
returned. See also GfNormalize() .
Parameters
----------
eps : GfHalf
"""
result["Vec4h"].GetNormalized.func_doc = """GetNormalized(eps) -> Vec4h
Parameters
----------
eps : GfHalf
"""
result["Vec4h"].XAxis.func_doc = """**classmethod** XAxis() -> Vec4h
Create a unit vector along the X-axis.
"""
result["Vec4h"].YAxis.func_doc = """**classmethod** YAxis() -> Vec4h
Create a unit vector along the Y-axis.
"""
result["Vec4h"].ZAxis.func_doc = """**classmethod** ZAxis() -> Vec4h
Create a unit vector along the Z-axis.
"""
result["Vec4h"].WAxis.func_doc = """**classmethod** WAxis() -> Vec4h
Create a unit vector along the W-axis.
"""
result["Vec4h"].Axis.func_doc = """**classmethod** Axis(i) -> Vec4h
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 4.
Parameters
----------
i : int
"""
result["Vec4i"].__doc__ = """
Basic type for a vector of 4 int components.
Represents a vector of 4 components of type ``int`` . It is intended
to be fast and simple.
"""
result["Vec4i"].__init__.func_doc = """__init__()
Default constructor does no initialization.
----------------------------------------------------------------------
__init__(value)
Initialize all elements to a single value.
Parameters
----------
value : int
----------------------------------------------------------------------
__init__(s0, s1, s2, s3)
Initialize all elements with explicit arguments.
Parameters
----------
s0 : int
s1 : int
s2 : int
s3 : int
----------------------------------------------------------------------
__init__(p)
Construct with pointer to values.
Parameters
----------
p : Scl
"""
result["Vec4i"].XAxis.func_doc = """**classmethod** XAxis() -> Vec4i
Create a unit vector along the X-axis.
"""
result["Vec4i"].YAxis.func_doc = """**classmethod** YAxis() -> Vec4i
Create a unit vector along the Y-axis.
"""
result["Vec4i"].ZAxis.func_doc = """**classmethod** ZAxis() -> Vec4i
Create a unit vector along the Z-axis.
"""
result["Vec4i"].WAxis.func_doc = """**classmethod** WAxis() -> Vec4i
Create a unit vector along the W-axis.
"""
result["Vec4i"].Axis.func_doc = """**classmethod** Axis(i) -> Vec4i
Create a unit vector along the i-th axis, zero-based.
Return the zero vector if ``i`` is greater than or equal to 4.
Parameters
----------
i : int
"""
result["DualQuatd"].__doc__ = """"""
result["DualQuatf"].__doc__ = """"""
result["DualQuath"].__doc__ = """"""
result["Matrix2d"].__doc__ = """"""
result["Matrix2f"].__doc__ = """"""
result["Matrix3d"].__doc__ = """"""
result["Matrix3f"].__doc__ = """"""
result["Matrix4d"].__doc__ = """"""
result["Matrix4f"].__doc__ = """"""
result["Quatd"].__doc__ = """"""
result["Quatf"].__doc__ = """"""
result["Quath"].__doc__ = """"""
result["Rect2i"].__doc__ = """"""
result["Transform"].__doc__ = """"""
result["Vec2d"].__doc__ = """"""
result["Vec2f"].__doc__ = """"""
result["Vec2h"].__doc__ = """"""
result["Vec2i"].__doc__ = """"""
result["Vec3d"].__doc__ = """"""
result["Vec3f"].__doc__ = """"""
result["Vec3h"].__doc__ = """"""
result["Vec3i"].__doc__ = """"""
result["Vec4d"].__doc__ = """"""
result["Vec4f"].__doc__ = """"""
result["Vec4h"].__doc__ = """"""
result["Vec4i"].__doc__ = """"""
result["GetHomogenized"].func_doc = """GetHomogenized(v) -> Vec4f
Returns a vector which is ``v`` homogenized.
If the fourth element of ``v`` is 0, it is set to 1.
Parameters
----------
v : Vec4f
"""
result["HomogeneousCross"].func_doc = """HomogeneousCross(a, b) -> Vec4f
Homogenizes ``a`` and ``b`` and then performs the cross product on the
first three elements of each.
Returns the cross product as a homogenized vector.
Parameters
----------
a : Vec4f
b : Vec4f
----------------------------------------------------------------------
HomogeneousCross(a, b) -> Vec4d
Homogenizes ``a`` and ``b`` and then performs the cross product on the
first three elements of each.
Returns the cross product as a homogenized vector.
Parameters
----------
a : Vec4d
b : Vec4d
"""
result["MultiInterval"].__doc__ = """"""
result["IsClose"].func_doc = """IsClose(a, b, epsilon) -> bool
Returns true if ``a`` and ``b`` are with ``epsilon`` of each other.
Parameters
----------
a : float
b : float
epsilon : float
"""
result["RadiansToDegrees"].func_doc = """RadiansToDegrees(radians) -> float
Converts an angle in radians to degrees.
Parameters
----------
radians : float
"""
result["DegreesToRadians"].func_doc = """DegreesToRadians(degrees) -> float
Converts an angle in degrees to radians.
Parameters
----------
degrees : float
"""
result["Sqr"].func_doc = """Sqr(x) -> float
Returns the inner product of ``x`` with itself: specifically,
``x\\*x`` .
Defined for ``int`` , ``float`` , ``double`` , and all ``GfVec``
types.
Parameters
----------
x : T
"""
result["Sgn"].func_doc = """Sgn(v) -> T
Return the signum of ``v`` (i.e.
\\-1, 0, or 1).
The type ``T`` must implement the<and>operators; the function returns
zero only if value neither positive, nor negative.
Parameters
----------
v : T
"""
result["Sqrt"].func_doc = """Sqrt(f) -> float
Return sqrt( ``f`` ).
Parameters
----------
f : float
----------------------------------------------------------------------
Sqrt(f) -> float
Return sqrt( ``f`` ).
Parameters
----------
f : float
"""
result["Exp"].func_doc = """Exp(f) -> float
Return exp( ``f`` ).
Parameters
----------
f : float
----------------------------------------------------------------------
Exp(f) -> float
Return exp( ``f`` ).
Parameters
----------
f : float
"""
result["Log"].func_doc = """Log(f) -> float
Return log( ``f`` ).
Parameters
----------
f : float
----------------------------------------------------------------------
Log(f) -> float
Return log( ``f`` ).
Parameters
----------
f : float
"""
result["Floor"].func_doc = """Floor(f) -> float
Return floor( ``f`` ).
Parameters
----------
f : float
----------------------------------------------------------------------
Floor(f) -> float
Return floor( ``f`` ).
Parameters
----------
f : float
"""
result["Ceil"].func_doc = """Ceil(f) -> float
Return ceil( ``f`` ).
Parameters
----------
f : float
----------------------------------------------------------------------
Ceil(f) -> float
Return ceil( ``f`` ).
Parameters
----------
f : float
"""
result["Abs"].func_doc = """Abs(f) -> float
Return abs( ``f`` ).
Parameters
----------
f : float
----------------------------------------------------------------------
Abs(f) -> float
Return abs( ``f`` ).
Parameters
----------
f : float
"""
result["Round"].func_doc = """Round(f) -> float
Return round( ``f`` ).
Parameters
----------
f : float
----------------------------------------------------------------------
Round(f) -> float
Return round( ``f`` ).
Parameters
----------
f : float
"""
result["Pow"].func_doc = """Pow(f, p) -> float
Return pow( ``f`` , ``p`` ).
Parameters
----------
f : float
p : float
----------------------------------------------------------------------
Pow(f, p) -> float
Return pow( ``f`` , ``p`` ).
Parameters
----------
f : float
p : float
"""
result["Clamp"].func_doc = """Clamp(value, min, max) -> float
Return the resulting of clamping ``value`` to lie between ``min`` and
``max`` .
This function is also defined for GfVecs.
Parameters
----------
value : float
min : float
max : float
----------------------------------------------------------------------
Clamp(value, min, max) -> float
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
value : float
min : float
max : float
"""
result["Mod"].func_doc = """Mod(a, b) -> float
The mod function with"correct"behaviour for negative numbers.
If ``a`` = ``n`` ``b`` for some integer ``n`` , zero is returned.
Otherwise, for positive ``a`` , the value returned is ``fmod(a,b)`` ,
and for negative ``a`` , the value returned is ``fmod(a,b)+b`` .
Parameters
----------
a : float
b : float
"""
result["Lerp"].func_doc = """Lerp(alpha, a, b) -> T
Linear interpolation function.
For any type that supports multiplication by a scalar and binary
addition, returns
.. code-block:: text
(1-alpha) \\* a + alpha \\* b
Parameters
----------
alpha : float
a : T
b : T
"""
result["Min"].func_doc = """Min(a1, a2) -> T
Returns the smallest of the given ``values`` .
Parameters
----------
a1 : T
a2 : T
"""
result["Max"].func_doc = """Max(a1, a2) -> T
Returns the largest of the given ``values`` .
Parameters
----------
a1 : T
a2 : T
"""
result["Dot"].func_doc = """Dot(left, right) -> decltype(declval[Left]() declval[Right]())
Returns the dot (inner) product of two vectors.
For scalar types, this is just the regular product.
Parameters
----------
left : Left
right : Right
"""
result["CompMult"].func_doc = """CompMult(left, right) -> decltype(declval[Left]() declval[Right]())
Returns component-wise multiplication of vectors.
For scalar types, this is just the regular product.
Parameters
----------
left : Left
right : Right
"""
result["CompDiv"].func_doc = """CompDiv(left, right) -> decltype(declval[Left]()/declval[Right]())
Returns component-wise quotient of vectors.
For scalar types, this is just the regular quotient.
Parameters
----------
left : Left
right : Right
"""
result["Camera"].__doc__ = """"""
result["Plane"].__doc__ = """"""
result["Range1d"].__doc__ = """"""
result["Range1f"].__doc__ = """"""
result["Range2d"].__doc__ = """"""
result["Range2f"].__doc__ = """"""
result["Range3d"].__doc__ = """"""
result["Range3f"].__doc__ = """"""
result["Ray"].__doc__ = """"""
result["Camera"].focalLength = property(result["Camera"].focalLength.fget, result["Camera"].focalLength.fset, result["Camera"].focalLength.fdel, """type : float
Returns the focal length in tenths of a world unit (e.g., mm if the
world unit is assumed to be cm).
----------------------------------------------------------------------
type : None
These are the values actually stored in the class and they correspond
to measurements of an actual physical camera (in mm).
Together with the clipping range, they determine the camera frustum.
Sets the focal length in tenths of a world unit (e.g., mm if the world
unit is assumed to be cm).
""")
result["Camera"].horizontalAperture = property(result["Camera"].horizontalAperture.fget, result["Camera"].horizontalAperture.fset, result["Camera"].horizontalAperture.fdel, """type : float
Returns the width of the projector aperture in tenths of a world unit
(e.g., mm if the world unit is assumed to be cm).
----------------------------------------------------------------------
type : None
Sets the width of the projector aperture in tenths of a world unit
(e.g., mm if the world unit is assumed to be cm).
""")
result["Camera"].verticalAperture = property(result["Camera"].verticalAperture.fget, result["Camera"].verticalAperture.fset, result["Camera"].verticalAperture.fdel, """type : float
Returns the height of the projector aperture in tenths of a world unit
(e.g., mm if the world unit is assumed to be cm).
----------------------------------------------------------------------
type : None
Sets the height of the projector aperture in tenths of a world unit
(e.g., mm if the world unit is assumed to be cm).
""")
result["Camera"].horizontalApertureOffset = property(result["Camera"].horizontalApertureOffset.fget, result["Camera"].horizontalApertureOffset.fset, result["Camera"].horizontalApertureOffset.fdel, """type : float
Returns the horizontal offset of the projector aperture in tenths of a
world unit (e.g., mm if the world unit is assumed to be cm).
In particular, an offset is necessary when writing out a stereo camera
with finite convergence distance as two cameras.
----------------------------------------------------------------------
type : None
Sets the horizontal offset of the projector aperture in tenths of a
world unit (e.g., mm if the world unit is assumed to be cm).
""")
result["Camera"].verticalApertureOffset = property(result["Camera"].verticalApertureOffset.fget, result["Camera"].verticalApertureOffset.fset, result["Camera"].verticalApertureOffset.fdel, """type : float
Returns the vertical offset of the projector aperture in tenths of a
world unit (e.g., mm if the world unit is assumed to be cm).
----------------------------------------------------------------------
type : None
Sets the vertical offset of the projector aperture in tenths of a
world unit (e.g., mm if the world unit is assumed to be cm).
""")
result["Camera"].transform = property(result["Camera"].transform.fget, result["Camera"].transform.fset, result["Camera"].transform.fdel, """type : Matrix4d
Returns the transform of the filmback in world space.
This is exactly the transform specified via SetTransform() .
----------------------------------------------------------------------
type : None
Sets the transform of the filmback in world space to ``val`` .
""")
result["Camera"].projection = property(result["Camera"].projection.fget, result["Camera"].projection.fset, result["Camera"].projection.fdel, """type : Projection
Returns the projection type.
----------------------------------------------------------------------
type : None
Sets the projection type.
""")
result["Camera"].clippingRange = property(result["Camera"].clippingRange.fget, result["Camera"].clippingRange.fset, result["Camera"].clippingRange.fdel, """type : Range1f
Returns the clipping range in world units.
----------------------------------------------------------------------
type : None
Sets the clipping range in world units.
""")
result["Camera"].clippingPlanes = property(result["Camera"].clippingPlanes.fget, result["Camera"].clippingPlanes.fset, result["Camera"].clippingPlanes.fdel, """type : list[Vec4f]
Returns additional clipping planes.
----------------------------------------------------------------------
type : None
Sets additional arbitrarily oriented clipping planes.
A vector (a,b,c,d) encodes a clipping plane that clips off points
(x,y,z) with a \\* x + b \\* y + c \\* z + d \\* 1<0
where (x,y,z) are the coordinates in the camera's space.
""")
result["Camera"].fStop = property(result["Camera"].fStop.fget, result["Camera"].fStop.fset, result["Camera"].fStop.fdel, """type : float
Returns the lens aperture.
----------------------------------------------------------------------
type : None
Sets the lens aperture, unitless.
""")
result["Camera"].focusDistance = property(result["Camera"].focusDistance.fget, result["Camera"].focusDistance.fset, result["Camera"].focusDistance.fdel, """type : float
Returns the focus distance in world units.
----------------------------------------------------------------------
type : None
Sets the focus distance in world units.
""")
result["Camera"].aspectRatio = property(result["Camera"].aspectRatio.fget, result["Camera"].aspectRatio.fset, result["Camera"].aspectRatio.fdel, """type : float
Returns the projector aperture aspect ratio.
""")
result["Camera"].frustum = property(result["Camera"].frustum.fget, result["Camera"].frustum.fset, result["Camera"].frustum.fdel, """type : Frustum
Returns the computed, world-space camera frustum.
The frustum will always be that of a Y-up, -Z-looking camera.
""")
result["Quaternion"].real = property(result["Quaternion"].real.fget, result["Quaternion"].real.fset, result["Quaternion"].real.fdel, """type : None
Sets the real part of the quaternion.
""")
result["Quaternion"].imaginary = property(result["Quaternion"].imaginary.fget, result["Quaternion"].imaginary.fset, result["Quaternion"].imaginary.fdel, """type : None
Sets the imaginary part of the quaternion.
""")
result["Ray"].startPoint = property(result["Ray"].startPoint.fget, result["Ray"].startPoint.fset, result["Ray"].startPoint.fdel, """type : Vec3d
Returns the starting point of the segment.
""")
result["Ray"].direction = property(result["Ray"].direction.fget, result["Ray"].direction.fset, result["Ray"].direction.fdel, """type : Vec3d
Returns the direction vector of the segment.
This is not guaranteed to be unit length.
""") | 212,405 | Python | 15.32511 | 228 | 0.608983 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Garch/__DOC.py | def Execute(result):
result["GLPlatformDebugContext"].__doc__ = """
Platform specific context (e.g. X11/GLX) which supports debug output.
"""
result["GLPlatformDebugContext"].makeCurrent.func_doc = """makeCurrent() -> None
"""
result["GLPlatformDebugContext"].__init__.func_doc = """__init__(majorVersion, minorVersion, coreProfile, directRenderering)
Parameters
----------
majorVersion : int
minorVersion : int
coreProfile : bool
directRenderering : bool
""" | 479 | Python | 18.199999 | 127 | 0.697286 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Pcp/__DOC.py | def Execute(result):
result["Cache"].__doc__ = """
PcpCache is the context required to make requests of the Pcp
composition algorithm and cache the results.
Because the algorithms are recursive making a request typically makes
other internal requests to solve subproblems caching subproblem
results is required for reasonable performance, and so this cache is
the only entrypoint to the algorithms.
There is a set of parameters that affect the composition results:
- variant fallbacks: per named variant set, an ordered list of
fallback values to use when composing a prim that defines a variant
set but does not specify a selection
- payload inclusion set: an SdfPath set used to identify which
prims should have their payloads included during composition; this is
the basis for explicit control over the"working set"of composition
- file format target: the file format target that Pcp will request
when opening scene description layers
- "USD mode"configures the Pcp composition algorithm to provide
only a custom, lighter subset of the full feature set, as needed by
the Universal Scene Description system
There are a number of different computations that can be requested.
These include computing a layer stack from a PcpLayerStackIdentifier,
computing a prim index or prim stack, and computing a property index.
"""
result["Cache"].GetLayerStackIdentifier.func_doc = """GetLayerStackIdentifier() -> LayerStackIdentifier
Get the identifier of the layerStack used for composition.
"""
result["Cache"].HasRootLayerStack.func_doc = """HasRootLayerStack(layerStack) -> bool
Return true if this cache's root layer stack is ``layerStack`` , false
otherwise.
This is functionally equivalent to comparing against the result of
GetLayerStack() , but does not require constructing a TfWeakPtr or any
refcount operations.
Parameters
----------
layerStack : LayerStack
----------------------------------------------------------------------
HasRootLayerStack(layerStack) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
layerStack : LayerStack
"""
result["Cache"].GetVariantFallbacks.func_doc = """GetVariantFallbacks() -> PcpVariantFallbackMap
Get the list of fallbacks to attempt to use when evaluating variant
sets that lack an authored selection.
"""
result["Cache"].SetVariantFallbacks.func_doc = """SetVariantFallbacks(map, changes) -> None
Set the list of fallbacks to attempt to use when evaluating variant
sets that lack an authored selection.
If ``changes`` is not ``None`` then it's adjusted to reflect the
changes necessary to see the change in standin preferences, otherwise
those changes are applied immediately.
Parameters
----------
map : PcpVariantFallbackMap
changes : PcpChanges
"""
result["Cache"].IsPayloadIncluded.func_doc = """IsPayloadIncluded(path) -> bool
Return true if the payload is included for the given path.
Parameters
----------
path : Path
"""
result["Cache"].RequestPayloads.func_doc = """RequestPayloads(pathsToInclude, pathsToExclude, changes) -> None
Request payloads to be included or excluded from composition.
pathsToInclude
is a set of paths to add to the set for payload inclusion.
pathsToExclude
is a set of paths to remove from the set for payload inclusion.
changes
if not ``None`` , is adjusted to reflect the changes necessary to see
the change in payloads; otherwise those changes are applied
immediately.
If a path is listed in both pathsToInclude and pathsToExclude, it will
be treated as an inclusion only.
Parameters
----------
pathsToInclude : SdfPathSet
pathsToExclude : SdfPathSet
changes : PcpChanges
"""
result["Cache"].RequestLayerMuting.func_doc = """RequestLayerMuting(layersToMute, layersToUnmute, changes, newLayersMuted, newLayersUnmuted) -> None
Request layers to be muted or unmuted in this cache.
Muted layers are ignored during composition and do not appear in any
layer stacks. The root layer of this stage may not be muted;
attempting to do so will generate a coding error. If the root layer of
a reference or payload layer stack is muted, the behavior is as if the
muted layer did not exist, which means a composition error will be
generated.
A canonical identifier for each layer in ``layersToMute`` will be
computed using ArResolver::CreateIdentifier using the cache's root
layer as the anchoring asset. Any layer encountered during composition
with the same identifier will be considered muted and ignored.
Note that muting a layer will cause this cache to release all
references to that layer. If no other client is holding on to
references to that layer, it will be unloaded. In this case, if there
are unsaved edits to the muted layer, those edits are lost. Since
anonymous layers are not serialized, muting an anonymous layer will
cause that layer and its contents to be lost in this case.
If ``changes`` is not ``nullptr`` , it is adjusted to reflect the
changes necessary to see the change in muted layers. Otherwise, those
changes are applied immediately.
``newLayersMuted`` and ``newLayersUnmuted`` contains the pruned vector
of layers which are muted or unmuted by this call to
RequestLayerMuting.
Parameters
----------
layersToMute : list[str]
layersToUnmute : list[str]
changes : PcpChanges
newLayersMuted : list[str]
newLayersUnmuted : list[str]
"""
result["Cache"].GetMutedLayers.func_doc = """GetMutedLayers() -> list[str]
Returns the list of canonical identifiers for muted layers in this
cache.
See documentation on RequestLayerMuting for more details.
"""
result["Cache"].IsLayerMuted.func_doc = """IsLayerMuted(layerIdentifier) -> bool
Returns true if the layer specified by ``layerIdentifier`` is muted in
this cache, false otherwise.
If ``layerIdentifier`` is relative, it is assumed to be relative to
this cache's root layer. See documentation on RequestLayerMuting for
more details.
Parameters
----------
layerIdentifier : str
----------------------------------------------------------------------
IsLayerMuted(anchorLayer, layerIdentifier, canonicalMutedLayerIdentifier) -> bool
Returns true if the layer specified by ``layerIdentifier`` is muted in
this cache, false otherwise.
If ``layerIdentifier`` is relative, it is assumed to be relative to
``anchorLayer`` . If ``canonicalMutedLayerIdentifier`` is supplied, it
will be populated with the canonical identifier of the muted layer if
this function returns true. See documentation on RequestLayerMuting
for more details.
Parameters
----------
anchorLayer : Layer
layerIdentifier : str
canonicalMutedLayerIdentifier : str
"""
result["Cache"].ComputeLayerStack.func_doc = """ComputeLayerStack(identifier, allErrors) -> LayerStack
Returns the layer stack for ``identifier`` if it exists, otherwise
creates a new layer stack for ``identifier`` .
This returns ``None`` if ``identifier`` is invalid (i.e. its root
layer is ``None`` ). ``allErrors`` will contain any errors encountered
while creating a new layer stack. It'll be unchanged if the layer
stack already existed.
Parameters
----------
identifier : LayerStackIdentifier
allErrors : list[PcpError]
"""
result["Cache"].UsesLayerStack.func_doc = """UsesLayerStack(layerStack) -> bool
Return true if ``layerStack`` is used by this cache in its
composition, false otherwise.
Parameters
----------
layerStack : LayerStack
"""
result["Cache"].ComputePrimIndex.func_doc = """ComputePrimIndex(primPath, allErrors) -> PrimIndex
Compute and return a reference to the cached result for the prim index
for the given path.
``allErrors`` will contain any errors encountered while performing
this operation.
Parameters
----------
primPath : Path
allErrors : list[PcpError]
"""
result["Cache"].FindPrimIndex.func_doc = """FindPrimIndex(primPath) -> PrimIndex
Returns a pointer to the cached computed prim index for the given
path, or None if it has not been computed.
Parameters
----------
primPath : Path
"""
result["Cache"].ComputePropertyIndex.func_doc = """ComputePropertyIndex(propPath, allErrors) -> PropertyIndex
Compute and return a reference to the cached result for the property
index for the given path.
``allErrors`` will contain any errors encountered while performing
this operation.
Parameters
----------
propPath : Path
allErrors : list[PcpError]
"""
result["Cache"].FindPropertyIndex.func_doc = """FindPropertyIndex(propPath) -> PropertyIndex
Returns a pointer to the cached computed property index for the given
path, or None if it has not been computed.
Parameters
----------
propPath : Path
"""
result["Cache"].ComputeRelationshipTargetPaths.func_doc = """ComputeRelationshipTargetPaths(relationshipPath, paths, localOnly, stopProperty, includeStopProperty, deletedPaths, allErrors) -> None
Compute the relationship target paths for the relationship at
``relationshipPath`` into ``paths`` .
If ``localOnly`` is ``true`` then this will compose relationship
targets from local nodes only. If ``stopProperty`` is not ``None``
then this will stop composing relationship targets at ``stopProperty``
, including ``stopProperty`` iff ``includeStopProperty`` is ``true`` .
If not ``None`` , ``deletedPaths`` will be populated with target paths
whose deletion contributed to the computed result. ``allErrors`` will
contain any errors encountered while performing this operation.
Parameters
----------
relationshipPath : Path
paths : list[SdfPath]
localOnly : bool
stopProperty : Spec
includeStopProperty : bool
deletedPaths : list[SdfPath]
allErrors : list[PcpError]
"""
result["Cache"].ComputeAttributeConnectionPaths.func_doc = """ComputeAttributeConnectionPaths(attributePath, paths, localOnly, stopProperty, includeStopProperty, deletedPaths, allErrors) -> None
Compute the attribute connection paths for the attribute at
``attributePath`` into ``paths`` .
If ``localOnly`` is ``true`` then this will compose attribute
connections from local nodes only. If ``stopProperty`` is not ``None``
then this will stop composing attribute connections at
``stopProperty`` , including ``stopProperty`` iff
``includeStopProperty`` is ``true`` . If not ``None`` ,
``deletedPaths`` will be populated with connection paths whose
deletion contributed to the computed result. ``allErrors`` will
contain any errors encountered while performing this operation.
Parameters
----------
attributePath : Path
paths : list[SdfPath]
localOnly : bool
stopProperty : Spec
includeStopProperty : bool
deletedPaths : list[SdfPath]
allErrors : list[PcpError]
"""
result["Cache"].GetUsedLayers.func_doc = """GetUsedLayers() -> SdfLayerHandleSet
Returns set of all layers used by this cache.
"""
result["Cache"].GetUsedLayersRevision.func_doc = """GetUsedLayersRevision() -> int
Return a number that can be used to determine whether or not the set
of layers used by this cache may have changed or not.
For example, if one calls GetUsedLayers() and saves the
GetUsedLayersRevision() , and then later calls GetUsedLayersRevision()
again, if the number is unchanged, then GetUsedLayers() is guaranteed
to be unchanged as well.
"""
result["Cache"].FindAllLayerStacksUsingLayer.func_doc = """FindAllLayerStacksUsingLayer(layer) -> list[PcpLayerStackPtr]
Returns every computed & cached layer stack that includes ``layer`` .
Parameters
----------
layer : Layer
"""
result["Cache"].FindSiteDependencies.func_doc = """FindSiteDependencies(siteLayerStack, sitePath, depMask, recurseOnSite, recurseOnIndex, filterForExistingCachesOnly) -> list[PcpDependency]
Returns dependencies on the given site of scene description, as
discovered by the cached index computations.
depMask
specifies what classes of dependency to include; see
PcpDependencyFlags for details recurseOnSite
includes incoming dependencies on children of sitePath recurseOnIndex
extends the result to include all PcpCache child indexes below
discovered results filterForExistingCachesOnly
filters the results to only paths representing computed prim and
property index caches; otherwise a recursively-expanded result can
include un-computed paths that are expected to depend on the site
Parameters
----------
siteLayerStack : LayerStack
sitePath : Path
depMask : PcpDependencyFlags
recurseOnSite : bool
recurseOnIndex : bool
filterForExistingCachesOnly : bool
----------------------------------------------------------------------
FindSiteDependencies(siteLayer, sitePath, depMask, recurseOnSite, recurseOnIndex, filterForExistingCachesOnly) -> list[PcpDependency]
Returns dependencies on the given site of scene description, as
discovered by the cached index computations.
This method overload takes a site layer rather than a layer stack. It
will check every layer stack using that layer, and apply any relevant
sublayer offsets to the map functions in the returned
PcpDependencyVector.
See the other method for parameter details.
Parameters
----------
siteLayer : Layer
sitePath : Path
depMask : PcpDependencyFlags
recurseOnSite : bool
recurseOnIndex : bool
filterForExistingCachesOnly : bool
"""
result["Cache"].IsInvalidSublayerIdentifier.func_doc = """IsInvalidSublayerIdentifier(identifier) -> bool
Returns true if ``identifier`` was used as a sublayer path in a layer
stack but did not identify a valid layer.
This is functionally equivalent to examining the values in the vector
returned by GetInvalidSublayerIdentifiers, but more efficient.
Parameters
----------
identifier : str
"""
result["Cache"].IsInvalidAssetPath.func_doc = """IsInvalidAssetPath(resolvedAssetPath) -> bool
Returns true if ``resolvedAssetPath`` was used by a prim (e.g.
in a reference) but did not resolve to a valid asset. This is
functionally equivalent to examining the values in the map returned by
GetInvalidAssetPaths, but more efficient.
Parameters
----------
resolvedAssetPath : str
"""
result["Cache"].HasAnyDynamicFileFormatArgumentDependencies.func_doc = """HasAnyDynamicFileFormatArgumentDependencies() -> bool
Returns true if any prim index in this cache has a dependency on a
dynamic file format argument field.
"""
result["Cache"].IsPossibleDynamicFileFormatArgumentField.func_doc = """IsPossibleDynamicFileFormatArgumentField(field) -> bool
Returns true if the given ``field`` is the name of a field that was
composed while generating dynamic file format arguments for any prim
index in this cache.
Parameters
----------
field : str
"""
result["Cache"].GetDynamicFileFormatArgumentDependencyData.func_doc = """GetDynamicFileFormatArgumentDependencyData(primIndexPath) -> DynamicFileFormatDependencyData
Returns the dynamic file format dependency data object for the prim
index with the given ``primIndexPath`` .
This will return an empty dependency data if either there is no cache
prim index for the path or if the prim index has no dynamic file
formats that it depends on.
Parameters
----------
primIndexPath : Path
"""
result["Cache"].Reload.func_doc = """Reload(changes) -> None
Reload the layers of the layer stack, except session layers and
sublayers of session layers.
This will also try to load sublayers in this cache's layer stack that
could not be loaded previously. It will also try to load any
referenced or payloaded layer that could not be loaded previously.
Clients should subsequently ``Apply()`` ``changes`` to use any now-
valid layers.
Parameters
----------
changes : PcpChanges
"""
result["Cache"].PrintStatistics.func_doc = """PrintStatistics() -> None
Prints various statistics about the data stored in this cache.
"""
result["Cache"].__init__.func_doc = """__init__(arg1)
Parameters
----------
arg1 : Cache
----------------------------------------------------------------------
__init__(layerStackIdentifier, fileFormatTarget, usd)
Construct a PcpCache to compose results for the layer stack identified
by *layerStackIdentifier*.
If ``fileFormatTarget`` is given, Pcp will specify
``fileFormatTarget`` as the file format target when searching for or
opening a layer.
If ``usd`` is true, computation of prim indices and composition of
prim child names are performed without relocates, inherits,
permissions, symmetry, or payloads, and without populating the prim
stack and gathering its dependencies.
Parameters
----------
layerStackIdentifier : LayerStackIdentifier
fileFormatTarget : str
usd : bool
"""
result["Dependency"].__doc__ = """
Description of a dependency.
"""
result["DynamicFileFormatDependencyData"].__doc__ = """
Contains the necessary information for storing a prim index's
dependency on dynamic file format arguments and determining if a field
change affects the prim index. This data structure does not store the
prim index or its path itself and is expected to be the data in some
other data structure that maps prim indexes to its dependencies.
"""
result["DynamicFileFormatDependencyData"].IsEmpty.func_doc = """IsEmpty() -> bool
Returns whether this dependency data is empty.
"""
result["DynamicFileFormatDependencyData"].GetRelevantFieldNames.func_doc = """GetRelevantFieldNames() -> str.Set
Returns a list of field names that were composed for any of the
dependency contexts that were added to this dependency.
"""
result["DynamicFileFormatDependencyData"].CanFieldChangeAffectFileFormatArguments.func_doc = """CanFieldChangeAffectFileFormatArguments(fieldName, oldValue, newValue) -> bool
Given a ``field`` name and the changed field values in
``oldAndNewValues`` this return whether this change can affect any of
the file format arguments generated by any of the contexts stored in
this dependency.
Parameters
----------
fieldName : str
oldValue : VtValue
newValue : VtValue
"""
result["ErrorArcCycle"].__doc__ = """
Arcs between PcpNodes that form a cycle.
"""
result["ErrorArcPermissionDenied"].__doc__ = """
Arcs that were not made between PcpNodes because of permission
restrictions.
"""
result["ErrorBase"].__doc__ = """
Base class for all error types.
"""
result["ErrorCapacityExceeded"].__doc__ = """
Exceeded the capacity for composition arcs at a single site.
"""
result["ErrorInconsistentAttributeType"].__doc__ = """
Attributes that have specs with conflicting definitions.
"""
result["ErrorInconsistentAttributeVariability"].__doc__ = """
Attributes that have specs with conflicting variability.
"""
result["ErrorInconsistentPropertyType"].__doc__ = """
Properties that have specs with conflicting definitions.
"""
result["ErrorInvalidAssetPath"].__doc__ = """
Invalid asset paths used by references or payloads.
"""
result["ErrorInvalidAssetPathBase"].__doc__ = """"""
result["ErrorInvalidExternalTargetPath"].__doc__ = """
Invalid target or connection path in some scope that points to an
object outside of that scope.
"""
result["ErrorInvalidInstanceTargetPath"].__doc__ = """
Invalid target or connection path authored in an inherited class that
points to an instance of that class.
"""
result["ErrorInvalidPrimPath"].__doc__ = """
Invalid prim paths used by references or payloads.
"""
result["ErrorInvalidReferenceOffset"].__doc__ = """
References or payloads that use invalid layer offsets.
"""
result["ErrorInvalidSublayerOffset"].__doc__ = """
Sublayers that use invalid layer offsets.
"""
result["ErrorInvalidSublayerOwnership"].__doc__ = """
Sibling layers that have the same owner.
"""
result["ErrorInvalidSublayerPath"].__doc__ = """
Asset paths that could not be both resolved and loaded.
"""
result["ErrorInvalidTargetPath"].__doc__ = """
Invalid target or connection path.
"""
result["ErrorMutedAssetPath"].__doc__ = """
Muted asset paths used by references or payloads.
"""
result["ErrorOpinionAtRelocationSource"].__doc__ = """
Opinions were found at a relocation source path.
"""
result["ErrorPrimPermissionDenied"].__doc__ = """
Layers with illegal opinions about private prims.
"""
result["ErrorPropertyPermissionDenied"].__doc__ = """
Layers with illegal opinions about private properties.
"""
result["ErrorSublayerCycle"].__doc__ = """
Layers that recursively sublayer themselves.
"""
result["ErrorTargetPathBase"].__doc__ = """
Base class for composition errors related to target or connection
paths.
"""
result["ErrorTargetPermissionDenied"].__doc__ = """
Paths with illegal opinions about private targets.
"""
result["ErrorUnresolvedPrimPath"].__doc__ = """
Asset paths that could not be both resolved and loaded.
"""
result["InstanceKey"].__doc__ = """
A PcpInstanceKey identifies instanceable prim indexes that share the
same set of opinions. Instanceable prim indexes with equal instance
keys are guaranteed to have the same opinions for name children and
properties beneath those name children. They are NOT guaranteed to
have the same opinions for direct properties of the prim indexes
themselves.
"""
result["InstanceKey"].__init__.func_doc = """__init__()
----------------------------------------------------------------------
__init__(primIndex)
Create an instance key for the given prim index.
Parameters
----------
primIndex : PrimIndex
"""
result["LayerStack"].__doc__ = """
Represents a stack of layers that contribute opinions to composition.
Each PcpLayerStack is identified by a PcpLayerStackIdentifier. This
identifier contains all of the parameters needed to construct a layer
stack, such as the root layer, session layer, and path resolver
context.
PcpLayerStacks are constructed and managed by a
Pcp_LayerStackRegistry.
"""
result["LayerStackIdentifier"].__doc__ = """
Arguments used to identify a layer stack.
Objects of this type are immutable.
"""
result["LayerStackIdentifier"].__init__.func_doc = """__init__()
Construct with all empty pointers.
----------------------------------------------------------------------
__init__(rootLayer_, sessionLayer_, pathResolverContext_)
Construct with given pointers.
If all arguments are ``TfNullPtr`` then the result is identical to the
default constructed object.
Parameters
----------
rootLayer_ : Layer
sessionLayer_ : Layer
pathResolverContext_ : ResolverContext
"""
result["LayerStackSite"].__doc__ = """
A site specifies a path in a layer stack of scene description.
"""
result["MapExpression"].__doc__ = """
An expression that yields a PcpMapFunction value.
Expressions comprise constant values, variables, and operators applied
to sub-expressions. Expressions cache their computed values
internally. Assigning a new value to a variable automatically
invalidates the cached values of dependent expressions. Common
(sub-)expressions are automatically detected and shared.
PcpMapExpression exists solely to support efficient incremental
handling of relocates edits. It represents a tree of the namespace
mapping operations and their inputs, so we can narrowly redo the
computation when one of the inputs changes.
"""
result["MapExpression"].Compose.func_doc = """Compose(f) -> MapExpression
Create a new PcpMapExpression representing the application of f's
value, followed by the application of this expression's value.
Parameters
----------
f : MapExpression
"""
result["MapExpression"].Inverse.func_doc = """Inverse() -> MapExpression
Create a new PcpMapExpression representing the inverse of f.
"""
result["MapExpression"].AddRootIdentity.func_doc = """AddRootIdentity() -> MapExpression
Return a new expression representing this expression with an added (if
necessary) mapping from</>to</>.
"""
result["MapExpression"].Identity.func_doc = """**classmethod** Identity() -> MapExpression
Return an expression representing PcpMapFunction::Identity() .
"""
result["MapExpression"].Constant.func_doc = """**classmethod** Constant(constValue) -> MapExpression
Create a new constant.
Parameters
----------
constValue : Value
"""
result["MapExpression"].MapSourceToTarget.func_doc = """MapSourceToTarget(path) -> Path
Map a path in the source namespace to the target.
If the path is not in the domain, returns an empty path.
Parameters
----------
path : Path
"""
result["MapExpression"].MapTargetToSource.func_doc = """MapTargetToSource(path) -> Path
Map a path in the target namespace to the source.
If the path is not in the co-domain, returns an empty path.
Parameters
----------
path : Path
"""
result["MapExpression"].Evaluate.func_doc = """Evaluate() -> Value
Evaluate this expression, yielding a PcpMapFunction value.
The computed result is cached. The return value is a reference to the
internal cached value. The cache is automatically invalidated as
needed.
"""
result["MapExpression"].__init__.func_doc = """__init__()
Default-construct a None expression.
----------------------------------------------------------------------
__init__(node)
Parameters
----------
node : _Node
"""
result["MapFunction"].__doc__ = """
A function that maps values from one namespace (and time domain) to
another. It represents the transformation that an arc such as a
reference arc applies as it incorporates values across the arc.
Take the example of a reference arc, where a source path</Model>is
referenced as a target path,</Model_1>. The source path</Model>is the
source of the opinions; the target path</Model_1>is where they are
incorporated in the scene. Values in the model that refer to paths
relative to</Model>must be transformed to be relative
to</Model_1>instead. The PcpMapFunction for the arc provides this
service.
Map functions have a specific *domain*, or set of values they can
operate on. Any values outside the domain cannot be mapped. The domain
precisely tracks what areas of namespace can be referred to across
various forms of arcs.
Map functions can be chained to represent a series of map operations
applied in sequence. The map function represent the cumulative effect
as efficiently as possible. For example, in the case of a chained
reference from</Model>to</Model>to</Model>to</Model_1>, this is
effectively the same as a mapping directly from</Model>to</Model_1>.
Representing the cumulative effect of arcs in this way is important
for handling larger scenes efficiently.
Map functions can be *inverted*. Formally, map functions are
bijections (one-to-one and onto), which ensures that they can be
inverted. Put differently, no information is lost by applying a map
function to set of values within its domain; they retain their
distinct identities and can always be mapped back.
One analogy that may or may not be helpful: In the same way a
geometric transform maps a model's points in its rest space into the
world coordinates for a particular instance, a PcpMapFunction maps
values about a referenced model into the composed scene for a
particular instance of that model. But rather than translating and
rotating points, the map function shifts the values in namespace (and
time).
"""
result["MapFunction"].__init__.func_doc = """__init__()
Construct a null function.
----------------------------------------------------------------------
__init__(sourceToTargetBegin, sourceToTargetEnd, offset, hasRootIdentity)
Parameters
----------
sourceToTargetBegin : PathPair
sourceToTargetEnd : PathPair
offset : LayerOffset
hasRootIdentity : bool
"""
result["MapFunction"].MapSourceToTarget.func_doc = """MapSourceToTarget(path) -> Path
Map a path in the source namespace to the target.
If the path is not in the domain, returns an empty path.
Parameters
----------
path : Path
"""
result["MapFunction"].MapTargetToSource.func_doc = """MapTargetToSource(path) -> Path
Map a path in the target namespace to the source.
If the path is not in the co-domain, returns an empty path.
Parameters
----------
path : Path
"""
result["MapFunction"].Compose.func_doc = """Compose(f) -> MapFunction
Compose this map over the given map function.
The result will represent the application of f followed by the
application of this function.
Parameters
----------
f : MapFunction
"""
result["MapFunction"].ComposeOffset.func_doc = """ComposeOffset(newOffset) -> MapFunction
Compose this map function over a hypothetical map function that has an
identity path mapping and ``offset`` .
This is equivalent to building such a map function and invoking
Compose() , but is faster.
Parameters
----------
newOffset : LayerOffset
"""
result["MapFunction"].GetInverse.func_doc = """GetInverse() -> MapFunction
Return the inverse of this map function.
This returns a true inverse ``inv:`` for any path p in this function's
domain that it maps to p', inv(p') ->p.
"""
result["MapFunction"].Identity.func_doc = """**classmethod** Identity() -> MapFunction
Construct an identity map function.
"""
result["MapFunction"].IdentityPathMap.func_doc = """**classmethod** IdentityPathMap() -> PathMap
Returns an identity path mapping.
"""
result["NodeRef"].__doc__ = """
PcpNode represents a node in an expression tree for compositing scene
description.
A node represents the opinions from a particular site. In addition, it
may have child nodes, representing nested expressions that are
composited over/under this node.
Child nodes are stored and composited in strength order.
Each node holds information about the arc to its parent. This captures
both the relative strength of the sub-expression as well as any value-
mapping needed, such as to rename opinions from a model to use in a
particular instance.
"""
result["NodeRef"].GetOriginRootNode.func_doc = """GetOriginRootNode() -> NodeRef
Walk up to the root origin node for this node.
This is the very first node that caused this node to be added to the
graph. For instance, the root origin node of an implied inherit is the
original inherit node.
"""
result["NodeRef"].GetRootNode.func_doc = """GetRootNode() -> NodeRef
Walk up to the root node of this expression.
"""
result["NodeRef"].GetDepthBelowIntroduction.func_doc = """GetDepthBelowIntroduction() -> int
Return the number of levels of namespace this node's site is below the
level at which it was introduced by an arc.
"""
result["NodeRef"].GetPathAtIntroduction.func_doc = """GetPathAtIntroduction() -> Path
Returns the path for this node's site when it was introduced.
"""
result["NodeRef"].GetIntroPath.func_doc = """GetIntroPath() -> Path
Get the path that introduced this node.
Specifically, this is the path the parent node had at the level of
namespace where this node was added as a child. For a root node, this
returns the absolute root path. See also GetDepthBelowIntroduction() .
"""
result["NodeRef"].IsRootNode.func_doc = """IsRootNode() -> bool
Returns true if this node is the root node of the prim index graph.
"""
result["NodeRef"].IsDueToAncestor.func_doc = """IsDueToAncestor() -> bool
"""
result["NodeRef"].CanContributeSpecs.func_doc = """CanContributeSpecs() -> bool
Returns true if this node is allowed to contribute opinions for
composition, false otherwise.
"""
result["PrimIndex"].__doc__ = """
PcpPrimIndex is an index of the all sites of scene description that
contribute opinions to a specific prim, under composition semantics.
PcpComputePrimIndex() builds an index ("indexes") the given prim site.
At any site there may be scene description values expressing arcs that
represent instructions to pull in further scene description.
PcpComputePrimIndex() recursively follows these arcs, building and
ordering the results.
"""
result["PrimIndex"].GetNodeProvidingSpec.func_doc = """GetNodeProvidingSpec(primSpec) -> NodeRef
Returns the node that brings opinions from ``primSpec`` into this prim
index.
If no such node exists, returns an invalid PcpNodeRef.
Parameters
----------
primSpec : PrimSpec
----------------------------------------------------------------------
GetNodeProvidingSpec(layer, path) -> NodeRef
Returns the node that brings opinions from the Sd prim spec at
``layer`` and ``path`` into this prim index.
If no such node exists, returns an invalid PcpNodeRef.
Parameters
----------
layer : Layer
path : Path
"""
result["PrimIndex"].PrintStatistics.func_doc = """PrintStatistics() -> None
Prints various statistics about this prim index.
"""
result["PrimIndex"].DumpToString.func_doc = """DumpToString(includeInheritOriginInfo, includeMaps) -> str
Dump the prim index contents to a string.
If ``includeInheritOriginInfo`` is ``true`` , output for implied
inherit nodes will include information about the originating inherit
node. If ``includeMaps`` is ``true`` , output for each node will
include the mappings to the parent and root node.
Parameters
----------
includeInheritOriginInfo : bool
includeMaps : bool
"""
result["PrimIndex"].DumpToDotGraph.func_doc = """DumpToDotGraph(filename, includeInheritOriginInfo, includeMaps) -> None
Dump the prim index in dot format to the file named ``filename`` .
See Dump(\\.\\.\\.) for information regarding arguments.
Parameters
----------
filename : str
includeInheritOriginInfo : bool
includeMaps : bool
"""
result["PrimIndex"].ComputePrimChildNames.func_doc = """ComputePrimChildNames(nameOrder, prohibitedNameSet) -> None
Compute the prim child names for the given path.
``errors`` will contain any errors encountered while performing this
operation.
Parameters
----------
nameOrder : list[TfToken]
prohibitedNameSet : PcpTokenSet
"""
result["PrimIndex"].ComputePrimPropertyNames.func_doc = """ComputePrimPropertyNames(nameOrder) -> None
Compute the prim property names for the given path.
``errors`` will contain any errors encountered while performing this
operation. The ``nameOrder`` vector must not contain any duplicate
entries.
Parameters
----------
nameOrder : list[TfToken]
"""
result["PrimIndex"].ComposeAuthoredVariantSelections.func_doc = """ComposeAuthoredVariantSelections() -> SdfVariantSelectionMap
Compose the authored prim variant selections.
These are the variant selections expressed in scene description. Note
that these selections may not have actually been applied, if they are
invalid.
This result is not cached, but computed each time.
"""
result["PrimIndex"].GetSelectionAppliedForVariantSet.func_doc = """GetSelectionAppliedForVariantSet(variantSet) -> str
Return the variant selection applied for the named variant set.
If none was applied, this returns an empty string. This can be
different from the authored variant selection; for example, if the
authored selection is invalid.
Parameters
----------
variantSet : str
"""
result["PrimIndex"].IsValid.func_doc = """IsValid() -> bool
Return true if this index is valid.
A default-constructed index is invalid.
"""
result["PrimIndex"].IsInstanceable.func_doc = """IsInstanceable() -> bool
Returns true if this prim index is instanceable.
Instanceable prim indexes with the same instance key are guaranteed to
have the same set of opinions, but may not have local opinions about
name children.
PcpInstanceKey
"""
result["PropertyIndex"].__doc__ = """
PcpPropertyIndex is an index of all sites in scene description that
contribute opinions to a specific property, under composition
semantics.
"""
result["Site"].__doc__ = """
A site specifies a path in a layer stack of scene description.
"""
result["Cache"].layerStack = property(result["Cache"].layerStack.fget, result["Cache"].layerStack.fset, result["Cache"].layerStack.fdel, """type : LayerStack
Get the layer stack for GetLayerStackIdentifier() .
Note that this will neither compute the layer stack nor report errors.
So if the layer stack has not been computed yet this will return
``None`` . Use ComputeLayerStack() if you need to compute the layer
stack if it hasn't been computed already and/or get errors caused by
computing the layer stack.
""")
result["Cache"].fileFormatTarget = property(result["Cache"].fileFormatTarget.fget, result["Cache"].fileFormatTarget.fset, result["Cache"].fileFormatTarget.fdel, """type : str
Returns the file format target this cache is configured for.
""")
result["LayerStack"].identifier = property(result["LayerStack"].identifier.fget, result["LayerStack"].identifier.fset, result["LayerStack"].identifier.fdel, """type : LayerStackIdentifier
Returns the identifier for this layer stack.
""")
result["LayerStack"].layers = property(result["LayerStack"].layers.fget, result["LayerStack"].layers.fset, result["LayerStack"].layers.fdel, """type : list[SdfLayerRefPtr]
Returns the layers in this layer stack in strong-to-weak order.
Note that this is only the *local* layer stack it does not include
any layers brought in by references inside prims.
""")
result["LayerStack"].layerTree = property(result["LayerStack"].layerTree.fget, result["LayerStack"].layerTree.fset, result["LayerStack"].layerTree.fdel, """type : LayerTree
Returns the layer tree representing the structure of this layer stack.
""")
result["LayerStack"].mutedLayers = property(result["LayerStack"].mutedLayers.fget, result["LayerStack"].mutedLayers.fset, result["LayerStack"].mutedLayers.fdel, """type : set[str]
Returns the set of layers that were muted in this layer stack.
""")
result["LayerStack"].localErrors = property(result["LayerStack"].localErrors.fget, result["LayerStack"].localErrors.fset, result["LayerStack"].localErrors.fdel, """type : list[PcpError]
Return the list of errors local to this layer stack.
""")
result["LayerStack"].relocatesSourceToTarget = property(result["LayerStack"].relocatesSourceToTarget.fget, result["LayerStack"].relocatesSourceToTarget.fset, result["LayerStack"].relocatesSourceToTarget.fdel, """type : SdfRelocatesMap
Returns relocation source-to-target mapping for this layer stack.
This map combines the individual relocation entries found across all
layers in this layer stack; multiple entries that affect a single prim
will be combined into a single entry. For instance, if this layer
stack contains relocations { /A: /B} and { /A/C: /A/D}, this map will
contain { /A: /B} and { /B/C: /B/D}. This allows consumers to go from
unrelocated namespace to relocated namespace in a single step.
""")
result["LayerStack"].relocatesTargetToSource = property(result["LayerStack"].relocatesTargetToSource.fget, result["LayerStack"].relocatesTargetToSource.fset, result["LayerStack"].relocatesTargetToSource.fdel, """type : SdfRelocatesMap
Returns relocation target-to-source mapping for this layer stack.
See GetRelocatesSourceToTarget for more details.
""")
result["LayerStack"].incrementalRelocatesSourceToTarget = property(result["LayerStack"].incrementalRelocatesSourceToTarget.fget, result["LayerStack"].incrementalRelocatesSourceToTarget.fset, result["LayerStack"].incrementalRelocatesSourceToTarget.fdel, """type : SdfRelocatesMap
Returns incremental relocation source-to-target mapping for this layer
stack.
This map contains the individual relocation entries found across all
layers in this layer stack; it does not combine ancestral entries with
descendant entries. For instance, if this layer stack contains
relocations { /A: /B} and { /A/C: /A/D}, this map will contain { /A:
/B} and { /A/C: /A/D}.
""")
result["LayerStack"].incrementalRelocatesTargetToSource = property(result["LayerStack"].incrementalRelocatesTargetToSource.fget, result["LayerStack"].incrementalRelocatesTargetToSource.fset, result["LayerStack"].incrementalRelocatesTargetToSource.fdel, """type : SdfRelocatesMap
Returns incremental relocation target-to-source mapping for this layer
stack.
See GetIncrementalRelocatesTargetToSource for more details.
""")
result["LayerStack"].pathsToPrimsWithRelocates = property(result["LayerStack"].pathsToPrimsWithRelocates.fget, result["LayerStack"].pathsToPrimsWithRelocates.fset, result["LayerStack"].pathsToPrimsWithRelocates.fdel, """type : list[SdfPath]
Returns a list of paths to all prims across all layers in this layer
stack that contained relocates.
""")
result["MapExpression"].isIdentity = property(result["MapExpression"].isIdentity.fget, result["MapExpression"].isIdentity.fset, result["MapExpression"].isIdentity.fdel, """type : bool
Return true if the evaluated map function is the identity function.
For identity, MapSourceToTarget() always returns the path unchanged.
""")
result["MapExpression"].timeOffset = property(result["MapExpression"].timeOffset.fget, result["MapExpression"].timeOffset.fset, result["MapExpression"].timeOffset.fdel, """type : LayerOffset
The time offset of the mapping.
""")
result["MapExpression"].isNull = property(result["MapExpression"].isNull.fget, result["MapExpression"].isNull.fset, result["MapExpression"].isNull.fdel, """type : bool
Return true if this is a null expression.
""")
result["MapFunction"].isNull = property(result["MapFunction"].isNull.fget, result["MapFunction"].isNull.fset, result["MapFunction"].isNull.fdel, """type : bool
Return true if this map function is the null function.
For a null function, MapSourceToTarget() always returns an empty path.
""")
result["MapFunction"].isIdentity = property(result["MapFunction"].isIdentity.fget, result["MapFunction"].isIdentity.fset, result["MapFunction"].isIdentity.fdel, """type : bool
Return true if the map function is the identity function.
The identity function has an identity path mapping and time offset.
""")
result["MapFunction"].isIdentityPathMapping = property(result["MapFunction"].isIdentityPathMapping.fget, result["MapFunction"].isIdentityPathMapping.fset, result["MapFunction"].isIdentityPathMapping.fdel, """type : bool
Return true if the map function uses the identity path mapping.
If true, MapSourceToTarget() always returns the path unchanged.
However, this map function may have a non-identity time offset.
""")
result["MapFunction"].sourceToTargetMap = property(result["MapFunction"].sourceToTargetMap.fget, result["MapFunction"].sourceToTargetMap.fset, result["MapFunction"].sourceToTargetMap.fdel, """type : PathMap
The set of path mappings, from source to target.
""")
result["MapFunction"].timeOffset = property(result["MapFunction"].timeOffset.fget, result["MapFunction"].timeOffset.fset, result["MapFunction"].timeOffset.fdel, """type : LayerOffset
The time offset of the mapping.
""")
result["NodeRef"].arcType = property(result["NodeRef"].arcType.fget, result["NodeRef"].arcType.fset, result["NodeRef"].arcType.fdel, """type : ArcType
Returns the type of arc connecting this node to its parent node.
""")
result["NodeRef"].mapToParent = property(result["NodeRef"].mapToParent.fget, result["NodeRef"].mapToParent.fset, result["NodeRef"].mapToParent.fdel, """type : MapExpression
Returns mapping function used to translate paths and values from this
node to its parent node.
""")
result["NodeRef"].mapToRoot = property(result["NodeRef"].mapToRoot.fget, result["NodeRef"].mapToRoot.fset, result["NodeRef"].mapToRoot.fdel, """type : MapExpression
Returns mapping function used to translate paths and values from this
node directly to the root node.
""")
result["NodeRef"].siblingNumAtOrigin = property(result["NodeRef"].siblingNumAtOrigin.fget, result["NodeRef"].siblingNumAtOrigin.fset, result["NodeRef"].siblingNumAtOrigin.fdel, """type : int
Returns this node's index among siblings with the same arc type at
this node's origin.
""")
result["NodeRef"].namespaceDepth = property(result["NodeRef"].namespaceDepth.fget, result["NodeRef"].namespaceDepth.fset, result["NodeRef"].namespaceDepth.fdel, """type : int
Returns the absolute namespace depth of the node that introduced this
node.
Note that this does *not* count any variant selections.
""")
result["NodeRef"].site = property(result["NodeRef"].site.fget, result["NodeRef"].site.fset, result["NodeRef"].site.fdel, """type : LayerStackSite
Get the site this node represents.
""")
result["NodeRef"].path = property(result["NodeRef"].path.fget, result["NodeRef"].path.fset, result["NodeRef"].path.fdel, """type : Path
Returns the path for the site this node represents.
""")
result["NodeRef"].layerStack = property(result["NodeRef"].layerStack.fget, result["NodeRef"].layerStack.fset, result["NodeRef"].layerStack.fdel, """type : LayerStack
Returns the layer stack for the site this node represents.
""")
result["NodeRef"].hasSymmetry = property(result["NodeRef"].hasSymmetry.fget, result["NodeRef"].hasSymmetry.fset, result["NodeRef"].hasSymmetry.fdel, """type : None
Get/set whether this node provides any symmetry opinions, either
directly or from a namespace ancestor.
""")
result["NodeRef"].permission = property(result["NodeRef"].permission.fget, result["NodeRef"].permission.fset, result["NodeRef"].permission.fdel, """type : Permission
----------------------------------------------------------------------
type : None
Get/set the permission for this node.
This indicates whether specs on this node can be accessed from other
nodes.
""")
result["NodeRef"].isInert = property(result["NodeRef"].isInert.fget, result["NodeRef"].isInert.fset, result["NodeRef"].isInert.fdel, """type : bool
""")
result["NodeRef"].isCulled = property(result["NodeRef"].isCulled.fget, result["NodeRef"].isCulled.fset, result["NodeRef"].isCulled.fdel, """type : bool
""")
result["NodeRef"].isRestricted = property(result["NodeRef"].isRestricted.fget, result["NodeRef"].isRestricted.fset, result["NodeRef"].isRestricted.fdel, """type : bool
""")
result["NodeRef"].hasSpecs = property(result["NodeRef"].hasSpecs.fget, result["NodeRef"].hasSpecs.fset, result["NodeRef"].hasSpecs.fdel, """type : None
Returns true if this node has opinions authored for composition, false
otherwise.
""")
result["PrimIndex"].localErrors = property(result["PrimIndex"].localErrors.fget, result["PrimIndex"].localErrors.fset, result["PrimIndex"].localErrors.fdel, """type : list[PcpError]
Return the list of errors local to this prim.
""")
result["PrimIndex"].rootNode = property(result["PrimIndex"].rootNode.fget, result["PrimIndex"].rootNode.fset, result["PrimIndex"].rootNode.fdel, """type : NodeRef
Returns the root node of the prim index graph.
""")
result["PropertyIndex"].localErrors = property(result["PropertyIndex"].localErrors.fget, result["PropertyIndex"].localErrors.fset, result["PropertyIndex"].localErrors.fdel, """type : list[PcpError]
Return the list of errors local to this property.
""") | 46,707 | Python | 25.78211 | 281 | 0.738861 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Plug/__DOC.py | def Execute(result):
result["Notice"].__doc__ = """
Notifications sent by the Plug module.
"""
result["Plugin"].__doc__ = """
Defines an interface to registered plugins.
Plugins are registered using the interfaces in ``PlugRegistry`` .
For each registered plugin, there is an instance of ``PlugPlugin``
which can be used to load and unload the plugin and to retrieve
information about the classes implemented by the plugin.
"""
result["Plugin"].Load.func_doc = """Load() -> bool
Loads the plugin.
This is a noop if the plugin is already loaded.
"""
result["Plugin"].GetMetadataForType.func_doc = """GetMetadataForType(type) -> JsObject
Returns the metadata sub-dictionary for a particular type.
Parameters
----------
type : Type
"""
result["Plugin"].DeclaresType.func_doc = """DeclaresType(type, includeSubclasses) -> bool
Returns true if ``type`` is declared by this plugin.
If ``includeSubclasses`` is specified, also returns true if any
subclasses of ``type`` have been declared.
Parameters
----------
type : Type
includeSubclasses : bool
"""
result["Plugin"].MakeResourcePath.func_doc = """MakeResourcePath(path) -> str
Build a plugin resource path by returning a given absolute path or
combining the plugin's resource path with a given relative path.
Parameters
----------
path : str
"""
result["Plugin"].FindPluginResource.func_doc = """FindPluginResource(path, verify) -> str
Find a plugin resource by absolute or relative path optionally
verifying that file exists.
If verification fails an empty path is returned. Relative paths are
relative to the plugin's resource path.
Parameters
----------
path : str
verify : bool
"""
result["Registry"].__doc__ = """
Defines an interface for registering plugins.
PlugRegistry maintains a registry of plug-ins known to the system and
provides an interface for base classes to load any plug-ins required
to instantiate a subclass of a given type.
Defining a Base Class API
=========================
In order to use this facility you will generally provide a module
which defines the API for a plug-in base class. This API will be
sufficient for the application or framework to make use of custom
subclasses that will be written by plug-in developers.
For example, if you have an image processing application, you might
want to support plug-ins that implement image filters. You can define
an abstract base class for image filters that declares the API your
application will require image filters to implement; perhaps something
simple like C++ Code Example 1 (Doxygen only).
People writing custom filters would write a subclass of ImageFilter
that overrides the two methods, implementing their own special
filtering behavior.
Enabling Plug-in Loading for the Base Class
===========================================
In order for ImageFilter to be able to load plug-ins that implement
these custom subclasses, it must be registered with the TfType system.
The ImageFilter base class, as was mentioned earlier, should be made
available in a module that the application links with. This is done
so that plug-ins that want to provide ImageFilters can also link with
the module allowing them to subclass ImageFilter.
Registering Plug-ins
====================
A plug-in developer can now write plug-ins with ImageFilter
subclasses. Plug-ins can be implemented either as native dynamic
modules (either regular dynamic modules or framework bundles) or
as Python modules.
Plug-ins must be registered with the registry. All plugins are
registered via RegisterPlugins() . Plug-in Python modules must be
directly importable (in other words they must be able to be found in
Python's module path.) Plugins are registered by providing a path or
paths to JSON files that describe the location, structure and contents
of the plugin. The standard name for these files in plugInfo.json.
Typically, the application that hosts plug-ins will locate and
register plug-ins at startup.
The plug-in facility is lazy. It does not dynamically load code from
plug-in bundles until that code is required.
plugInfo.json
=============
A plugInfo.json file has the following structure:
.. code-block:: text
{
# Comments are allowed and indicated by a hash at the start of a
# line or after spaces and tabs. They continue to the end of line.
# Blank lines are okay, too.
# This is optional. It may contain any number of strings.
# Paths may be absolute or relative.
# Paths ending with slash have plugInfo.json appended automatically.
# '\\*' may be used anywhere to match any character except slash.
# '\\*\\*' may be used anywhere to match any character including slash.
"Includes": [
"/absolute/path/to/plugInfo.json",
"/absolute/path/to/custom.filename",
"/absolute/path/to/directory/with/plugInfo/",
"relative/path/to/plugInfo.json",
"relative/path/to/directory/with/plugInfo/",
"glob\\*/pa\\*th/\\*to\\*/\\*/plugInfo.json",
"recursive/pa\\*\\*th/\\*\\*/"
],
# This is optional. It may contain any number of objects.
"Plugins": [
{
# Type is required and may be "module", "python" or "resource".
"Type": "module",
# Name is required. It should be the Python module name,
# the shared module name, or a unique resource name.
"Name": "myplugin",
# Root is optional. It defaults to ".".
# This gives the path to the plugin as a whole if the plugin
# has substructure. For Python it should be the directory
# with the __init__.py file. The path is usually relative.
"Root": ".",
# LibraryPath is required by Type "module" and unused
# otherwise. It gives the path to the shared module
# object, either absolute or relative to Root.
"LibraryPath": "libmyplugin.so",
# ResourcePath is option. It defaults to ".".
# This gives the path to the plugin's resources directory.
# The path is either absolute or relative to Root.
"ResourcePath": "resources",
# Info is required. It's described below.
"Info": {
# Plugin contents.
}
}
]
}
As a special case, if a plugInfo.json contains an object that doesn't
have either the"Includes"or"Plugins"keys then it's as if the object
was in a"Plugins"array.
Advertising a Plug-in's Contents
================================
Once the plug-ins are registered, the plug-in facility must also be
able to tell what they contain. Specifically, it must be able to find
out what subclasses of what plug-in base classes each plug-in
contains. Plug-ins must advertise this information through their
plugInfo.json file in the"Info"key. In the"Info"object there should be
a key"Types"holding an object.
This"Types"object's keys are names of subclasses and its values are
yet more objects (the subclass meta-data objects). The meta-data
objects can contain arbitrary key-value pairs. The plug-in mechanism
will look for a meta-data key called"displayName"whose value should be
the display name of the subclass. The plug-in mechanism will look for
a meta-data key called"bases"whose value should be an array of base
class type names.
For example, a bundle that contains a subclass of ImageFilter might
have a plugInfo.json that looks like the following example.
.. code-block:: text
{
"Types": {
"MyCustomCoolFilter" : {
"bases": ["ImageFilter"],
"displayName": "Add Coolness to Image"
# other arbitrary metadata for MyCustomCoolFilter here
}
}
}
What this says is that the plug-in contains a type called
MyCustomCoolFilter which has a base class ImageFilter and that this
subclass should be called"Add Coolness to Image"in user-visible
contexts.
In addition to the"displayName"meta-data key which is actually known
to the plug-in facility, you may put whatever other information you
want into a class'meta-data dictionary. If your plug-in base class
wants to define custom keys that it requires all subclasses to
provide, you can do that. Or, if a plug-in writer wants to define
their own keys that their code will look for at runtime, that is OK as
well.
Working with Subclasses of a Plug-in Base Class
===============================================
Most code with uses types defined in plug-ins doesn't deal with the
Plug API directly. Instead, the TfType interface is used to lookup
types and to manufacture instances. The TfType interface will take
care to load any required plugins.
To wrap up our example, the application that wants to actually use
ImageFilter plug-ins would probably do a couple of things. First, it
would get a list of available ImageFilters to present to the user.
This could be accomplished as shown in Python Code Example 2 (Doxygen
only).
Then, when the user picks a filter from the list, it would manufacture
and instance of the filter as shown in Python Code Example 3 (Doxygen
only).
As was mentioned earlier, this plug-in facility tries to be as lazy as
possible about loading the code associated with plug-ins. To that end,
loading of a plugin will be deferred until an instance of a type is
manufactured which requires the plugin.
Multiple Subclasses of Multiple Plug-in Base Classes
====================================================
It is possible for a bundle to implement multiple subclasses for a
plug-in base class if desired. If you want to package half a dozen
ImageFilter subclasses in one bundle, that will work fine. All must be
declared in the plugInfo.json.
It is possible for there to be multiple classes in your application or
framework that are plug-in base classes. Plug-ins that implement
subclasses of any of these base classes can all coexist. And, it is
possible to have subclasses of multiple plug-in base classes in the
same bundle.
When putting multiple subclasses (of the same or different base
classes) in a bundle, keep in mind that dynamic loading happens for
the whole bundle the first time any subclass is needed, the whole
bundle will be loaded. But this is generally not a big concern.
For example, say the example application also has a plug-in base
class"ImageCodec"that allows people to add support for reading and
writing other image formats. Imagine that you want to supply a plug-in
that has two codecs and a filter all in a single plug-in. Your
plugInfo.json"Info"object might look something like this example.
.. code-block:: text
{
"Types": {
"MyTIFFCodec": {
"bases": ["ImageCodec"],
"displayName": "TIFF Image"
},
"MyJPEGCodec": {
"bases": ["ImageCodec"],
"displayName": "JPEG Image"
},
"MyCustomCoolFilter" : {
"bases": ["ImageFilter"],
"displayName": "Add Coolness to Image"
}
}
}
Dependencies on Other Plug-ins
==============================
If you write a plug-in that has dependencies on another plug-in that
you cannot (or do not want to) link against statically, you can
declare the dependencies in your plug-in's plugInfo.json. A plug-in
declares dependencies on other classes with a PluginDependencies key
whose value is a dictionary. The keys of the dictionary are plug-in
base class names and the values are arrays of subclass names.
The following example contains an example of a plug-in that depends on
two classes from the plug-in in the previous example.
.. code-block:: text
{
"Types": {
"UltraCoolFilter": {
"bases": ["MyCustomCoolFilter"],
"displayName": "Add Unbelievable Coolness to Image"
# A subclass of MyCustomCoolFilter that also uses MyTIFFCodec
}
},
"PluginDependencies": {
"ImageFilter": ["MyCustomCoolFilter"],
"ImageCodec": ["MyTIFFCodec"]
}
}
The ImageFilter provided by the plug-in in this example depends on the
other ImageFilter MyCoolImageFilter and the ImageCodec MyTIFFCodec.
Before loading this plug-in, the plug-in facility will ensure that
those two classes are present, loading the plug-in that contains them
if needed.
"""
result["Registry"].__init__.func_doc = """__init__(arg1)
Parameters
----------
arg1 : Registry
----------------------------------------------------------------------
__init__() -> PLUG_LOCAL
"""
result["Registry"].FindTypeByName.func_doc = """**classmethod** FindTypeByName(typeName) -> Type
Retrieve the ``TfType`` corresponding to the given ``name`` .
See the documentation for ``TfType::FindByName`` for more information.
Use this function if you expect that ``name`` may name a type provided
by a plugin. Calling this function will incur plugin discovery (but
not loading) if plugin discovery has not yet occurred.
Note that additional plugins may be registered during program runtime.
Plug-In Discovery & Registration
Parameters
----------
typeName : str
"""
result["Registry"].FindDerivedTypeByName.func_doc = """**classmethod** FindDerivedTypeByName(base, typeName) -> Type
Retrieve the ``TfType`` that derives from ``base`` and has the given
alias or type name ``typeName`` .
See the documentation for ``TfType::FindDerivedByName`` for more
information. Use this function if you expect that the derived type may
be provided by a plugin. Calling this function will incur plugin
discovery (but not loading) if plugin discovery has not yet occurred.
Note that additional plugins may be registered during program runtime.
Plug-In Discovery & Registration
Parameters
----------
base : Type
typeName : str
----------------------------------------------------------------------
FindDerivedTypeByName(typeName) -> Type
Retrieve the ``TfType`` that derives from ``Base`` and has the given
alias or type name ``typeName`` .
See the documentation for ``TfType::FindDerivedByName`` for more
information. Use this function if you expect that the derived type may
be provided by a plugin. Calling this function will incur plugin
discovery (but not loading) if plugin discovery has not yet occurred.
Note that additional plugins may be registered during program runtime.
Plug-In Discovery & Registration
Parameters
----------
typeName : str
"""
result["Registry"].GetDirectlyDerivedTypes.func_doc = """**classmethod** GetDirectlyDerivedTypes(base) -> list[Type]
Return a vector of types derived directly from *base*.
Use this function if you expect that plugins may provide types derived
from *base*. Otherwise, use *TfType::GetDirectlyDerivedTypes*.
Parameters
----------
base : Type
"""
result["Registry"].GetAllDerivedTypes.func_doc = """**classmethod** GetAllDerivedTypes(base, result) -> None
Return the set of all types derived (directly or indirectly) from
*base*.
Use this function if you expect that plugins may provide types derived
from *base*. Otherwise, use *TfType::GetAllDerivedTypes*.
Note that additional plugins may be registered during program runtime.
Plug-In Discovery & Registration
Parameters
----------
base : Type
result : set[Type]
----------------------------------------------------------------------
GetAllDerivedTypes(result) -> None
Return the set of all types derived (directly or indirectly) from
*Base*.
Use this function if you expect that plugins may provide types derived
from *base*. Otherwise, use *TfType::GetAllDerivedTypes*.
Note that additional plugins may be registered during program runtime.
Plug-In Discovery & Registration
Parameters
----------
result : set[Type]
"""
result["Registry"].RegisterPlugins.func_doc = """RegisterPlugins(pathToPlugInfo) -> list[PlugPluginPtr]
Registers all plug-ins discovered at *pathToPlugInfo*.
Sends PlugNotice::DidRegisterPlugins with any newly registered
plugins.
Parameters
----------
pathToPlugInfo : str
----------------------------------------------------------------------
RegisterPlugins(pathsToPlugInfo) -> list[PlugPluginPtr]
Registers all plug-ins discovered in any of *pathsToPlugInfo*.
Sends PlugNotice::DidRegisterPlugins with any newly registered
plugins.
Parameters
----------
pathsToPlugInfo : list[str]
"""
result["Registry"].GetPluginForType.func_doc = """GetPluginForType(t) -> Plugin
Returns the plug-in for the given type, or a null pointer if there is
no registered plug-in.
Parameters
----------
t : Type
"""
result["Registry"].GetAllPlugins.func_doc = """GetAllPlugins() -> list[PlugPluginPtr]
Returns all registered plug-ins.
Note that additional plugins may be registered during program runtime.
Plug-In Discovery & Registration
"""
result["Registry"].GetPluginWithName.func_doc = """GetPluginWithName(name) -> Plugin
Returns a plugin with the specified module name.
Note that additional plugins may be registered during program runtime.
Plug-In Discovery & Registration
Parameters
----------
name : str
"""
result["Registry"].GetStringFromPluginMetaData.func_doc = """GetStringFromPluginMetaData(type, key) -> str
Looks for a string associated with *type* and *key* and returns it, or
an empty string if *type* or *key* are not found.
Parameters
----------
type : Type
key : str
"""
result["Plugin"].isLoaded = property(result["Plugin"].isLoaded.fget, result["Plugin"].isLoaded.fset, result["Plugin"].isLoaded.fdel, """type : bool
Returns ``true`` if the plugin is currently loaded.
Resource plugins always report as loaded.
""")
result["Plugin"].isPythonModule = property(result["Plugin"].isPythonModule.fget, result["Plugin"].isPythonModule.fset, result["Plugin"].isPythonModule.fdel, """type : bool
Returns ``true`` if the plugin is a python module.
""")
result["Plugin"].isResource = property(result["Plugin"].isResource.fget, result["Plugin"].isResource.fset, result["Plugin"].isResource.fdel, """type : bool
Returns ``true`` if the plugin is resource-only.
""")
result["Plugin"].metadata = property(result["Plugin"].metadata.fget, result["Plugin"].metadata.fset, result["Plugin"].metadata.fdel, """type : JsObject
Returns the dictionary containing meta-data for the plugin.
""")
result["Plugin"].name = property(result["Plugin"].name.fget, result["Plugin"].name.fset, result["Plugin"].name.fdel, """type : str
Returns the plugin's name.
""")
result["Plugin"].path = property(result["Plugin"].path.fget, result["Plugin"].path.fset, result["Plugin"].path.fdel, """type : str
Returns the plugin's filesystem path.
""")
result["Plugin"].resourcePath = property(result["Plugin"].resourcePath.fget, result["Plugin"].resourcePath.fset, result["Plugin"].resourcePath.fdel, """type : str
Returns the plugin's resources filesystem path.
""") | 18,993 | Python | 28.402477 | 174 | 0.696046 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdShade/__DOC.py | def Execute(result):
result["ConnectableAPI"].__doc__ = """
UsdShadeConnectableAPI is an API schema that provides a common
interface for creating outputs and making connections between shading
parameters and outputs. The interface is common to all UsdShade
schemas that support Inputs and Outputs, which currently includes
UsdShadeShader, UsdShadeNodeGraph, and UsdShadeMaterial.
One can construct a UsdShadeConnectableAPI directly from a UsdPrim, or
from objects of any of the schema classes listed above. If it seems
onerous to need to construct a secondary schema object to interact
with Inputs and Outputs, keep in mind that any function whose purpose
is either to walk material/shader networks via their connections, or
to create such networks, can typically be written entirely in terms of
UsdShadeConnectableAPI objects, without needing to care what the
underlying prim type is.
Additionally, the most common UsdShadeConnectableAPI behaviors
(creating Inputs and Outputs, and making connections) are wrapped as
convenience methods on the prim schema classes (creation) and
UsdShadeInput and UsdShadeOutput.
"""
result["ConnectableAPI"].CanConnect.func_doc = """**classmethod** CanConnect(input, source) -> bool
Determines whether the given input can be connected to the given
source attribute, which can be an input or an output.
The result depends on the"connectability"of the input and the source
attributes. Depending on the prim type, this may require the plugin
that defines connectability behavior for that prim type be loaded.
UsdShadeInput::SetConnectability
UsdShadeInput::GetConnectability
Parameters
----------
input : Input
source : Attribute
----------------------------------------------------------------------
CanConnect(input, sourceInput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
sourceInput : Input
----------------------------------------------------------------------
CanConnect(input, sourceOutput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
sourceOutput : Output
----------------------------------------------------------------------
CanConnect(output, source) -> bool
Determines whether the given output can be connected to the given
source attribute, which can be an input or an output.
An output is considered to be connectable only if it belongs to a
node-graph. Shader outputs are not connectable.
``source`` is an optional argument. If a valid UsdAttribute is
supplied for it, this method will return true only if the source
attribute is owned by a descendant of the node-graph owning the
output.
Parameters
----------
output : Output
source : Attribute
----------------------------------------------------------------------
CanConnect(output, sourceInput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
sourceInput : Input
----------------------------------------------------------------------
CanConnect(output, sourceOutput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
sourceOutput : Output
"""
result["ConnectableAPI"].ConnectToSource.func_doc = """**classmethod** ConnectToSource(shadingAttr, source, mod) -> bool
Authors a connection for a given shading attribute ``shadingAttr`` .
``shadingAttr`` can represent a parameter, an input or an output.
``source`` is a struct that describes the upstream source attribute
with all the information necessary to make a connection. See the
documentation for UsdShadeConnectionSourceInfo. ``mod`` describes the
operation that should be applied to the list of connections. By
default the new connection will replace any existing connections, but
it can add to the list of connections to represent multiple input
connections.
``true`` if a connection was created successfully. ``false`` if
``shadingAttr`` or ``source`` is invalid.
This method does not verify the connectability of the shading
attribute to the source. Clients must invoke CanConnect() themselves
to ensure compatibility.
The source shading attribute is created if it doesn't exist already.
Parameters
----------
shadingAttr : Attribute
source : ConnectionSourceInfo
mod : ConnectionModification
----------------------------------------------------------------------
ConnectToSource(input, source, mod) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
source : ConnectionSourceInfo
mod : ConnectionModification
----------------------------------------------------------------------
ConnectToSource(output, source, mod) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
source : ConnectionSourceInfo
mod : ConnectionModification
----------------------------------------------------------------------
ConnectToSource(shadingAttr, source, sourceName, sourceType, typeName) -> bool
Deprecated
Please use the versions that take a UsdShadeConnectionSourceInfo to
describe the upstream source This is an overloaded member function,
provided for convenience. It differs from the above function only in
what argument(s) it accepts.
Parameters
----------
shadingAttr : Attribute
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
typeName : ValueTypeName
----------------------------------------------------------------------
ConnectToSource(input, source, sourceName, sourceType, typeName) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
typeName : ValueTypeName
----------------------------------------------------------------------
ConnectToSource(output, source, sourceName, sourceType, typeName) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
typeName : ValueTypeName
----------------------------------------------------------------------
ConnectToSource(shadingAttr, sourcePath) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Connect the given shading attribute to the source at path,
``sourcePath`` .
``sourcePath`` should be the fully namespaced property path.
This overload is provided for convenience, for use in contexts where
the prim types are unknown or unavailable.
Parameters
----------
shadingAttr : Attribute
sourcePath : Path
----------------------------------------------------------------------
ConnectToSource(input, sourcePath) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
sourcePath : Path
----------------------------------------------------------------------
ConnectToSource(output, sourcePath) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
sourcePath : Path
----------------------------------------------------------------------
ConnectToSource(shadingAttr, sourceInput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Connect the given shading attribute to the given source input.
Parameters
----------
shadingAttr : Attribute
sourceInput : Input
----------------------------------------------------------------------
ConnectToSource(input, sourceInput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
sourceInput : Input
----------------------------------------------------------------------
ConnectToSource(output, sourceInput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
sourceInput : Input
----------------------------------------------------------------------
ConnectToSource(shadingAttr, sourceOutput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Connect the given shading attribute to the given source output.
Parameters
----------
shadingAttr : Attribute
sourceOutput : Output
----------------------------------------------------------------------
ConnectToSource(input, sourceOutput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
sourceOutput : Output
----------------------------------------------------------------------
ConnectToSource(output, sourceOutput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
sourceOutput : Output
"""
result["ConnectableAPI"].SetConnectedSources.func_doc = """**classmethod** SetConnectedSources(shadingAttr, sourceInfos) -> bool
Authors a list of connections for a given shading attribute
``shadingAttr`` .
``shadingAttr`` can represent a parameter, an input or an output.
``sourceInfos`` is a vector of structs that describes the upstream
source attributes with all the information necessary to make all the
connections. See the documentation for UsdShadeConnectionSourceInfo.
``true`` if all connection were created successfully. ``false`` if the
``shadingAttr`` or one of the sources are invalid.
A valid connection is one that has a valid
``UsdShadeConnectionSourceInfo`` , which requires the existence of the
upstream source prim. It does not require the existence of the source
attribute as it will be create if necessary.
Parameters
----------
shadingAttr : Attribute
sourceInfos : list[ConnectionSourceInfo]
"""
result["ConnectableAPI"].GetConnectedSource.func_doc = """**classmethod** GetConnectedSource(shadingAttr, source, sourceName, sourceType) -> bool
Deprecated
Shading attributes can have multiple connections and so using
GetConnectedSources is needed in general
Finds the source of a connection for the given shading attribute.
``shadingAttr`` is the shading attribute whose connection we want to
interrogate. ``source`` is an output parameter which will be set to
the source connectable prim. ``sourceName`` will be set to the name of
the source shading attribute, which may be an input or an output, as
specified by ``sourceType`` ``sourceType`` will have the type of the
source shading attribute, i.e. whether it is an ``Input`` or
``Output``
``true`` if the shading attribute is connected to a valid, defined
source attribute. ``false`` if the shading attribute is not connected
to a single, defined source attribute.
Previously this method would silently return false for multiple
connections. We are changing the behavior of this method to return the
result for the first connection and issue a TfWarn about it. We want
to encourage clients to use GetConnectedSources going forward.
The python wrapping for this method returns a (source, sourceName,
sourceType) tuple if the parameter is connected, else ``None``
Parameters
----------
shadingAttr : Attribute
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
----------------------------------------------------------------------
GetConnectedSource(input, source, sourceName, sourceType) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
----------------------------------------------------------------------
GetConnectedSource(output, source, sourceName, sourceType) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
"""
result["ConnectableAPI"].GetConnectedSources.func_doc = """**classmethod** GetConnectedSources(shadingAttr, invalidSourcePaths) -> list[UsdShadeSourceInfo]
Finds the valid sources of connections for the given shading
attribute.
``shadingAttr`` is the shading attribute whose connections we want to
interrogate. ``invalidSourcePaths`` is an optional output parameter to
collect the invalid source paths that have not been reported in the
returned vector.
Returns a vector of ``UsdShadeConnectionSourceInfo`` structs with
information about each upsteam attribute. If the vector is empty,
there have been no connections.
A valid connection requires the existence of the source attribute and
also requires that the source prim is UsdShadeConnectableAPI
compatible.
The python wrapping returns a tuple with the valid connections first,
followed by the invalid source paths.
Parameters
----------
shadingAttr : Attribute
invalidSourcePaths : list[SdfPath]
----------------------------------------------------------------------
GetConnectedSources(input, invalidSourcePaths) -> list[UsdShadeSourceInfo]
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
invalidSourcePaths : list[SdfPath]
----------------------------------------------------------------------
GetConnectedSources(output, invalidSourcePaths) -> list[UsdShadeSourceInfo]
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
invalidSourcePaths : list[SdfPath]
"""
result["ConnectableAPI"].GetRawConnectedSourcePaths.func_doc = """**classmethod** GetRawConnectedSourcePaths(shadingAttr, sourcePaths) -> bool
Deprecated
Please us GetConnectedSources to retrieve multiple connections
Returns the"raw"(authored) connected source paths for the given
shading attribute.
Parameters
----------
shadingAttr : Attribute
sourcePaths : list[SdfPath]
----------------------------------------------------------------------
GetRawConnectedSourcePaths(input, sourcePaths) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
sourcePaths : list[SdfPath]
----------------------------------------------------------------------
GetRawConnectedSourcePaths(output, sourcePaths) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
sourcePaths : list[SdfPath]
"""
result["ConnectableAPI"].HasConnectedSource.func_doc = """**classmethod** HasConnectedSource(shadingAttr) -> bool
Returns true if and only if the shading attribute is currently
connected to at least one valid (defined) source.
If you will be calling GetConnectedSources() afterwards anyways, it
will be *much* faster to instead check if the returned vector is
empty:
.. code-block:: text
UsdShadeSourceInfoVector connections =
UsdShadeConnectableAPI::GetConnectedSources(attribute);
if (!connections.empty()){
// process connected attribute
} else {
// process unconnected attribute
}
Parameters
----------
shadingAttr : Attribute
----------------------------------------------------------------------
HasConnectedSource(input) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
----------------------------------------------------------------------
HasConnectedSource(output) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
"""
result["ConnectableAPI"].IsSourceConnectionFromBaseMaterial.func_doc = """**classmethod** IsSourceConnectionFromBaseMaterial(shadingAttr) -> bool
Returns true if the connection to the given shading attribute's
source, as returned by UsdShadeConnectableAPI::GetConnectedSource() ,
is authored across a specializes arc, which is used to denote a base
material.
Parameters
----------
shadingAttr : Attribute
----------------------------------------------------------------------
IsSourceConnectionFromBaseMaterial(input) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
----------------------------------------------------------------------
IsSourceConnectionFromBaseMaterial(output) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
"""
result["ConnectableAPI"].DisconnectSource.func_doc = """**classmethod** DisconnectSource(shadingAttr, sourceAttr) -> bool
Disconnect source for this shading attribute.
If ``sourceAttr`` is valid it will disconnect the connection to this
upstream attribute. Otherwise it will disconnect all connections by
authoring an empty list of connections for the attribute
``shadingAttr`` .
This may author more scene description than you might expect - we
define the behavior of disconnect to be that, even if a shading
attribute becomes connected in a weaker layer than the current
UsdEditTarget, the attribute will *still* be disconnected in the
composition, therefore we must"block"it in the current UsdEditTarget.
ConnectToSource() .
Parameters
----------
shadingAttr : Attribute
sourceAttr : Attribute
----------------------------------------------------------------------
DisconnectSource(input, sourceAttr) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
sourceAttr : Attribute
----------------------------------------------------------------------
DisconnectSource(output, sourceAttr) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
sourceAttr : Attribute
"""
result["ConnectableAPI"].ClearSources.func_doc = """**classmethod** ClearSources(shadingAttr) -> bool
Clears sources for this shading attribute in the current
UsdEditTarget.
Most of the time, what you probably want is DisconnectSource() rather
than this function.
DisconnectSource()
Parameters
----------
shadingAttr : Attribute
----------------------------------------------------------------------
ClearSources(input) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
----------------------------------------------------------------------
ClearSources(output) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
"""
result["ConnectableAPI"].ClearSource.func_doc = """**classmethod** ClearSource(shadingAttr) -> bool
Deprecated
This is the older version that only referenced a single source. Please
use ClearSources instead.
Parameters
----------
shadingAttr : Attribute
----------------------------------------------------------------------
ClearSource(input) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
input : Input
----------------------------------------------------------------------
ClearSource(output) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
"""
result["ConnectableAPI"].HasConnectableAPI.func_doc = """**classmethod** HasConnectableAPI(schemaType) -> bool
Return true if the ``schemaType`` has a valid connectableAPIBehavior
registered, false otherwise.
To check if a prim's connectableAPI has a behavior defined, use
UsdSchemaBase::operator bool() .
Parameters
----------
schemaType : Type
----------------------------------------------------------------------
HasConnectableAPI() -> bool
Return true if the schema type ``T`` has a connectableAPIBehavior
registered, false otherwise.
"""
result["ConnectableAPI"].CreateOutput.func_doc = """CreateOutput(name, typeName) -> Output
Create an output, which represents and externally computed, typed
value.
Outputs on node-graphs can be connected.
The attribute representing an output is created in
the"outputs:"namespace.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["ConnectableAPI"].GetOutput.func_doc = """GetOutput(name) -> Output
Return the requested output if it exists.
``name`` is the unnamespaced base name.
Parameters
----------
name : str
"""
result["ConnectableAPI"].GetOutputs.func_doc = """GetOutputs(onlyAuthored) -> list[Output]
Returns all outputs on the connectable prim (i.e.
shader or node-graph). Outputs are represented by attributes in
the"outputs:"namespace. If ``onlyAuthored`` is true (the default),
then only return authored attributes; otherwise, this also returns un-
authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["ConnectableAPI"].CreateInput.func_doc = """CreateInput(name, typeName) -> Input
Create an input which can both have a value and be connected.
The attribute representing the input is created in
the"inputs:"namespace.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["ConnectableAPI"].GetInput.func_doc = """GetInput(name) -> Input
Return the requested input if it exists.
``name`` is the unnamespaced base name.
Parameters
----------
name : str
"""
result["ConnectableAPI"].GetInputs.func_doc = """GetInputs(onlyAuthored) -> list[Input]
Returns all inputs on the connectable prim (i.e.
shader or node-graph). Inputs are represented by attributes in
the"inputs:"namespace. If ``onlyAuthored`` is true (the default), then
only return authored attributes; otherwise, this also returns un-
authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["ConnectableAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdShadeConnectableAPI on UsdPrim ``prim`` .
Equivalent to UsdShadeConnectableAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdShadeConnectableAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdShadeConnectableAPI (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["ConnectableAPI"].IsContainer.func_doc = """IsContainer() -> bool
Returns true if the prim is a container.
The underlying prim type may provide runtime behavior that defines
whether it is a container.
"""
result["ConnectableAPI"].RequiresEncapsulation.func_doc = """RequiresEncapsulation() -> bool
Returns true if container encapsulation rules should be respected when
evaluating connectibility behavior, false otherwise.
The underlying prim type may provide runtime behavior that defines if
encapsulation rules are respected or not.
"""
result["ConnectableAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["ConnectableAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> ConnectableAPI
Return a UsdShadeConnectableAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdShadeConnectableAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["ConnectableAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["ConnectionSourceInfo"].__doc__ = """
A compact struct to represent a bundle of information about an
upstream source attribute.
"""
result["ConnectionSourceInfo"].__init__.func_doc = """__init__()
----------------------------------------------------------------------
__init__(source_, sourceName_, sourceType_, typeName_)
Parameters
----------
source_ : ConnectableAPI
sourceName_ : str
sourceType_ : AttributeType
typeName_ : ValueTypeName
----------------------------------------------------------------------
__init__(input)
Parameters
----------
input : Input
----------------------------------------------------------------------
__init__(output)
Parameters
----------
output : Output
----------------------------------------------------------------------
__init__(stage, sourcePath)
Construct the information for this struct from a property path.
The source attribute does not have to exist, but the ``sourcePath``
needs to have a valid prefix to identify the sourceType. The source
prim needs to exist and be UsdShadeConnectableAPI compatible
Parameters
----------
stage : Stage
sourcePath : Path
"""
result["ConnectionSourceInfo"].IsValid.func_doc = """IsValid() -> bool
Return true if this source info is valid for setting up a connection.
"""
result["CoordSysAPI"].__doc__ = """
UsdShadeCoordSysAPI provides a way to designate, name, and discover
coordinate systems.
Coordinate systems are implicitly established by UsdGeomXformable
prims, using their local space. That coordinate system may be bound
(i.e., named) from another prim. The binding is encoded as a single-
target relationship in the"coordSys:"namespace. Coordinate system
bindings apply to descendants of the prim where the binding is
expressed, but names may be re-bound by descendant prims.
Named coordinate systems are useful in shading workflows. An example
is projection paint, which projects a texture from a certain view (the
paint coordinate system). Using the paint coordinate frame avoids the
need to assign a UV set to the object, and can be a concise way to
project paint across a collection of objects with a single shared
paint coordinate system.
This is a non-applied API schema.
"""
result["CoordSysAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdShadeCoordSysAPI on UsdPrim ``prim`` .
Equivalent to UsdShadeCoordSysAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdShadeCoordSysAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdShadeCoordSysAPI (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["CoordSysAPI"].HasLocalBindings.func_doc = """HasLocalBindings() -> bool
Returns true if the prim has local coordinate system binding opinions.
Note that the resulting binding list may still be empty.
"""
result["CoordSysAPI"].GetLocalBindings.func_doc = """GetLocalBindings() -> list[Binding]
Get the list of coordinate system bindings local to this prim.
This does not process inherited bindings. It does not validate that a
prim exists at the indicated path. If the binding relationship has
multiple targets, only the first is used.
"""
result["CoordSysAPI"].FindBindingsWithInheritance.func_doc = """FindBindingsWithInheritance() -> list[Binding]
Find the list of coordinate system bindings that apply to this prim,
including inherited bindings.
This computation examines this prim and ancestors for the strongest
binding for each name. A binding expressed by a child prim supercedes
bindings on ancestors.
Note that this API does not validate the prims at the target paths;
they may be of incorrect type, or missing entirely.
Binding relationships with no resolved targets are skipped.
"""
result["CoordSysAPI"].Bind.func_doc = """Bind(name, path) -> bool
Bind the name to the given path.
The prim at the given path is expected to be UsdGeomXformable, in
order for the binding to be succesfully resolved.
Parameters
----------
name : str
path : Path
"""
result["CoordSysAPI"].ClearBinding.func_doc = """ClearBinding(name, removeSpec) -> bool
Clear the indicated coordinate system binding on this prim from the
current edit target.
Only remove the spec if ``removeSpec`` is true (leave the spec to
preserve meta-data we may have intentionally authored on the
relationship)
Parameters
----------
name : str
removeSpec : bool
"""
result["CoordSysAPI"].BlockBinding.func_doc = """BlockBinding(name) -> bool
Block the indicated coordinate system binding on this prim by blocking
targets on the underlying relationship.
Parameters
----------
name : str
"""
result["CoordSysAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["CoordSysAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> CoordSysAPI
Return a UsdShadeCoordSysAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdShadeCoordSysAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["CoordSysAPI"].GetCoordSysRelationshipName.func_doc = """**classmethod** GetCoordSysRelationshipName(coordSysName) -> str
Returns the fully namespaced coordinate system relationship name,
given the coordinate system name.
Parameters
----------
coordSysName : str
"""
result["CoordSysAPI"].CanContainPropertyName.func_doc = """**classmethod** CanContainPropertyName(name) -> bool
Test whether a given ``name`` contains the"coordSys:"prefix.
Parameters
----------
name : str
"""
result["CoordSysAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Input"].__doc__ = """
This class encapsulates a shader or node-graph input, which is a
connectable attribute representing a typed value.
"""
result["Input"].SetRenderType.func_doc = """SetRenderType(renderType) -> bool
Specify an alternative, renderer-specific type to use when
emitting/translating this Input, rather than translating based on its
GetTypeName()
For example, we set the renderType to"struct"for Inputs that are of
renderman custom struct types.
true on success.
Parameters
----------
renderType : str
"""
result["Input"].GetRenderType.func_doc = """GetRenderType() -> str
Return this Input's specialized renderType, or an empty token if none
was authored.
SetRenderType()
"""
result["Input"].HasRenderType.func_doc = """HasRenderType() -> bool
Return true if a renderType has been specified for this Input.
SetRenderType()
"""
result["Input"].GetSdrMetadata.func_doc = """GetSdrMetadata() -> NdrTokenMap
Returns this Input's composed"sdrMetadata"dictionary as a NdrTokenMap.
"""
result["Input"].GetSdrMetadataByKey.func_doc = """GetSdrMetadataByKey(key) -> str
Returns the value corresponding to ``key`` in the composed
**sdrMetadata** dictionary.
Parameters
----------
key : str
"""
result["Input"].SetSdrMetadata.func_doc = """SetSdrMetadata(sdrMetadata) -> None
Authors the given ``sdrMetadata`` value on this Input at the current
EditTarget.
Parameters
----------
sdrMetadata : NdrTokenMap
"""
result["Input"].SetSdrMetadataByKey.func_doc = """SetSdrMetadataByKey(key, value) -> None
Sets the value corresponding to ``key`` to the given string ``value``
, in the Input's"sdrMetadata"dictionary at the current EditTarget.
Parameters
----------
key : str
value : str
"""
result["Input"].HasSdrMetadata.func_doc = """HasSdrMetadata() -> bool
Returns true if the Input has a non-empty
composed"sdrMetadata"dictionary value.
"""
result["Input"].HasSdrMetadataByKey.func_doc = """HasSdrMetadataByKey(key) -> bool
Returns true if there is a value corresponding to the given ``key`` in
the composed"sdrMetadata"dictionary.
Parameters
----------
key : str
"""
result["Input"].ClearSdrMetadata.func_doc = """ClearSdrMetadata() -> None
Clears any"sdrMetadata"value authored on the Input in the current
EditTarget.
"""
result["Input"].ClearSdrMetadataByKey.func_doc = """ClearSdrMetadataByKey(key) -> None
Clears the entry corresponding to the given ``key`` in
the"sdrMetadata"dictionary authored in the current EditTarget.
Parameters
----------
key : str
"""
result["Input"].__init__.func_doc = """__init__(attr)
Speculative constructor that will produce a valid UsdShadeInput when
``attr`` already represents a shade Input, and produces an *invalid*
UsdShadeInput otherwise (i.e.
the explicit bool conversion operator will return false).
Parameters
----------
attr : Attribute
----------------------------------------------------------------------
__init__()
Default constructor returns an invalid Input.
Exists for the sake of container classes
----------------------------------------------------------------------
__init__(prim, name, typeName)
Parameters
----------
prim : Prim
name : str
typeName : ValueTypeName
"""
result["Input"].GetAttr.func_doc = """GetAttr() -> Attribute
Explicit UsdAttribute extractor.
"""
result["Input"].SetDocumentation.func_doc = """SetDocumentation(docs) -> bool
Set documentation string for this Input.
UsdObject::SetDocumentation()
Parameters
----------
docs : str
"""
result["Input"].GetDocumentation.func_doc = """GetDocumentation() -> str
Get documentation string for this Input.
UsdObject::GetDocumentation()
"""
result["Input"].SetDisplayGroup.func_doc = """SetDisplayGroup(displayGroup) -> bool
Set the displayGroup metadata for this Input, i.e.
hinting for the location and nesting of the attribute.
Note for an input representing a nested SdrShaderProperty, its
expected to have the scope delimited by a":".
UsdProperty::SetDisplayGroup() , UsdProperty::SetNestedDisplayGroup()
SdrShaderProperty::GetPage()
Parameters
----------
displayGroup : str
"""
result["Input"].GetDisplayGroup.func_doc = """GetDisplayGroup() -> str
Get the displayGroup metadata for this Input, i.e.
hint for the location and nesting of the attribute.
UsdProperty::GetDisplayGroup() , UsdProperty::GetNestedDisplayGroup()
"""
result["Input"].IsInput.func_doc = """**classmethod** IsInput(attr) -> bool
Test whether a given UsdAttribute represents a valid Input, which
implies that creating a UsdShadeInput from the attribute will succeed.
Success implies that ``attr.IsDefined()`` is true.
Parameters
----------
attr : Attribute
"""
result["Input"].IsInterfaceInputName.func_doc = """**classmethod** IsInterfaceInputName(name) -> bool
Test if this name has a namespace that indicates it could be an input.
Parameters
----------
name : str
"""
result["Input"].CanConnect.func_doc = """CanConnect(source) -> bool
Determines whether this Input can be connected to the given source
attribute, which can be an input or an output.
UsdShadeConnectableAPI::CanConnect
Parameters
----------
source : Attribute
----------------------------------------------------------------------
CanConnect(sourceInput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
sourceInput : Input
----------------------------------------------------------------------
CanConnect(sourceOutput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
sourceOutput : Output
"""
result["Input"].ConnectToSource.func_doc = """ConnectToSource(source, mod) -> bool
Authors a connection for this Input.
``source`` is a struct that describes the upstream source attribute
with all the information necessary to make a connection. See the
documentation for UsdShadeConnectionSourceInfo. ``mod`` describes the
operation that should be applied to the list of connections. By
default the new connection will replace any existing connections, but
it can add to the list of connections to represent multiple input
connections.
``true`` if a connection was created successfully. ``false`` if this
input or ``source`` is invalid.
This method does not verify the connectability of the shading
attribute to the source. Clients must invoke CanConnect() themselves
to ensure compatibility.
The source shading attribute is created if it doesn't exist already.
UsdShadeConnectableAPI::ConnectToSource
Parameters
----------
source : ConnectionSourceInfo
mod : ConnectionModification
----------------------------------------------------------------------
ConnectToSource(source, sourceName, sourceType, typeName) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
typeName : ValueTypeName
----------------------------------------------------------------------
ConnectToSource(sourcePath) -> bool
Authors a connection for this Input to the source at the given path.
UsdShadeConnectableAPI::ConnectToSource
Parameters
----------
sourcePath : Path
----------------------------------------------------------------------
ConnectToSource(sourceInput) -> bool
Connects this Input to the given input, ``sourceInput`` .
UsdShadeConnectableAPI::ConnectToSource
Parameters
----------
sourceInput : Input
----------------------------------------------------------------------
ConnectToSource(sourceOutput) -> bool
Connects this Input to the given output, ``sourceOutput`` .
UsdShadeConnectableAPI::ConnectToSource
Parameters
----------
sourceOutput : Output
"""
result["Input"].SetConnectedSources.func_doc = """SetConnectedSources(sourceInfos) -> bool
Connects this Input to the given sources, ``sourceInfos`` .
UsdShadeConnectableAPI::SetConnectedSources
Parameters
----------
sourceInfos : list[ConnectionSourceInfo]
"""
result["Input"].GetConnectedSources.func_doc = """GetConnectedSources(invalidSourcePaths) -> list[SourceInfo]
Finds the valid sources of connections for the Input.
``invalidSourcePaths`` is an optional output parameter to collect the
invalid source paths that have not been reported in the returned
vector.
Returns a vector of ``UsdShadeConnectionSourceInfo`` structs with
information about each upsteam attribute. If the vector is empty,
there have been no valid connections.
A valid connection requires the existence of the source attribute and
also requires that the source prim is UsdShadeConnectableAPI
compatible.
The python wrapping returns a tuple with the valid connections first,
followed by the invalid source paths.
UsdShadeConnectableAPI::GetConnectedSources
Parameters
----------
invalidSourcePaths : list[SdfPath]
"""
result["Input"].GetConnectedSource.func_doc = """GetConnectedSource(source, sourceName, sourceType) -> bool
Deprecated
Parameters
----------
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
"""
result["Input"].GetRawConnectedSourcePaths.func_doc = """GetRawConnectedSourcePaths(sourcePaths) -> bool
Deprecated
Returns the"raw"(authored) connected source paths for this Input.
UsdShadeConnectableAPI::GetRawConnectedSourcePaths
Parameters
----------
sourcePaths : list[SdfPath]
"""
result["Input"].HasConnectedSource.func_doc = """HasConnectedSource() -> bool
Returns true if and only if this Input is currently connected to a
valid (defined) source.
UsdShadeConnectableAPI::HasConnectedSource
"""
result["Input"].IsSourceConnectionFromBaseMaterial.func_doc = """IsSourceConnectionFromBaseMaterial() -> bool
Returns true if the connection to this Input's source, as returned by
GetConnectedSource() , is authored across a specializes arc, which is
used to denote a base material.
UsdShadeConnectableAPI::IsSourceConnectionFromBaseMaterial
"""
result["Input"].DisconnectSource.func_doc = """DisconnectSource(sourceAttr) -> bool
Disconnect source for this Input.
If ``sourceAttr`` is valid, only a connection to the specified
attribute is disconnected, otherwise all connections are removed.
UsdShadeConnectableAPI::DisconnectSource
Parameters
----------
sourceAttr : Attribute
"""
result["Input"].ClearSources.func_doc = """ClearSources() -> bool
Clears sources for this Input in the current UsdEditTarget.
Most of the time, what you probably want is DisconnectSource() rather
than this function.
UsdShadeConnectableAPI::ClearSources
"""
result["Input"].ClearSource.func_doc = """ClearSource() -> bool
Deprecated
"""
result["Input"].SetConnectability.func_doc = """SetConnectability(connectability) -> bool
Set the connectability of the Input.
In certain shading data models, there is a need to distinguish which
inputs **can** vary over a surface from those that must be
**uniform**. This is accomplished in UsdShade by limiting the
connectability of the input. This is done by setting
the"connectability"metadata on the associated attribute.
Connectability of an Input can be set to UsdShadeTokens->full or
UsdShadeTokens->interfaceOnly.
- **full** implies that the Input can be connected to any other
Input or Output.
- **interfaceOnly** implies that the Input can only be connected to
a NodeGraph Input (which represents an interface override, not a
render-time dataflow connection), or another Input whose
connectability is also"interfaceOnly".
The default connectability of an input is UsdShadeTokens->full.
SetConnectability()
Parameters
----------
connectability : str
"""
result["Input"].GetConnectability.func_doc = """GetConnectability() -> str
Returns the connectability of the Input.
SetConnectability()
"""
result["Input"].ClearConnectability.func_doc = """ClearConnectability() -> bool
Clears any authored connectability on the Input.
"""
result["Input"].GetValueProducingAttributes.func_doc = """GetValueProducingAttributes(shaderOutputsOnly) -> list[UsdShadeAttribute]
Find what is connected to this Input recursively.
UsdShadeUtils::GetValueProducingAttributes
Parameters
----------
shaderOutputsOnly : bool
"""
result["Input"].GetValueProducingAttribute.func_doc = """GetValueProducingAttribute(attrType) -> Attribute
Deprecated
in favor of calling GetValueProducingAttributes
Parameters
----------
attrType : AttributeType
"""
result["Input"].GetFullName.func_doc = """GetFullName() -> str
Get the name of the attribute associated with the Input.
"""
result["Input"].GetBaseName.func_doc = """GetBaseName() -> str
Returns the name of the input.
We call this the base name since it strips off the"inputs:"namespace
prefix from the attribute name, and returns it.
"""
result["Input"].GetTypeName.func_doc = """GetTypeName() -> ValueTypeName
Get the"scene description"value type name of the attribute associated
with the Input.
"""
result["Input"].GetPrim.func_doc = """GetPrim() -> Prim
Get the prim that the input belongs to.
"""
result["Input"].Get.func_doc = """Get(value, time) -> bool
Convenience wrapper for the templated UsdAttribute::Get() .
Parameters
----------
value : T
time : TimeCode
----------------------------------------------------------------------
Get(value, time) -> bool
Convenience wrapper for VtValue version of UsdAttribute::Get() .
Parameters
----------
value : VtValue
time : TimeCode
"""
result["Input"].Set.func_doc = """Set(value, time) -> bool
Set a value for the Input at ``time`` .
Parameters
----------
value : VtValue
time : TimeCode
----------------------------------------------------------------------
Set(value, time) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Set a value of the Input at ``time`` .
Parameters
----------
value : T
time : TimeCode
"""
result["Material"].__doc__ = """
A Material provides a container into which multiple"render targets"can
add data that defines a"shading material"for a renderer. Typically
this consists of one or more UsdRelationship properties that target
other prims of type *Shader* - though a target/client is free to add
any data that is suitable. We **strongly advise** that all targets
adopt the convention that all properties be prefixed with a namespace
that identifies the target, e.g."rel ri:surface =</Shaders/mySurf>".
In the UsdShading model, geometry expresses a binding to a single
Material or to a set of Materials partitioned by UsdGeomSubsets
defined beneath the geometry; it is legal to bind a Material at the
root (or other sub-prim) of a model, and then bind a different
Material to individual gprims, but the meaning of inheritance
and"ancestral overriding"of Material bindings is left to each render-
target to determine. Since UsdGeom has no concept of shading, we
provide the API for binding and unbinding geometry on the API schema
UsdShadeMaterialBindingAPI.
The entire power of USD VariantSets and all the other composition
operators can leveraged when encoding shading variation.
UsdShadeMaterial provides facilities for a particular way of
building"Material variants"in which neither the identity of the
Materials themselves nor the geometry Material-bindings need to change
\\- instead we vary the targeted networks, interface values, and even
parameter values within a single variantSet. See Authoring Material
Variations for more details.
UsdShade requires that all of the shaders that"belong"to the Material
live under the Material in namespace. This supports powerful, easy
reuse of Materials, because it allows us to *reference* a Material
from one asset (the asset might be a module of Materials) into
another asset: USD references compose all descendant prims of the
reference target into the referencer's namespace, which means that all
of the referenced Material's shader networks will come along with the
Material. When referenced in this way, Materials can also be
instanced, for ease of deduplication and compactness. Finally,
Material encapsulation also allows us to specialize child materials
from parent materials.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdShadeTokens. So to set an attribute to the value"rightHanded",
use UsdShadeTokens->rightHanded as the value.
"""
result["Material"].CreateSurfaceOutput.func_doc = """CreateSurfaceOutput(renderContext) -> Output
Creates and returns the"surface"output on this material for the
specified ``renderContext`` .
If the output already exists on the material, it is returned and no
authoring is performed. The returned output will always have the
requested renderContext.
Parameters
----------
renderContext : str
"""
result["Material"].GetSurfaceOutput.func_doc = """GetSurfaceOutput(renderContext) -> Output
Returns the"surface"output of this material for the specified
``renderContext`` .
The returned output will always have the requested renderContext.
An invalid output is returned if an output corresponding to the
requested specific-renderContext does not exist.
UsdShadeMaterial::ComputeSurfaceSource()
Parameters
----------
renderContext : str
"""
result["Material"].GetSurfaceOutputs.func_doc = """GetSurfaceOutputs() -> list[Output]
Returns the"surface"outputs of this material for all available
renderContexts.
The returned vector will include all authored"surface"outputs with the
*universal* renderContext output first, if present. Outputs are
returned regardless of whether they are connected to a valid source.
"""
result["Material"].ComputeSurfaceSource.func_doc = """ComputeSurfaceSource(renderContext, sourceName, sourceType) -> Shader
Deprecated
Use the form that takes a TfTokenVector or renderContexts.
Parameters
----------
renderContext : str
sourceName : str
sourceType : AttributeType
----------------------------------------------------------------------
ComputeSurfaceSource(contextVector, sourceName, sourceType) -> Shader
Computes the resolved"surface"output source for the given
``contextVector`` .
Using the earliest renderContext in the contextVector that produces a
valid Shader object.
If a"surface"output corresponding to each of the renderContexts does
not exist **or** is not connected to a valid source, then this checks
the *universal* surface output.
Returns an empty Shader object if there is no valid *surface* output
source for any of the renderContexts in the ``contextVector`` . The
python version of this method returns a tuple containing three
elements (the source surface shader, sourceName, sourceType).
Parameters
----------
contextVector : list[TfToken]
sourceName : str
sourceType : AttributeType
"""
result["Material"].CreateDisplacementOutput.func_doc = """CreateDisplacementOutput(renderContext) -> Output
Creates and returns the"displacement"output on this material for the
specified ``renderContext`` .
If the output already exists on the material, it is returned and no
authoring is performed. The returned output will always have the
requested renderContext.
Parameters
----------
renderContext : str
"""
result["Material"].GetDisplacementOutput.func_doc = """GetDisplacementOutput(renderContext) -> Output
Returns the"displacement"output of this material for the specified
renderContext.
The returned output will always have the requested renderContext.
An invalid output is returned if an output corresponding to the
requested specific-renderContext does not exist.
UsdShadeMaterial::ComputeDisplacementSource()
Parameters
----------
renderContext : str
"""
result["Material"].GetDisplacementOutputs.func_doc = """GetDisplacementOutputs() -> list[Output]
Returns the"displacement"outputs of this material for all available
renderContexts.
The returned vector will include all authored"displacement"outputs
with the *universal* renderContext output first, if present. Outputs
are returned regardless of whether they are connected to a valid
source.
"""
result["Material"].ComputeDisplacementSource.func_doc = """ComputeDisplacementSource(renderContext, sourceName, sourceType) -> Shader
Deprecated
Use the form that takes a TfTokenVector or renderContexts
Parameters
----------
renderContext : str
sourceName : str
sourceType : AttributeType
----------------------------------------------------------------------
ComputeDisplacementSource(contextVector, sourceName, sourceType) -> Shader
Computes the resolved"displacement"output source for the given
``contextVector`` .
Using the earliest renderContext in the contextVector that produces a
valid Shader object.
If a"displacement"output corresponding to each of the renderContexts
does not exist **or** is not connected to a valid source, then this
checks the *universal* displacement output.
Returns an empty Shader object if there is no valid *displacement*
output source for any of the renderContexts in the ``contextVector`` .
The python version of this method returns a tuple containing three
elements (the source displacement shader, sourceName, sourceType).
Parameters
----------
contextVector : list[TfToken]
sourceName : str
sourceType : AttributeType
"""
result["Material"].CreateVolumeOutput.func_doc = """CreateVolumeOutput(renderContext) -> Output
Creates and returns the"volume"output on this material for the
specified ``renderContext`` .
If the output already exists on the material, it is returned and no
authoring is performed. The returned output will always have the
requested renderContext.
Parameters
----------
renderContext : str
"""
result["Material"].GetVolumeOutput.func_doc = """GetVolumeOutput(renderContext) -> Output
Returns the"volume"output of this material for the specified
renderContext.
The returned output will always have the requested renderContext.
An invalid output is returned if an output corresponding to the
requested specific-renderContext does not exist.
UsdShadeMaterial::ComputeVolumeSource()
Parameters
----------
renderContext : str
"""
result["Material"].GetVolumeOutputs.func_doc = """GetVolumeOutputs() -> list[Output]
Returns the"volume"outputs of this material for all available
renderContexts.
The returned vector will include all authored"volume"outputs with the
*universal* renderContext output first, if present. Outputs are
returned regardless of whether they are connected to a valid source.
"""
result["Material"].ComputeVolumeSource.func_doc = """ComputeVolumeSource(renderContext, sourceName, sourceType) -> Shader
Deprecated
Use the form that takes a TfTokenVector or renderContexts
Parameters
----------
renderContext : str
sourceName : str
sourceType : AttributeType
----------------------------------------------------------------------
ComputeVolumeSource(contextVector, sourceName, sourceType) -> Shader
Computes the resolved"volume"output source for the given
``contextVector`` .
Using the earliest renderContext in the contextVector that produces a
valid Shader object.
If a"volume"output corresponding to each of the renderContexts does
not exist **or** is not connected to a valid source, then this checks
the *universal* volume output.
Returns an empty Shader object if there is no valid *volume* output
output source for any of the renderContexts in the ``contextVector`` .
The python version of this method returns a tuple containing three
elements (the source volume shader, sourceName, sourceType).
Parameters
----------
contextVector : list[TfToken]
sourceName : str
sourceType : AttributeType
"""
result["Material"].GetEditContextForVariant.func_doc = """GetEditContextForVariant(MaterialVariantName, layer) -> tuple[Stage, EditTarget]
Helper function for configuring a UsdStage 's UsdEditTarget to author
Material variations.
Takes care of creating the Material variantSet and specified variant,
if necessary.
Let's assume that we are authoring Materials into the Stage's current
UsdEditTarget, and that we are iterating over the variations of a
UsdShadeMaterial *clothMaterial*, and *currVariant* is the variant we
are processing (e.g."denim").
In C++, then, we would use the following pattern:
.. code-block:: text
{
UsdEditContext ctxt(clothMaterial.GetEditContextForVariant(currVariant));
// All USD mutation of the UsdStage on which clothMaterial sits will
// now go "inside" the currVariant of the "MaterialVariant" variantSet
}
In python, the pattern is:
.. code-block:: text
with clothMaterial.GetEditContextForVariant(currVariant):
# Now sending mutations to currVariant
If ``layer`` is specified, then we will use it, rather than the
stage's current UsdEditTarget 's layer as the destination layer for
the edit context we are building. If ``layer`` does not actually
contribute to the Material prim's definition, any editing will have no
effect on this Material.
**Note:** As just stated, using this method involves authoring a
selection for the MaterialVariant in the stage's current EditTarget.
When client is done authoring variations on this prim, they will
likely want to either UsdVariantSet::SetVariantSelection() to the
appropriate default selection, or possibly
UsdVariantSet::ClearVariantSelection() on the
UsdShadeMaterial::GetMaterialVariant() UsdVariantSet.
UsdVariantSet::GetVariantEditContext()
Parameters
----------
MaterialVariantName : str
layer : Layer
"""
result["Material"].GetMaterialVariant.func_doc = """GetMaterialVariant() -> VariantSet
Return a UsdVariantSet object for interacting with the Material
variant variantSet.
"""
result["Material"].CreateMasterMaterialVariant.func_doc = """**classmethod** CreateMasterMaterialVariant(masterPrim, MaterialPrims, masterVariantSetName) -> bool
Create a variantSet on ``masterPrim`` that will set the
MaterialVariant on each of the given *MaterialPrims*.
The variantSet, whose name can be specified with
``masterVariantSetName`` and defaults to the same MaterialVariant name
created on Materials by GetEditContextForVariant() , will have the
same variants as the Materials, and each Master variant will set every
``MaterialPrims'`` MaterialVariant selection to the same variant as
the master. Thus, it allows all Materials to be switched with a single
variant selection, on ``masterPrim`` .
If ``masterPrim`` is an ancestor of any given member of
``MaterialPrims`` , then we will author variant selections directly on
the MaterialPrims. However, it is often preferable to create a master
MaterialVariant in a separately rooted tree from the MaterialPrims, so
that it can be layered more strongly on top of the Materials.
Therefore, for any MaterialPrim in a different tree than masterPrim,
we will create"overs"as children of masterPrim that recreate the path
to the MaterialPrim, substituting masterPrim's full path for the
MaterialPrim's root path component.
Upon successful completion, the new variantSet we created on
``masterPrim`` will have its variant selection authored to
the"last"variant (determined lexicographically). It is up to the
calling client to either UsdVariantSet::ClearVariantSelection() on
``masterPrim`` , or set the selection to the desired default setting.
Return ``true`` on success. It is an error if any of ``Materials``
have a different set of variants for the MaterialVariant than the
others.
Parameters
----------
masterPrim : Prim
MaterialPrims : list[Prim]
masterVariantSetName : str
"""
result["Material"].GetBaseMaterial.func_doc = """GetBaseMaterial() -> Material
Get the path to the base Material of this Material.
If there is no base Material, an empty Material is returned
"""
result["Material"].GetBaseMaterialPath.func_doc = """GetBaseMaterialPath() -> Path
Get the base Material of this Material.
If there is no base Material, an empty path is returned
"""
result["Material"].SetBaseMaterial.func_doc = """SetBaseMaterial(baseMaterial) -> None
Set the base Material of this Material.
An empty Material is equivalent to clearing the base Material.
Parameters
----------
baseMaterial : Material
"""
result["Material"].SetBaseMaterialPath.func_doc = """SetBaseMaterialPath(baseMaterialPath) -> None
Set the path to the base Material of this Material.
An empty path is equivalent to clearing the base Material.
Parameters
----------
baseMaterialPath : Path
"""
result["Material"].ClearBaseMaterial.func_doc = """ClearBaseMaterial() -> None
Clear the base Material of this Material.
"""
result["Material"].HasBaseMaterial.func_doc = """HasBaseMaterial() -> bool
"""
result["Material"].__init__.func_doc = """__init__(prim)
Construct a UsdShadeMaterial on UsdPrim ``prim`` .
Equivalent to UsdShadeMaterial::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdShadeMaterial on the prim held by ``schemaObj`` .
Should be preferred over UsdShadeMaterial (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Material"].GetSurfaceAttr.func_doc = """GetSurfaceAttr() -> Attribute
Represents the universal"surface"output terminal of a material.
Declaration
``token outputs:surface``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["Material"].CreateSurfaceAttr.func_doc = """CreateSurfaceAttr(defaultValue, writeSparsely) -> Attribute
See GetSurfaceAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Material"].GetDisplacementAttr.func_doc = """GetDisplacementAttr() -> Attribute
Represents the universal"displacement"output terminal of a material.
Declaration
``token outputs:displacement``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["Material"].CreateDisplacementAttr.func_doc = """CreateDisplacementAttr(defaultValue, writeSparsely) -> Attribute
See GetDisplacementAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Material"].GetVolumeAttr.func_doc = """GetVolumeAttr() -> Attribute
Represents the universal"volume"output terminal of a material.
Declaration
``token outputs:volume``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["Material"].CreateVolumeAttr.func_doc = """CreateVolumeAttr(defaultValue, writeSparsely) -> Attribute
See GetVolumeAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Material"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Material"].Get.func_doc = """**classmethod** Get(stage, path) -> Material
Return a UsdShadeMaterial holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdShadeMaterial(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Material"].Define.func_doc = """**classmethod** Define(stage, path) -> Material
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Material"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["MaterialBindingAPI"].__doc__ = """
UsdShadeMaterialBindingAPI is an API schema that provides an interface
for binding materials to prims or collections of prims (represented by
UsdCollectionAPI objects).
In the USD shading model, each renderable gprim computes a single
**resolved Material** that will be used to shade the gprim
(exceptions, of course, for gprims that possess UsdGeomSubsets, as
each subset can be shaded by a different Material). A gprim **and each
of its ancestor prims** can possess, through the MaterialBindingAPI,
both a **direct** binding to a Material, and any number of
**collection-based** bindings to Materials; each binding can be
generic or declared for a particular **purpose**, and given a specific
**binding strength**. It is the process of"material resolution"(see
UsdShadeMaterialBindingAPI_MaterialResolution) that examines all of
these bindings, and selects the one Material that best matches the
client's needs.
The intent of **purpose** is that each gprim should be able to resolve
a Material for any given purpose, which implies it can have
differently bound materials for different purposes. There are two
*special* values of **purpose** defined in UsdShade, although the API
fully supports specifying arbitrary values for it, for the sake of
extensibility:
- **UsdShadeTokens->full** : to be used when the purpose of the
render is entirely to visualize the truest representation of a scene,
considering all lighting and material information, at highest
fidelity.
- **UsdShadeTokens->preview** : to be used when the render is in
service of a goal other than a high fidelity"full"render (such as
scene manipulation, modeling, or realtime playback). Latency and speed
are generally of greater concern for preview renders, therefore
preview materials are generally designed to be"lighterweight"compared
to full materials.
A binding can also have no specific purpose at all, in which case, it
is considered to be the fallback or all-purpose binding (denoted by
the empty-valued token **UsdShadeTokens->allPurpose**).
The **purpose** of a material binding is encoded in the name of the
binding relationship.
- In the case of a direct binding, the *allPurpose* binding is
represented by the relationship named **"material:binding"**. Special-
purpose direct bindings are represented by relationships named
**"material:binding: *purpose***. A direct binding relationship must
have a single target path that points to a **UsdShadeMaterial**.
- In the case of a collection-based binding, the *allPurpose*
binding is represented by a relationship
named"material:binding:collection:<i>bindingName</i>", where
**bindingName** establishes an identity for the binding that is unique
on the prim. Attempting to establish two collection bindings of the
same name on the same prim will result in the first binding simply
being overridden. A special-purpose collection-based binding is
represented by a relationship
named"material:binding:collection:<i>purpose:bindingName</i>". A
collection-based binding relationship must have exacly two targets,
one of which should be a collection-path (see ef
UsdCollectionAPI::GetCollectionPath() ) and the other should point to
a **UsdShadeMaterial**. In the future, we may allow a single
collection binding to target multiple collections, if we can establish
a reasonable round-tripping pattern for applications that only allow a
single collection to be associated with each Material.
**Note:** Both **bindingName** and **purpose** must be non-namespaced
tokens. This allows us to know the role of a binding relationship
simply from the number of tokens in it.
- **Two tokens** : the fallback,"all purpose", direct binding,
*material:binding*
- **Three tokens** : a purpose-restricted, direct, fallback
binding, e.g. material:binding:preview
- **Four tokens** : an all-purpose, collection-based binding, e.g.
material:binding:collection:metalBits
- **Five tokens** : a purpose-restricted, collection-based binding,
e.g. material:binding:collection:full:metalBits
A **binding-strength** value is used to specify whether a binding
authored on a prim should be weaker or stronger than bindings that
appear lower in namespace. We encode the binding strength with as
token-valued metadata **'bindMaterialAs'** for future flexibility,
even though for now, there are only two possible values:
*UsdShadeTokens->weakerThanDescendants* and
*UsdShadeTokens->strongerThanDescendants*. When binding-strength is
not authored (i.e. empty) on a binding-relationship, the default
behavior matches UsdShadeTokens->weakerThanDescendants.
If a material binding relationship is a built-in property defined as
part of a typed prim's schema, a fallback value should not be provided
for it. This is because the"material resolution"algorithm only
conisders *authored* properties.
"""
result["MaterialBindingAPI"].GetDirectBindingRel.func_doc = """GetDirectBindingRel(materialPurpose) -> Relationship
Returns the direct material-binding relationship on this prim for the
given material purpose.
The material purpose of the relationship that's returned will match
the specified ``materialPurpose`` .
Parameters
----------
materialPurpose : str
"""
result["MaterialBindingAPI"].GetCollectionBindingRel.func_doc = """GetCollectionBindingRel(bindingName, materialPurpose) -> Relationship
Returns the collection-based material-binding relationship with the
given ``bindingName`` and ``materialPurpose`` on this prim.
For info on ``bindingName`` , see UsdShadeMaterialBindingAPI::Bind() .
The material purpose of the relationship that's returned will match
the specified ``materialPurpose`` .
Parameters
----------
bindingName : str
materialPurpose : str
"""
result["MaterialBindingAPI"].GetCollectionBindingRels.func_doc = """GetCollectionBindingRels(materialPurpose) -> list[Relationship]
Returns the list of collection-based material binding relationships on
this prim for the given material purpose, ``materialPurpose`` .
The returned list of binding relationships will be in native property
order. See UsdPrim::GetPropertyOrder() , UsdPrim::SetPropertyOrder() .
Bindings that appear earlier in the property order are considered to
be stronger than the ones that come later. See rule #6 in
UsdShadeMaterialBindingAPI_MaterialResolution.
Parameters
----------
materialPurpose : str
"""
result["MaterialBindingAPI"].GetDirectBinding.func_doc = """GetDirectBinding(materialPurpose) -> DirectBinding
Computes and returns the direct binding for the given material purpose
on this prim.
The returned binding always has the specified ``materialPurpose``
(i.e. the all-purpose binding is not returned if a special purpose
binding is requested).
If the direct binding is to a prim that is not a Material, this does
not generate an error, but the returned Material will be invalid (i.e.
evaluate to false).
Parameters
----------
materialPurpose : str
"""
result["MaterialBindingAPI"].GetCollectionBindings.func_doc = """GetCollectionBindings(materialPurpose) -> list[CollectionBinding]
Returns all the collection-based bindings on this prim for the given
material purpose.
The returned CollectionBinding objects always have the specified
``materialPurpose`` (i.e. the all-purpose binding is not returned if a
special purpose binding is requested).
If one or more collection based bindings are to prims that are not
Materials, this does not generate an error, but the corresponding
Material(s) will be invalid (i.e. evaluate to false).
The python version of this API returns a tuple containing the vector
of CollectionBinding objects and the corresponding vector of binding
relationships.
The returned list of collection-bindings will be in native property
order of the associated binding relationships. See
UsdPrim::GetPropertyOrder() , UsdPrim::SetPropertyOrder() . Binding
relationships that come earlier in the list are considered to be
stronger than the ones that come later. See rule #6 in
UsdShadeMaterialBindingAPI_MaterialResolution.
Parameters
----------
materialPurpose : str
"""
result["MaterialBindingAPI"].GetMaterialBindingStrength.func_doc = """**classmethod** GetMaterialBindingStrength(bindingRel) -> str
Resolves the'bindMaterialAs'token-valued metadata on the given binding
relationship and returns it.
If the resolved value is empty, this returns the fallback value
UsdShadeTokens->weakerThanDescendants.
UsdShadeMaterialBindingAPI::SetMaterialBindingStrength()
Parameters
----------
bindingRel : Relationship
"""
result["MaterialBindingAPI"].SetMaterialBindingStrength.func_doc = """**classmethod** SetMaterialBindingStrength(bindingRel, bindingStrength) -> bool
Sets the'bindMaterialAs'token-valued metadata on the given binding
relationship.
If ``bindingStrength`` is *UsdShadeTokens->fallbackStrength*, the
value UsdShadeTokens->weakerThanDescendants is authored sparsely, i.e.
only when there is a different existing bindingStrength value. To
stamp out the bindingStrength value explicitly, clients can pass in
UsdShadeTokens->weakerThanDescendants or
UsdShadeTokens->strongerThanDescendants directly. Returns true on
success, false otherwise.
UsdShadeMaterialBindingAPI::GetMaterialBindingStrength()
Parameters
----------
bindingRel : Relationship
bindingStrength : str
"""
result["MaterialBindingAPI"].Bind.func_doc = """Bind(material, bindingStrength, materialPurpose) -> bool
Authors a direct binding to the given ``material`` on this prim.
If ``bindingStrength`` is UsdShadeTokens->fallbackStrength, the value
UsdShadeTokens->weakerThanDescendants is authored sparsely. To stamp
out the bindingStrength value explicitly, clients can pass in
UsdShadeTokens->weakerThanDescendants or
UsdShadeTokens->strongerThanDescendants directly.
If ``materialPurpose`` is specified and isn't equal to
UsdShadeTokens->allPurpose, the binding only applies to the specified
material purpose.
Note that UsdShadeMaterialBindingAPI is a SingleAppliedAPI schema
which when applied updates the prim definition accordingly. This
information on the prim definition is helpful in multiple queries and
more performant. Hence its recommended to call
UsdShadeMaterialBindingAPI::Apply() when Binding a material.
Returns true on success, false otherwise.
Parameters
----------
material : Material
bindingStrength : str
materialPurpose : str
----------------------------------------------------------------------
Bind(collection, material, bindingName, bindingStrength, materialPurpose) -> bool
Authors a collection-based binding, which binds the given ``material``
to the given ``collection`` on this prim.
``bindingName`` establishes an identity for the binding that is unique
on the prim. Attempting to establish two collection bindings of the
same name on the same prim will result in the first binding simply
being overridden. If ``bindingName`` is empty, it is set to the base-
name of the collection being bound (which is the collection-name with
any namespaces stripped out). If there are multiple collections with
the same base-name being bound at the same prim, clients should pass
in a unique binding name per binding, in order to preserve all
bindings. The binding name used in constructing the collection-binding
relationship name shoud not contain namespaces. Hence, a coding error
is issued and no binding is authored if the provided value of
``bindingName`` is non-empty and contains namespaces.
If ``bindingStrength`` is *UsdShadeTokens->fallbackStrength*, the
value UsdShadeTokens->weakerThanDescendants is authored sparsely, i.e.
only when there is an existing binding with a different
bindingStrength. To stamp out the bindingStrength value explicitly,
clients can pass in UsdShadeTokens->weakerThanDescendants or
UsdShadeTokens->strongerThanDescendants directly.
If ``materialPurpose`` is specified and isn't equal to
UsdShadeTokens->allPurpose, the binding only applies to the specified
material purpose.
Note that UsdShadeMaterialBindingAPI is a SingleAppliedAPI schema
which when applied updates the prim definition accordingly. This
information on the prim definition is helpful in multiple queries and
more performant. Hence its recommended to call
UsdShadeMaterialBindingAPI::Apply() when Binding a material.
Returns true on success, false otherwise.
Parameters
----------
collection : CollectionAPI
material : Material
bindingName : str
bindingStrength : str
materialPurpose : str
"""
result["MaterialBindingAPI"].UnbindDirectBinding.func_doc = """UnbindDirectBinding(materialPurpose) -> bool
Unbinds the direct binding for the given material purpose (
``materialPurpose`` ) on this prim.
It accomplishes this by blocking the targets of the binding
relationship in the current edit target.
Parameters
----------
materialPurpose : str
"""
result["MaterialBindingAPI"].UnbindCollectionBinding.func_doc = """UnbindCollectionBinding(bindingName, materialPurpose) -> bool
Unbinds the collection-based binding with the given ``bindingName`` ,
for the given ``materialPurpose`` on this prim.
It accomplishes this by blocking the targets of the associated binding
relationship in the current edit target.
If a binding was created without specifying a ``bindingName`` , then
the correct ``bindingName`` to use for unbinding is the instance name
of the targetted collection.
Parameters
----------
bindingName : str
materialPurpose : str
"""
result["MaterialBindingAPI"].UnbindAllBindings.func_doc = """UnbindAllBindings() -> bool
Unbinds all direct and collection-based bindings on this prim.
"""
result["MaterialBindingAPI"].RemovePrimFromBindingCollection.func_doc = """RemovePrimFromBindingCollection(prim, bindingName, materialPurpose) -> bool
Removes the specified ``prim`` from the collection targeted by the
binding relationship corresponding to given ``bindingName`` and
``materialPurpose`` .
If the collection-binding relationship doesn't exist or if the
targeted collection does not include the ``prim`` , then this does
nothing and returns true.
If the targeted collection includes ``prim`` , then this modifies the
collection by removing the prim from it (by invoking
UsdCollectionAPI::RemovePrim()). This method can be used in
conjunction with the Unbind\\*() methods (if desired) to guarantee
that a prim has no resolved material binding.
Parameters
----------
prim : Prim
bindingName : str
materialPurpose : str
"""
result["MaterialBindingAPI"].AddPrimToBindingCollection.func_doc = """AddPrimToBindingCollection(prim, bindingName, materialPurpose) -> bool
Adds the specified ``prim`` to the collection targeted by the binding
relationship corresponding to given ``bindingName`` and
``materialPurpose`` .
If the collection-binding relationship doesn't exist or if the
targeted collection already includes the ``prim`` , then this does
nothing and returns true.
If the targeted collection does not include ``prim`` (or excludes it
explicitly), then this modifies the collection by adding the prim to
it (by invoking UsdCollectionAPI::AddPrim()).
Parameters
----------
prim : Prim
bindingName : str
materialPurpose : str
"""
result["MaterialBindingAPI"].ComputeBoundMaterial.func_doc = """ComputeBoundMaterial(bindingsCache, collectionQueryCache, materialPurpose, bindingRel) -> Material
Computes the resolved bound material for this prim, for the given
material purpose.
This overload of ComputeBoundMaterial makes use of the BindingsCache (
``bindingsCache`` ) and CollectionQueryCache (
``collectionQueryCache`` ) that are passed in, to avoid redundant
binding computations and computations of MembershipQuery objects for
collections. It would be beneficial to make use of these when
resolving bindings for a tree of prims. These caches are populated
lazily as more and more bindings are resolved.
When the goal is to compute the bound material for a range (or list)
of prims, it is recommended to use this version of
ComputeBoundMaterial() . Here's how you could compute the bindings of
a range of prims efficiently in C++:
.. code-block:: text
std::vector<std::pair<UsdPrim, UsdShadeMaterial> primBindings;
UsdShadeMaterialBindingAPI::BindingsCache bindingsCache;
UsdShadeMaterialBindingAPI::CollectionQueryCache collQueryCache;
for (auto prim : UsdPrimRange(rootPrim)) {
UsdShadeMaterial boundMaterial =
UsdShadeMaterialBindingAPI(prim).ComputeBoundMaterial(
& bindingsCache, & collQueryCache);
if (boundMaterial) {
primBindings.emplace_back({prim, boundMaterial});
}
}
If ``bindingRel`` is not null, then it is set to the"winning"binding
relationship.
Note the resolved bound material is considered valid if the target
path of the binding relationship is a valid non-empty prim path. This
makes sure winning binding relationship and the bound material remain
consistent consistent irrespective of the presence/absence of prim at
material path. For ascenario where ComputeBoundMaterial returns a
invalid UsdShadeMaterial with a valid winning bindingRel, clients can
use the static method
UsdShadeMaterialBindingAPI::GetResolvedTargetPathFromBindingRel to get
the path of the resolved target identified by the winning bindingRel.
See Bound Material Resolution for details on the material resolution
process.
The python version of this method returns a tuple containing the bound
material and the"winning"binding relationship.
Parameters
----------
bindingsCache : BindingsCache
collectionQueryCache : CollectionQueryCache
materialPurpose : str
bindingRel : Relationship
----------------------------------------------------------------------
ComputeBoundMaterial(materialPurpose, bindingRel) -> Material
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the resolved bound material for this prim, for the given
material purpose.
This overload does not utilize cached MembershipQuery object. However,
it only computes the MembershipQuery of every collection that bound in
the ancestor chain at most once.
If ``bindingRel`` is not null, then it is set to the winning binding
relationship.
See Bound Material Resolution for details on the material resolution
process.
The python version of this method returns a tuple containing the bound
material and the"winning"binding relationship.
Parameters
----------
materialPurpose : str
bindingRel : Relationship
"""
result["MaterialBindingAPI"].GetMaterialPurposes.func_doc = """**classmethod** GetMaterialPurposes() -> list[TfToken]
Returns a vector of the possible values for the'material purpose'.
"""
result["MaterialBindingAPI"].GetResolvedTargetPathFromBindingRel.func_doc = """**classmethod** GetResolvedTargetPathFromBindingRel(bindingRel) -> Path
returns the path of the resolved target identified by ``bindingRel`` .
Parameters
----------
bindingRel : Relationship
"""
result["MaterialBindingAPI"].ComputeBoundMaterials.func_doc = """**classmethod** ComputeBoundMaterials(prims, materialPurpose, bindingRels) -> list[Material]
Static API for efficiently and concurrently computing the resolved
material bindings for a vector of UsdPrims, ``prims`` for the given
``materialPurpose`` .
The size of the returned vector always matches the size of the input
vector, ``prims`` . If a prim is not bound to any material, an invalid
or empty UsdShadeMaterial is returned at the index corresponding to
it.
If the pointer ``bindingRels`` points to a valid vector, then it is
populated with the set of all"winning"binding relationships.
The python version of this method returns a tuple containing two lists
\\- the bound materials and the corresponding"winning"binding
relationships.
Parameters
----------
prims : list[Prim]
materialPurpose : str
bindingRels : list[Relationship]
"""
result["MaterialBindingAPI"].CreateMaterialBindSubset.func_doc = """CreateMaterialBindSubset(subsetName, indices, elementType) -> Subset
Creates a GeomSubset named ``subsetName`` with element type,
``elementType`` and familyName **materialBind **below this prim.****
If a GeomSubset named ``subsetName`` already exists, then
its"familyName"is updated to be UsdShadeTokens->materialBind and its
indices (at *default* timeCode) are updated with the provided
``indices`` value before returning.
This method forces the familyType of the"materialBind"family of
subsets to UsdGeomTokens->nonOverlapping if it's unset or explicitly
set to UsdGeomTokens->unrestricted.
The default value ``elementType`` is UsdGeomTokens->face, as we expect
materials to be bound most often to subsets of faces on meshes.
Parameters
----------
subsetName : str
indices : IntArray
elementType : str
"""
result["MaterialBindingAPI"].GetMaterialBindSubsets.func_doc = """GetMaterialBindSubsets() -> list[Subset]
Returns all the existing GeomSubsets with
familyName=UsdShadeTokens->materialBind below this prim.
"""
result["MaterialBindingAPI"].SetMaterialBindSubsetsFamilyType.func_doc = """SetMaterialBindSubsetsFamilyType(familyType) -> bool
Author the *familyType* of the"materialBind"family of GeomSubsets on
this prim.
The default ``familyType`` is *UsdGeomTokens->nonOverlapping *. It can
be set to *UsdGeomTokens->partition* to indicate that the entire
imageable prim is included in the union of all
the"materialBind"subsets. The family type should never be set to
UsdGeomTokens->unrestricted, since it is invalid for a single piece of
geometry (in this case, a subset) to be bound to more than one
material. Hence, a coding error is issued if ``familyType`` is
UsdGeomTokens->unrestricted.**
**
UsdGeomSubset::SetFamilyType**
Parameters
----------
familyType : str
"""
result["MaterialBindingAPI"].GetMaterialBindSubsetsFamilyType.func_doc = """GetMaterialBindSubsetsFamilyType() -> str
Returns the familyType of the family of"materialBind"GeomSubsets on
this prim.
By default, materialBind subsets have familyType="nonOverlapping", but
they can also be tagged as a"partition", using
SetMaterialBindFaceSubsetsFamilyType().
UsdGeomSubset::GetFamilyNameAttr
"""
result["MaterialBindingAPI"].CanContainPropertyName.func_doc = """**classmethod** CanContainPropertyName(name) -> bool
Test whether a given ``name`` contains the"material:binding:"prefix.
Parameters
----------
name : str
"""
result["MaterialBindingAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdShadeMaterialBindingAPI on UsdPrim ``prim`` .
Equivalent to UsdShadeMaterialBindingAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdShadeMaterialBindingAPI on the prim held by
``schemaObj`` .
Should be preferred over UsdShadeMaterialBindingAPI
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["MaterialBindingAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["MaterialBindingAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> MaterialBindingAPI
Return a UsdShadeMaterialBindingAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdShadeMaterialBindingAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["MaterialBindingAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["MaterialBindingAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> MaterialBindingAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"MaterialBindingAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdShadeMaterialBindingAPI object is returned upon success. An
invalid (or empty) UsdShadeMaterialBindingAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["MaterialBindingAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["NodeDefAPI"].__doc__ = """
UsdShadeNodeDefAPI is an API schema that provides attributes for a
prim to select a corresponding Shader Node Definition ("Sdr Node"), as
well as to look up a runtime entry for that shader node in the form of
an SdrShaderNode.
UsdShadeNodeDefAPI is intended to be a pre-applied API schema for any
prim type that wants to refer to the SdrRegistry for further
implementation details about the behavior of that prim. The primary
use in UsdShade itself is as UsdShadeShader, which is a basis for
material shading networks (UsdShadeMaterial), but this is intended to
be used in other domains that also use the Sdr node mechanism.
This schema provides properties that allow a prim to identify an
external node definition, either by a direct identifier key into the
SdrRegistry (info:id), an asset to be parsed by a suitable
NdrParserPlugin (info:sourceAsset), or an inline source code that must
also be parsed (info:sourceCode); as well as a selector attribute to
determine which specifier is active (info:implementationSource).
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdShadeTokens. So to set an attribute to the value"rightHanded",
use UsdShadeTokens->rightHanded as the value.
"""
result["NodeDefAPI"].GetImplementationSource.func_doc = """GetImplementationSource() -> str
Reads the value of info:implementationSource attribute and returns a
token identifying the attribute that must be consulted to identify the
shader's source program.
This returns
- **id**, to indicate that the"info:id"attribute must be consulted.
- **sourceAsset** to indicate that the asset-
valued"info:{sourceType}:sourceAsset"attribute associated with the
desired **sourceType** should be consulted to locate the asset with
the shader's source.
- **sourceCode** to indicate that the string-
valued"info:{sourceType}:sourceCode"attribute associated with the
desired **sourceType** should be read to get shader's source.
This issues a warning and returns **id** if the
*info:implementationSource* attribute has an invalid value.
*{sourceType}* above is a place holder for a token that identifies the
type of shader source or its implementation. For example: osl, glslfx,
riCpp etc. This allows a shader to specify different sourceAsset (or
sourceCode) values for different sourceTypes. The sourceType tokens
usually correspond to the sourceType value of the NdrParserPlugin
that's used to parse the shader source (NdrParserPlugin::SourceType).
When sourceType is empty, the corresponding sourceAsset or sourceCode
is considered to be"universal"(or fallback), which is represented by
the empty-valued token UsdShadeTokens->universalSourceType. When the
sourceAsset (or sourceCode) corresponding to a specific, requested
sourceType is unavailable, the universal sourceAsset (or sourceCode)
is returned by GetSourceAsset (and GetSourceCode} API, if present.
GetShaderId()
GetSourceAsset()
GetSourceCode()
"""
result["NodeDefAPI"].SetShaderId.func_doc = """SetShaderId(id) -> bool
Sets the shader's ID value.
This also sets the *info:implementationSource* attribute on the shader
to **UsdShadeTokens->id**, if the existing value is different.
Parameters
----------
id : str
"""
result["NodeDefAPI"].GetShaderId.func_doc = """GetShaderId(id) -> bool
Fetches the shader's ID value from the *info:id* attribute, if the
shader's *info:implementationSource* is **id**.
Returns **true** if the shader's implementation source is **id** and
the value was fetched properly into ``id`` . Returns false otherwise.
GetImplementationSource()
Parameters
----------
id : str
"""
result["NodeDefAPI"].SetSourceAsset.func_doc = """SetSourceAsset(sourceAsset, sourceType) -> bool
Sets the shader's source-asset path value to ``sourceAsset`` for the
given source type, ``sourceType`` .
This also sets the *info:implementationSource* attribute on the shader
to **UsdShadeTokens->sourceAsset**.
Parameters
----------
sourceAsset : AssetPath
sourceType : str
"""
result["NodeDefAPI"].GetSourceAsset.func_doc = """GetSourceAsset(sourceAsset, sourceType) -> bool
Fetches the shader's source asset value for the specified
``sourceType`` value from the **info: *sourceType*: sourceAsset**
attribute, if the shader's *info:implementationSource* is
**sourceAsset**.
If the *sourceAsset* attribute corresponding to the requested
*sourceType* isn't present on the shader, then the *universal*
*fallback* sourceAsset attribute, i.e. *info:sourceAsset* is
consulted, if present, to get the source asset path.
Returns **true** if the shader's implementation source is
**sourceAsset** and the source asset path value was fetched
successfully into ``sourceAsset`` . Returns false otherwise.
GetImplementationSource()
Parameters
----------
sourceAsset : AssetPath
sourceType : str
"""
result["NodeDefAPI"].SetSourceAssetSubIdentifier.func_doc = """SetSourceAssetSubIdentifier(subIdentifier, sourceType) -> bool
Set a sub-identifier to be used with a source asset of the given
source type.
This sets the **info: *sourceType*: sourceAsset:subIdentifier**.
This also sets the *info:implementationSource* attribute on the shader
to **UsdShadeTokens->sourceAsset**
Parameters
----------
subIdentifier : str
sourceType : str
"""
result["NodeDefAPI"].GetSourceAssetSubIdentifier.func_doc = """GetSourceAssetSubIdentifier(subIdentifier, sourceType) -> bool
Fetches the shader's sub-identifier for the source asset with the
specified ``sourceType`` value from the **info: *sourceType*:
sourceAsset:subIdentifier** attribute, if the shader's *info:
implementationSource* is **sourceAsset**.
If the *subIdentifier* attribute corresponding to the requested
*sourceType* isn't present on the shader, then the *universal*
*fallback* sub-identifier attribute, i.e. *info:sourceAsset:
subIdentifier* is consulted, if present, to get the sub-identifier
name.
Returns **true** if the shader's implementation source is
**sourceAsset** and the sub-identifier for the given source type was
fetched successfully into ``subIdentifier`` . Returns false otherwise.
Parameters
----------
subIdentifier : str
sourceType : str
"""
result["NodeDefAPI"].SetSourceCode.func_doc = """SetSourceCode(sourceCode, sourceType) -> bool
Sets the shader's source-code value to ``sourceCode`` for the given
source type, ``sourceType`` .
This also sets the *info:implementationSource* attribute on the shader
to **UsdShadeTokens->sourceCode**.
Parameters
----------
sourceCode : str
sourceType : str
"""
result["NodeDefAPI"].GetSourceCode.func_doc = """GetSourceCode(sourceCode, sourceType) -> bool
Fetches the shader's source code for the specified ``sourceType``
value by reading the **info: *sourceType*: sourceCode** attribute, if
the shader's *info:implementationSource* is **sourceCode**.
If the *sourceCode* attribute corresponding to the requested
*sourceType* isn't present on the shader, then the *universal* or
*fallback* sourceCode attribute (i.e. *info:sourceCode*) is consulted,
if present, to get the source code.
Returns **true** if the shader's implementation source is
**sourceCode** and the source code string was fetched successfully
into ``sourceCode`` . Returns false otherwise.
GetImplementationSource()
Parameters
----------
sourceCode : str
sourceType : str
"""
result["NodeDefAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdShadeNodeDefAPI on UsdPrim ``prim`` .
Equivalent to UsdShadeNodeDefAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdShadeNodeDefAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdShadeNodeDefAPI (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["NodeDefAPI"].GetImplementationSourceAttr.func_doc = """GetImplementationSourceAttr() -> Attribute
Specifies the attribute that should be consulted to get the shader's
implementation or its source code.
- If set to"id", the"info:id"attribute's value is used to determine
the shader source from the shader registry.
- If set to"sourceAsset", the resolved value of
the"info:sourceAsset"attribute corresponding to the desired
implementation (or source-type) is used to locate the shader source. A
source asset file may also specify multiple shader definitions, so
there is an optional attribute"info:sourceAsset:subIdentifier"whose
value should be used to indicate a particular shader definition from a
source asset file.
- If set to"sourceCode", the value of"info:sourceCode"attribute
corresponding to the desired implementation (or source type) is used
as the shader source.
Declaration
``uniform token info:implementationSource ="id"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
id, sourceAsset, sourceCode
"""
result["NodeDefAPI"].CreateImplementationSourceAttr.func_doc = """CreateImplementationSourceAttr(defaultValue, writeSparsely) -> Attribute
See GetImplementationSourceAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NodeDefAPI"].GetIdAttr.func_doc = """GetIdAttr() -> Attribute
The id is an identifier for the type or purpose of the shader.
E.g.: Texture or FractalFloat. The use of this id will depend on the
render target: some will turn it into an actual shader path, some will
use it to generate shader source code dynamically.
SetShaderId()
Declaration
``uniform token info:id``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["NodeDefAPI"].CreateIdAttr.func_doc = """CreateIdAttr(defaultValue, writeSparsely) -> Attribute
See GetIdAttr() , and also Create vs Get Property Methods for when to
use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NodeDefAPI"].GetShaderNodeForSourceType.func_doc = """GetShaderNodeForSourceType(sourceType) -> ShaderNode
This method attempts to ensure that there is a ShaderNode in the
shader registry (i.e.
SdrRegistry) representing this shader for the given ``sourceType`` .
It may return a null pointer if none could be found or created.
Parameters
----------
sourceType : str
"""
result["NodeDefAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["NodeDefAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> NodeDefAPI
Return a UsdShadeNodeDefAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdShadeNodeDefAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["NodeDefAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["NodeDefAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> NodeDefAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"NodeDefAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdShadeNodeDefAPI object is returned upon success. An invalid
(or empty) UsdShadeNodeDefAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["NodeDefAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["NodeGraph"].__doc__ = """
A node-graph is a container for shading nodes, as well as other node-
graphs. It has a public input interface and provides a list of public
outputs.
**Node Graph Interfaces**
One of the most important functions of a node-graph is to host
the"interface"with which clients of already-built shading networks
will interact. Please see Interface Inputs for a detailed explanation
of what the interface provides, and how to construct and use it, to
effectively share/instance shader networks.
**Node Graph Outputs**
These behave like outputs on a shader and are typically connected to
an output on a shader inside the node-graph.
"""
result["NodeGraph"].CreateOutput.func_doc = """CreateOutput(name, typeName) -> Output
Create an output which can either have a value or can be connected.
The attribute representing the output is created in
the"outputs:"namespace.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["NodeGraph"].GetOutput.func_doc = """GetOutput(name) -> Output
Return the requested output if it exists.
Parameters
----------
name : str
"""
result["NodeGraph"].GetOutputs.func_doc = """GetOutputs(onlyAuthored) -> list[Output]
Outputs are represented by attributes in the"outputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["NodeGraph"].ComputeOutputSource.func_doc = """ComputeOutputSource(outputName, sourceName, sourceType) -> Shader
Deprecated
in favor of GetValueProducingAttributes on UsdShadeOutput Resolves the
connection source of the requested output, identified by
``outputName`` to a shader output.
``sourceName`` is an output parameter that is set to the name of the
resolved output, if the node-graph output is connected to a valid
shader source.
``sourceType`` is an output parameter that is set to the type of the
resolved output, if the node-graph output is connected to a valid
shader source.
Returns a valid shader object if the specified output exists and is
connected to one. Return an empty shader object otherwise. The python
version of this method returns a tuple containing three elements (the
source shader, sourceName, sourceType).
Parameters
----------
outputName : str
sourceName : str
sourceType : AttributeType
"""
result["NodeGraph"].CreateInput.func_doc = """CreateInput(name, typeName) -> Input
Create an Input which can either have a value or can be connected.
The attribute representing the input is created in
the"inputs:"namespace.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["NodeGraph"].GetInput.func_doc = """GetInput(name) -> Input
Return the requested input if it exists.
Parameters
----------
name : str
"""
result["NodeGraph"].GetInputs.func_doc = """GetInputs(onlyAuthored) -> list[Input]
Returns all inputs present on the node-graph.
These are represented by attributes in the"inputs:"namespace. If
``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["NodeGraph"].GetInterfaceInputs.func_doc = """GetInterfaceInputs() -> list[Input]
Returns all the"Interface Inputs"of the node-graph.
This is the same as GetInputs() , but is provided as a convenience, to
allow clients to distinguish between inputs on shaders vs. interface-
inputs on node-graphs.
"""
result["NodeGraph"].ComputeInterfaceInputConsumersMap.func_doc = """ComputeInterfaceInputConsumersMap(computeTransitiveConsumers) -> InterfaceInputConsumersMap
Walks the namespace subtree below the node-graph and computes a map
containing the list of all inputs on the node-graph and the associated
vector of consumers of their values.
The consumers can be inputs on shaders within the node-graph or on
nested node-graphs).
If ``computeTransitiveConsumers`` is true, then value consumers
belonging to **node-graphs** are resolved transitively to compute the
transitive mapping from inputs on the node-graph to inputs on shaders
inside the material. Note that inputs on node-graphs that don't have
value consumers will continue to be included in the result.
This API is provided for use by DCC's that want to present node-graph
interface / shader connections in the opposite direction than they are
encoded in USD.
Parameters
----------
computeTransitiveConsumers : bool
"""
result["NodeGraph"].__init__.func_doc = """__init__(prim)
Construct a UsdShadeNodeGraph on UsdPrim ``prim`` .
Equivalent to UsdShadeNodeGraph::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdShadeNodeGraph on the prim held by ``schemaObj`` .
Should be preferred over UsdShadeNodeGraph (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
----------------------------------------------------------------------
__init__(connectable)
Constructor that takes a ConnectableAPI object.
Allow implicit (auto) conversion of UsdShadeConnectableAPI to
UsdShadeNodeGraph, so that a ConnectableAPI can be passed into any
function that accepts a NodeGraph.
that the conversion may produce an invalid NodeGraph object, because
not all UsdShadeConnectableAPI s are UsdShadeNodeGraph s
Parameters
----------
connectable : ConnectableAPI
"""
result["NodeGraph"].ConnectableAPI.func_doc = """ConnectableAPI() -> ConnectableAPI
Contructs and returns a UsdShadeConnectableAPI object with this node-
graph.
Note that most tasks can be accomplished without explicitly
constructing a UsdShadeConnectable API, since connection-related API
such as UsdShadeConnectableAPI::ConnectToSource() are static methods,
and UsdShadeNodeGraph will auto-convert to a UsdShadeConnectableAPI
when passed to functions that want to act generically on a connectable
UsdShadeConnectableAPI object.
"""
result["NodeGraph"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["NodeGraph"].Get.func_doc = """**classmethod** Get(stage, path) -> NodeGraph
Return a UsdShadeNodeGraph holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdShadeNodeGraph(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["NodeGraph"].Define.func_doc = """**classmethod** Define(stage, path) -> NodeGraph
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["NodeGraph"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Output"].__doc__ = """
This class encapsulates a shader or node-graph output, which is a
connectable attribute representing a typed, externally computed value.
"""
result["Output"].SetRenderType.func_doc = """SetRenderType(renderType) -> bool
Specify an alternative, renderer-specific type to use when
emitting/translating this output, rather than translating based on its
GetTypeName()
For example, we set the renderType to"struct"for outputs that are of
renderman custom struct types.
true on success
Parameters
----------
renderType : str
"""
result["Output"].GetRenderType.func_doc = """GetRenderType() -> str
Return this output's specialized renderType, or an empty token if none
was authored.
SetRenderType()
"""
result["Output"].HasRenderType.func_doc = """HasRenderType() -> bool
Return true if a renderType has been specified for this output.
SetRenderType()
"""
result["Output"].GetSdrMetadata.func_doc = """GetSdrMetadata() -> NdrTokenMap
Returns this Output's composed"sdrMetadata"dictionary as a
NdrTokenMap.
"""
result["Output"].GetSdrMetadataByKey.func_doc = """GetSdrMetadataByKey(key) -> str
Returns the value corresponding to ``key`` in the composed
**sdrMetadata** dictionary.
Parameters
----------
key : str
"""
result["Output"].SetSdrMetadata.func_doc = """SetSdrMetadata(sdrMetadata) -> None
Authors the given ``sdrMetadata`` value on this Output at the current
EditTarget.
Parameters
----------
sdrMetadata : NdrTokenMap
"""
result["Output"].SetSdrMetadataByKey.func_doc = """SetSdrMetadataByKey(key, value) -> None
Sets the value corresponding to ``key`` to the given string ``value``
, in the Output's"sdrMetadata"dictionary at the current EditTarget.
Parameters
----------
key : str
value : str
"""
result["Output"].HasSdrMetadata.func_doc = """HasSdrMetadata() -> bool
Returns true if the Output has a non-empty
composed"sdrMetadata"dictionary value.
"""
result["Output"].HasSdrMetadataByKey.func_doc = """HasSdrMetadataByKey(key) -> bool
Returns true if there is a value corresponding to the given ``key`` in
the composed"sdrMetadata"dictionary.
Parameters
----------
key : str
"""
result["Output"].ClearSdrMetadata.func_doc = """ClearSdrMetadata() -> None
Clears any"sdrMetadata"value authored on the Output in the current
EditTarget.
"""
result["Output"].ClearSdrMetadataByKey.func_doc = """ClearSdrMetadataByKey(key) -> None
Clears the entry corresponding to the given ``key`` in
the"sdrMetadata"dictionary authored in the current EditTarget.
Parameters
----------
key : str
"""
result["Output"].__init__.func_doc = """__init__(attr)
Speculative constructor that will produce a valid UsdShadeOutput when
``attr`` already represents a shade Output, and produces an *invalid*
UsdShadeOutput otherwise (i.e.
the explicit bool conversion operator will return false).
Parameters
----------
attr : Attribute
----------------------------------------------------------------------
__init__()
Default constructor returns an invalid Output.
Exists for container classes
----------------------------------------------------------------------
__init__(prim, name, typeName)
Parameters
----------
prim : Prim
name : str
typeName : ValueTypeName
"""
result["Output"].GetAttr.func_doc = """GetAttr() -> Attribute
Explicit UsdAttribute extractor.
"""
result["Output"].IsOutput.func_doc = """**classmethod** IsOutput(attr) -> bool
Test whether a given UsdAttribute represents a valid Output, which
implies that creating a UsdShadeOutput from the attribute will
succeed.
Success implies that ``attr.IsDefined()`` is true.
Parameters
----------
attr : Attribute
"""
result["Output"].CanConnect.func_doc = """CanConnect(source) -> bool
Determines whether this Output can be connected to the given source
attribute, which can be an input or an output.
An output is considered to be connectable only if it belongs to a
node-graph. Shader outputs are not connectable.
UsdShadeConnectableAPI::CanConnect
Parameters
----------
source : Attribute
----------------------------------------------------------------------
CanConnect(sourceInput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
sourceInput : Input
----------------------------------------------------------------------
CanConnect(sourceOutput) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
sourceOutput : Output
"""
result["Output"].ConnectToSource.func_doc = """ConnectToSource(source, mod) -> bool
Authors a connection for this Output.
``source`` is a struct that describes the upstream source attribute
with all the information necessary to make a connection. See the
documentation for UsdShadeConnectionSourceInfo. ``mod`` describes the
operation that should be applied to the list of connections. By
default the new connection will replace any existing connections, but
it can add to the list of connections to represent multiple input
connections.
``true`` if a connection was created successfully. ``false`` if
``shadingAttr`` or ``source`` is invalid.
This method does not verify the connectability of the shading
attribute to the source. Clients must invoke CanConnect() themselves
to ensure compatibility.
The source shading attribute is created if it doesn't exist already.
UsdShadeConnectableAPI::ConnectToSource
Parameters
----------
source : ConnectionSourceInfo
mod : ConnectionModification
----------------------------------------------------------------------
ConnectToSource(source, sourceName, sourceType, typeName) -> bool
Deprecated
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
typeName : ValueTypeName
----------------------------------------------------------------------
ConnectToSource(sourcePath) -> bool
Authors a connection for this Output to the source at the given path.
UsdShadeConnectableAPI::ConnectToSource
Parameters
----------
sourcePath : Path
----------------------------------------------------------------------
ConnectToSource(sourceInput) -> bool
Connects this Output to the given input, ``sourceInput`` .
UsdShadeConnectableAPI::ConnectToSource
Parameters
----------
sourceInput : Input
----------------------------------------------------------------------
ConnectToSource(sourceOutput) -> bool
Connects this Output to the given output, ``sourceOutput`` .
UsdShadeConnectableAPI::ConnectToSource
Parameters
----------
sourceOutput : Output
"""
result["Output"].SetConnectedSources.func_doc = """SetConnectedSources(sourceInfos) -> bool
Connects this Output to the given sources, ``sourceInfos`` .
UsdShadeConnectableAPI::SetConnectedSources
Parameters
----------
sourceInfos : list[ConnectionSourceInfo]
"""
result["Output"].GetConnectedSources.func_doc = """GetConnectedSources(invalidSourcePaths) -> list[SourceInfo]
Finds the valid sources of connections for the Output.
``invalidSourcePaths`` is an optional output parameter to collect the
invalid source paths that have not been reported in the returned
vector.
Returns a vector of ``UsdShadeConnectionSourceInfo`` structs with
information about each upsteam attribute. If the vector is empty,
there have been no valid connections.
A valid connection requires the existence of the source attribute and
also requires that the source prim is UsdShadeConnectableAPI
compatible.
The python wrapping returns a tuple with the valid connections first,
followed by the invalid source paths.
UsdShadeConnectableAPI::GetConnectedSources
Parameters
----------
invalidSourcePaths : list[SdfPath]
"""
result["Output"].GetConnectedSource.func_doc = """GetConnectedSource(source, sourceName, sourceType) -> bool
Deprecated
Please use GetConnectedSources instead
Parameters
----------
source : ConnectableAPI
sourceName : str
sourceType : AttributeType
"""
result["Output"].GetRawConnectedSourcePaths.func_doc = """GetRawConnectedSourcePaths(sourcePaths) -> bool
Deprecated
Returns the"raw"(authored) connected source paths for this Output.
UsdShadeConnectableAPI::GetRawConnectedSourcePaths
Parameters
----------
sourcePaths : list[SdfPath]
"""
result["Output"].HasConnectedSource.func_doc = """HasConnectedSource() -> bool
Returns true if and only if this Output is currently connected to a
valid (defined) source.
UsdShadeConnectableAPI::HasConnectedSource
"""
result["Output"].IsSourceConnectionFromBaseMaterial.func_doc = """IsSourceConnectionFromBaseMaterial() -> bool
Returns true if the connection to this Output's source, as returned by
GetConnectedSource() , is authored across a specializes arc, which is
used to denote a base material.
UsdShadeConnectableAPI::IsSourceConnectionFromBaseMaterial
"""
result["Output"].DisconnectSource.func_doc = """DisconnectSource(sourceAttr) -> bool
Disconnect source for this Output.
If ``sourceAttr`` is valid, only a connection to the specified
attribute is disconnected, otherwise all connections are removed.
UsdShadeConnectableAPI::DisconnectSource
Parameters
----------
sourceAttr : Attribute
"""
result["Output"].ClearSources.func_doc = """ClearSources() -> bool
Clears sources for this Output in the current UsdEditTarget.
Most of the time, what you probably want is DisconnectSource() rather
than this function.
UsdShadeConnectableAPI::ClearSources
"""
result["Output"].ClearSource.func_doc = """ClearSource() -> bool
Deprecated
"""
result["Output"].GetValueProducingAttributes.func_doc = """GetValueProducingAttributes(shaderOutputsOnly) -> list[UsdShadeAttribute]
Find what is connected to this Output recursively.
UsdShadeUtils::GetValueProducingAttributes
Parameters
----------
shaderOutputsOnly : bool
"""
result["Output"].GetFullName.func_doc = """GetFullName() -> str
Get the name of the attribute associated with the output.
"""
result["Output"].GetBaseName.func_doc = """GetBaseName() -> str
Returns the name of the output.
We call this the base name since it strips off the"outputs:"namespace
prefix from the attribute name, and returns it.
"""
result["Output"].GetPrim.func_doc = """GetPrim() -> Prim
Get the prim that the output belongs to.
"""
result["Output"].GetTypeName.func_doc = """GetTypeName() -> ValueTypeName
Get the"scene description"value type name of the attribute associated
with the output.
"""
result["Output"].Set.func_doc = """Set(value, time) -> bool
Set a value for the output.
It's unusual to be setting a value on an output since it represents an
externally computed value. The Set API is provided here just for the
sake of completeness and uniformity with other property schema.
Parameters
----------
value : VtValue
time : TimeCode
----------------------------------------------------------------------
Set(value, time) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Set the attribute value of the Output at ``time`` .
Parameters
----------
value : T
time : TimeCode
"""
result["Shader"].__doc__ = """
Base class for all USD shaders. Shaders are the building blocks of
shading networks. While UsdShadeShader objects are not target
specific, each renderer or application target may derive its own
renderer-specific shader object types from this base, if needed.
Objects of this class generally represent a single shading object,
whether it exists in the target renderer or not. For example, a
texture, a fractal, or a mix node.
The UsdShadeNodeDefAPI provides attributes to uniquely identify the
type of this node. The id resolution into a renderable shader target
type of this node. The id resolution into a renderable shader target
is deferred to the consuming application.
The purpose of representing them in Usd is two-fold:
- To represent, via"connections"the topology of the shading network
that must be reconstructed in the renderer. Facilities for authoring
and manipulating connections are encapsulated in the API schema
UsdShadeConnectableAPI.
- To present a (partial or full) interface of typed input
parameters whose values can be set and overridden in Usd, to be
provided later at render-time as parameter values to the actual render
shader objects. Shader input parameters are encapsulated in the
property schema UsdShadeInput.
"""
result["Shader"].__init__.func_doc = """__init__(connectable)
Constructor that takes a ConnectableAPI object.
Allow implicit (auto) conversion of UsdShadeConnectableAPI to
UsdShadeShader, so that a ConnectableAPI can be passed into any
function that accepts a Shader.
that the conversion may produce an invalid Shader object, because not
all UsdShadeConnectableAPI s are Shaders
Parameters
----------
connectable : ConnectableAPI
----------------------------------------------------------------------
__init__(prim)
Construct a UsdShadeShader on UsdPrim ``prim`` .
Equivalent to UsdShadeShader::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdShadeShader on the prim held by ``schemaObj`` .
Should be preferred over UsdShadeShader (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Shader"].ConnectableAPI.func_doc = """ConnectableAPI() -> ConnectableAPI
Contructs and returns a UsdShadeConnectableAPI object with this
shader.
Note that most tasks can be accomplished without explicitly
constructing a UsdShadeConnectable API, since connection-related API
such as UsdShadeConnectableAPI::ConnectToSource() are static methods,
and UsdShadeShader will auto-convert to a UsdShadeConnectableAPI when
passed to functions that want to act generically on a connectable
UsdShadeConnectableAPI object.
"""
result["Shader"].CreateOutput.func_doc = """CreateOutput(name, typeName) -> Output
Create an output which can either have a value or can be connected.
The attribute representing the output is created in
the"outputs:"namespace. Outputs on a shader cannot be connected, as
their value is assumed to be computed externally.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["Shader"].GetOutput.func_doc = """GetOutput(name) -> Output
Return the requested output if it exists.
Parameters
----------
name : str
"""
result["Shader"].GetOutputs.func_doc = """GetOutputs(onlyAuthored) -> list[Output]
Outputs are represented by attributes in the"outputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["Shader"].CreateInput.func_doc = """CreateInput(name, typeName) -> Input
Create an input which can either have a value or can be connected.
The attribute representing the input is created in
the"inputs:"namespace. Inputs on both shaders and node-graphs are
connectable.
Parameters
----------
name : str
typeName : ValueTypeName
"""
result["Shader"].GetInput.func_doc = """GetInput(name) -> Input
Return the requested input if it exists.
Parameters
----------
name : str
"""
result["Shader"].GetInputs.func_doc = """GetInputs(onlyAuthored) -> list[Input]
Inputs are represented by attributes in the"inputs:"namespace.
If ``onlyAuthored`` is true (the default), then only return authored
attributes; otherwise, this also returns un-authored builtins.
Parameters
----------
onlyAuthored : bool
"""
result["Shader"].GetImplementationSourceAttr.func_doc = """GetImplementationSourceAttr() -> Attribute
Forwards to UsdShadeNodeDefAPI(prim).
"""
result["Shader"].CreateImplementationSourceAttr.func_doc = """CreateImplementationSourceAttr(defaultValue, writeSparsely) -> Attribute
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Shader"].GetIdAttr.func_doc = """GetIdAttr() -> Attribute
Forwards to UsdShadeNodeDefAPI(prim).
"""
result["Shader"].CreateIdAttr.func_doc = """CreateIdAttr(defaultValue, writeSparsely) -> Attribute
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Shader"].GetImplementationSource.func_doc = """GetImplementationSource() -> str
Forwards to UsdShadeNodeDefAPI(prim).
"""
result["Shader"].SetShaderId.func_doc = """SetShaderId(id) -> bool
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
id : str
"""
result["Shader"].GetShaderId.func_doc = """GetShaderId(id) -> bool
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
id : str
"""
result["Shader"].SetSourceAsset.func_doc = """SetSourceAsset(sourceAsset, sourceType) -> bool
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
sourceAsset : AssetPath
sourceType : str
"""
result["Shader"].GetSourceAsset.func_doc = """GetSourceAsset(sourceAsset, sourceType) -> bool
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
sourceAsset : AssetPath
sourceType : str
"""
result["Shader"].SetSourceAssetSubIdentifier.func_doc = """SetSourceAssetSubIdentifier(subIdentifier, sourceType) -> bool
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
subIdentifier : str
sourceType : str
"""
result["Shader"].GetSourceAssetSubIdentifier.func_doc = """GetSourceAssetSubIdentifier(subIdentifier, sourceType) -> bool
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
subIdentifier : str
sourceType : str
"""
result["Shader"].SetSourceCode.func_doc = """SetSourceCode(sourceCode, sourceType) -> bool
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
sourceCode : str
sourceType : str
"""
result["Shader"].GetSourceCode.func_doc = """GetSourceCode(sourceCode, sourceType) -> bool
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
sourceCode : str
sourceType : str
"""
result["Shader"].GetShaderNodeForSourceType.func_doc = """GetShaderNodeForSourceType(sourceType) -> ShaderNode
Forwards to UsdShadeNodeDefAPI(prim).
Parameters
----------
sourceType : str
"""
result["Shader"].GetSdrMetadata.func_doc = """GetSdrMetadata() -> NdrTokenMap
Returns this shader's composed"sdrMetadata"dictionary as a
NdrTokenMap.
"""
result["Shader"].GetSdrMetadataByKey.func_doc = """GetSdrMetadataByKey(key) -> str
Returns the value corresponding to ``key`` in the composed
**sdrMetadata** dictionary.
Parameters
----------
key : str
"""
result["Shader"].SetSdrMetadata.func_doc = """SetSdrMetadata(sdrMetadata) -> None
Authors the given ``sdrMetadata`` on this shader at the current
EditTarget.
Parameters
----------
sdrMetadata : NdrTokenMap
"""
result["Shader"].SetSdrMetadataByKey.func_doc = """SetSdrMetadataByKey(key, value) -> None
Sets the value corresponding to ``key`` to the given string ``value``
, in the shader's"sdrMetadata"dictionary at the current EditTarget.
Parameters
----------
key : str
value : str
"""
result["Shader"].HasSdrMetadata.func_doc = """HasSdrMetadata() -> bool
Returns true if the shader has a non-empty
composed"sdrMetadata"dictionary value.
"""
result["Shader"].HasSdrMetadataByKey.func_doc = """HasSdrMetadataByKey(key) -> bool
Returns true if there is a value corresponding to the given ``key`` in
the composed"sdrMetadata"dictionary.
Parameters
----------
key : str
"""
result["Shader"].ClearSdrMetadata.func_doc = """ClearSdrMetadata() -> None
Clears any"sdrMetadata"value authored on the shader in the current
EditTarget.
"""
result["Shader"].ClearSdrMetadataByKey.func_doc = """ClearSdrMetadataByKey(key) -> None
Clears the entry corresponding to the given ``key`` in
the"sdrMetadata"dictionary authored in the current EditTarget.
Parameters
----------
key : str
"""
result["Shader"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Shader"].Get.func_doc = """**classmethod** Get(stage, path) -> Shader
Return a UsdShadeShader holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdShadeShader(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Shader"].Define.func_doc = """**classmethod** Define(stage, path) -> Shader
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Shader"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["ShaderDefParserPlugin"].__doc__ = """
Parses shader definitions represented using USD scene description
using the schemas provided by UsdShade.
"""
result["ShaderDefParserPlugin"].__init__.func_doc = """__init__()
"""
result["ShaderDefParserPlugin"].Parse.func_doc = """Parse(discoveryResult) -> NdrNodeUnique
Takes the specified ``NdrNodeDiscoveryResult`` instance, which was a
result of the discovery process, and generates a new ``NdrNode`` .
The node's name, source type, and family must match.
Parameters
----------
discoveryResult : NodeDiscoveryResult
"""
result["ShaderDefParserPlugin"].GetDiscoveryTypes.func_doc = """GetDiscoveryTypes() -> NdrTokenVec
Returns the types of nodes that this plugin can parse.
"Type"here is the discovery type (in the case of files, this will
probably be the file extension, but in other systems will be data that
can be determined during discovery). This type should only be used to
match up a ``NdrNodeDiscoveryResult`` to its parser plugin; this value
is not exposed in the node's API.
"""
result["ShaderDefParserPlugin"].GetSourceType.func_doc = """GetSourceType() -> str
Returns the source type that this parser operates on.
A source type is the most general type for a node. The parser plugin
is responsible for parsing all discovery results that have the types
declared under ``GetDiscoveryTypes()`` , and those types are
collectively identified as one"source type".
"""
result["ShaderDefUtils"].__doc__ = """
This class contains a set of utility functions used for populating the
shader registry with shaders definitions specified using UsdShade
schemas.
"""
result["ShaderDefUtils"].GetNodeDiscoveryResults.func_doc = """**classmethod** GetNodeDiscoveryResults(shaderDef, sourceUri) -> NdrNodeDiscoveryResultVec
Returns the list of NdrNodeDiscoveryResult objects that must be added
to the shader registry for the given shader ``shaderDef`` , assuming
it is found in a shader definition file found by an Ndr discovery
plugin.
To enable the shaderDef parser to find and parse this shader,
``sourceUri`` should have the resolved path to the usd file containing
this shader prim.
Parameters
----------
shaderDef : Shader
sourceUri : str
"""
result["ShaderDefUtils"].GetShaderProperties.func_doc = """**classmethod** GetShaderProperties(shaderDef) -> NdrPropertyUniquePtrVec
Gets all input and output properties of the given ``shaderDef`` and
translates them into NdrProperties that can be used as the properties
for an SdrShaderNode.
Parameters
----------
shaderDef : ConnectableAPI
"""
result["ShaderDefUtils"].GetPrimvarNamesMetadataString.func_doc = """**classmethod** GetPrimvarNamesMetadataString(metadata, shaderDef) -> str
Collects all the names of valid primvar inputs of the given
``metadata`` and the given ``shaderDef`` and returns the string used
to represent them in SdrShaderNode metadata.
Parameters
----------
metadata : NdrTokenMap
shaderDef : ConnectableAPI
"""
result["Utils"].__doc__ = """
This class contains a set of utility functions used when authoring and
querying shading networks.
"""
result["Utils"].GetPrefixForAttributeType.func_doc = """**classmethod** GetPrefixForAttributeType(sourceType) -> str
Returns the namespace prefix of the USD attribute associated with the
given shading attribute type.
Parameters
----------
sourceType : AttributeType
"""
result["Utils"].GetConnectedSourcePath.func_doc = """**classmethod** GetConnectedSourcePath(srcInfo) -> Path
For a valid UsdShadeConnectionSourceInfo, return the complete path to
the source property; otherwise the empty path.
Parameters
----------
srcInfo : ConnectionSourceInfo
"""
result["Utils"].GetBaseNameAndType.func_doc = """**classmethod** GetBaseNameAndType(fullName) -> tuple[str, AttributeType]
Given the full name of a shading attribute, returns it's base name and
shading attribute type.
Parameters
----------
fullName : str
"""
result["Utils"].GetType.func_doc = """**classmethod** GetType(fullName) -> AttributeType
Given the full name of a shading attribute, returns its shading
attribute type.
Parameters
----------
fullName : str
"""
result["Utils"].GetFullName.func_doc = """**classmethod** GetFullName(baseName, type) -> str
Returns the full shading attribute name given the basename and the
shading attribute type.
``baseName`` is the name of the input or output on the shading node.
``type`` is the UsdShadeAttributeType of the shading attribute.
Parameters
----------
baseName : str
type : AttributeType
"""
result["Utils"].GetValueProducingAttributes.func_doc = """**classmethod** GetValueProducingAttributes(input, shaderOutputsOnly) -> list[UsdShadeAttribute]
Find what is connected to an Input or Output recursively.
GetValueProducingAttributes implements the UsdShade connectivity rules
described in Connection Resolution Utilities.
When tracing connections within networks that contain containers like
UsdShadeNodeGraph nodes, the actual output(s) or value(s) at the end
of an input or output might be multiple connections removed. The
methods below resolves this across multiple physical connections.
An UsdShadeInput is getting its value from one of these sources:
- If the input is not connected the UsdAttribute for this input is
returned, but only if it has an authored value. The input attribute
itself carries the value for this input.
- If the input is connected we follow the connection(s) until we
reach a valid output of a UsdShadeShader node or if we reach a valid
UsdShadeInput attribute of a UsdShadeNodeGraph or UsdShadeMaterial
that has an authored value.
An UsdShadeOutput on a container can get its value from the same type
of sources as a UsdShadeInput on either a UsdShadeShader or
UsdShadeNodeGraph. Outputs on non-containers (UsdShadeShaders) cannot
be connected.
This function returns a vector of UsdAttributes. The vector is empty
if no valid attribute was found. The type of each attribute can be
determined with the ``UsdShadeUtils::GetType`` function.
If ``shaderOutputsOnly`` is true, it will only report attributes that
are outputs of non-containers (UsdShadeShaders). This is a bit faster
and what is need when determining the connections for Material
terminals.
This will return the last attribute along the connection chain that
has an authored value, which might not be the last attribute in the
chain itself.
When the network contains multi-connections, this function can return
multiple attributes for a single input or output. The list of
attributes is build by a depth-first search, following the underlying
connection paths in order. The list can contain both UsdShadeOutput
and UsdShadeInput attributes. It is up to the caller to decide how to
process such a mixture.
Parameters
----------
input : Input
shaderOutputsOnly : bool
----------------------------------------------------------------------
GetValueProducingAttributes(output, shaderOutputsOnly) -> list[UsdShadeAttribute]
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
output : Output
shaderOutputsOnly : bool
""" | 144,470 | Python | 22.335649 | 165 | 0.726075 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdUtils/complianceChecker.py | #
# Copyright 2018 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.
#
from __future__ import print_function
from pxr import Ar
from pxr.UsdUtils.constantsGroup import ConstantsGroup
class NodeTypes(ConstantsGroup):
UsdPreviewSurface = "UsdPreviewSurface"
UsdUVTexture = "UsdUVTexture"
UsdTransform2d = "UsdTransform2d"
UsdPrimvarReader = "UsdPrimvarReader"
class ShaderProps(ConstantsGroup):
Bias = "bias"
Scale = "scale"
SourceColorSpace = "sourceColorSpace"
Normal = "normal"
File = "file"
def _IsPackageOrPackagedLayer(layer):
return layer.GetFileFormat().IsPackage() or \
Ar.IsPackageRelativePath(layer.identifier)
class BaseRuleChecker(object):
"""This is Base class for all the rule-checkers."""
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
self._verbose = verbose
self._consumerLevelChecks = consumerLevelChecks
self._assetLevelChecks = assetLevelChecks
self._failedChecks = []
self._errors = []
self._warnings = []
def _AddFailedCheck(self, msg):
self._failedChecks.append(msg)
def _AddError(self, msg):
self._errors.append(msg)
def _AddWarning(self, msg):
self._warnings.append(msg)
def _Msg(self, msg):
if self._verbose:
print(msg)
def GetFailedChecks(self):
return self._failedChecks
def GetErrors(self):
return self._errors
def GetWarnings(self):
return self._warnings
# -------------------------------------------------------------------------
# Virtual methods that any derived rule-checker may want to override.
# Default implementations do nothing.
#
# A rule-checker may choose to override one or more of the virtual methods.
# The callbacks are invoked in the order they are defined here (i.e.
# CheckStage is invoked first, followed by CheckDiagnostics, followed by
# CheckUnresolvedPaths and so on until CheckPrim). Some of the callbacks may
# be invoked multiple times per-rule with different parameters, for example,
# CheckLayer, CheckPrim and CheckZipFile.
def CheckStage(self, usdStage):
""" Check the given usdStage. """
pass
def CheckDiagnostics(self, diagnostics):
""" Check the diagnostic messages that were generated when opening the
USD stage. The diagnostic messages are collected using a
UsdUtilsCoalescingDiagnosticDelegate.
"""
pass
def CheckUnresolvedPaths(self, unresolvedPaths):
""" Check or process any unresolved asset paths that were found when
analysing the dependencies.
"""
pass
def CheckDependencies(self, usdStage, layerDeps, assetDeps):
""" Check usdStage's layer and asset dependencies that were gathered
using UsdUtils.ComputeAllDependencies().
"""
pass
def CheckLayer(self, layer):
""" Check the given SdfLayer. """
pass
def CheckZipFile(self, zipFile, packagePath):
""" Check the zipFile object created by opening the package at path
packagePath.
"""
pass
def CheckPrim(self, prim):
""" Check the given prim, which may only exist is a specific combination
of variant selections on the UsdStage.
"""
pass
def ResetCaches(self):
""" Reset any caches the rule owns. Called whenever stage authoring
occurs, such as when we iterate through VariantSet combinations.
"""
pass
# -------------------------------------------------------------------------
class ByteAlignmentChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "Files within a usdz package must be laid out properly, "\
"i.e. they should be aligned to 64 bytes."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(ByteAlignmentChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckZipFile(self, zipFile, packagePath):
fileNames = zipFile.GetFileNames()
for fileName in fileNames:
fileExt = Ar.GetResolver().GetExtension(fileName)
fileInfo = zipFile.GetFileInfo(fileName)
offset = fileInfo.dataOffset
if offset % 64 != 0:
self._AddFailedCheck("File '%s' in package '%s' has an "
"invalid offset %s." %
(fileName, packagePath, offset))
class CompressionChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "Files within a usdz package should not be compressed or "\
"encrypted."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(CompressionChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckZipFile(self, zipFile, packagePath):
fileNames = zipFile.GetFileNames()
for fileName in fileNames:
fileExt = Ar.GetResolver().GetExtension(fileName)
fileInfo = zipFile.GetFileInfo(fileName)
if fileInfo.compressionMethod != 0:
self._AddFailedCheck("File '%s' in package '%s' has "
"compression. Compression method is '%s', actual size "
"is %s. Uncompressed size is %s." % (
fileName, packagePath, fileInfo.compressionMethod,
fileInfo.size, fileInfo.uncompressedSize))
class MissingReferenceChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "The composed USD stage should not contain any unresolvable"\
" asset dependencies (in every possible variation of the "\
"asset), when using the default asset resolver. "
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(MissingReferenceChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckDiagnostics(self, diagnostics):
for diag in diagnostics:
# "_ReportErrors" is the name of the function that issues
# warnings about unresolved references, sublayers and other
# composition arcs.
if '_ReportErrors' in diag.sourceFunction and \
'usd/stage.cpp' in diag.sourceFileName:
self._AddFailedCheck(diag.commentary)
def CheckUnresolvedPaths(self, unresolvedPaths):
for unresolvedPath in unresolvedPaths:
self._AddFailedCheck("Found unresolvable external dependency "
"'%s'." % unresolvedPath)
class StageMetadataChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return """All stages should declare their 'upAxis' and 'metersPerUnit'.
Stages that can be consumed as referencable assets should furthermore have
a valid 'defaultPrim' declared, and stages meant for consumer-level packaging
should always have upAxis set to 'Y'"""
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(StageMetadataChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckStage(self, usdStage):
from pxr import UsdGeom
if not usdStage.HasAuthoredMetadata(UsdGeom.Tokens.upAxis):
self._AddFailedCheck("Stage does not specify an upAxis.")
elif self._consumerLevelChecks:
upAxis = UsdGeom.GetStageUpAxis(usdStage)
if upAxis != UsdGeom.Tokens.y:
self._AddFailedCheck("Stage specifies upAxis '%s'. upAxis should"
" be '%s'." % (upAxis, UsdGeom.Tokens.y))
if not usdStage.HasAuthoredMetadata(UsdGeom.Tokens.metersPerUnit):
self._AddFailedCheck("Stage does not specify its linear scale "
"in metersPerUnit.")
if self._assetLevelChecks:
defaultPrim = usdStage.GetDefaultPrim()
if not defaultPrim:
self._AddFailedCheck("Stage has missing or invalid defaultPrim.")
class TextureChecker(BaseRuleChecker):
# The most basic formats are those published in the USDZ spec
_basicUSDZImageFormats = ("jpg", "png")
# In non-consumer-content (arkit) mode, OIIO can allow us to
# additionaly read other formats from USDZ packages
_extraUSDZ_OIIOImageFormats = (".exr")
# Include a list of "unsupported" image formats to provide better error
# messages when we find one of these. Our builtin image decoder
# _can_ decode these, but they are not considered portable consumer-level
_unsupportedImageFormats = ["bmp", "tga", "hdr", "exr", "tif", "zfile",
"tx"]
@staticmethod
def GetDescription():
return """Texture files should be readable by intended client
(only .jpg or .png for consumer-level USDZ)."""
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
# Check if the prim has an allowed type.
super(TextureChecker, self).__init__(verbose, consumerLevelChecks,
assetLevelChecks)
# a None value for _allowedFormats indicates all formats are allowed
self._allowedFormats = None
def CheckStage(self, usdStage):
# This is the point at which we can determine whether we have a USDZ
# archive, and so have enough information to set the allowed formats.
rootLayer = usdStage.GetRootLayer()
if rootLayer.GetFileFormat().IsPackage() or self._consumerLevelChecks:
self._allowedFormats = list(TextureChecker._basicUSDZImageFormats)
if not self._consumerLevelChecks:
self._allowedFormats.append(TextureChecker._extraUSDZ_OIIOImageFormats)
else:
self._Msg("Not performing texture format checks for general "
"USD asset")
def _CheckTexture(self, texAssetPath, inputPath):
self._Msg("Checking texture <%s>." % texAssetPath)
texFileExt = Ar.GetResolver().GetExtension(texAssetPath).lower()
if (self._consumerLevelChecks and
texFileExt in TextureChecker._unsupportedImageFormats):
self._AddFailedCheck("Texture <%s> with asset @%s@ has non-portable "
"file format." % (inputPath, texAssetPath))
elif texFileExt not in self._allowedFormats:
self._AddFailedCheck("Texture <%s> with asset @%s@ has unknown "
"file format." % (inputPath, texAssetPath))
def CheckPrim(self, prim):
# Right now, we find texture referenced by looking at the asset-valued
# inputs on Connectable prims.
from pxr import Sdf, Usd, UsdShade
# Nothing to do if we are allowing all formats, or if
# we are an untyped prim
if self._allowedFormats is None or not prim.GetTypeName():
return
# Check if the prim is Connectable.
connectable = UsdShade.ConnectableAPI(prim)
if not connectable:
return
shaderInputs = connectable.GetInputs()
for ip in shaderInputs:
attrPath = ip.GetAttr().GetPath()
if ip.GetTypeName() == Sdf.ValueTypeNames.Asset:
texFilePath = ip.Get(Usd.TimeCode.EarliestTime())
# ip may be unauthored and/or connected
if texFilePath:
self._CheckTexture(texFilePath.path, attrPath)
elif ip.GetTypeName() == Sdf.ValueTypeNames.AssetArray:
texPathArray = ip.Get(Usd.TimeCode.EarliestTime())
if texPathArray:
for texPath in texPathArray:
self._CheckTexture(texPath, attrPath)
class PrimEncapsulationChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return """Check for basic prim encapsulation rules:
- Boundables may not be nested under Gprims
- Connectable prims (e.g. Shader, Material, etc) can only be nested
inside other Container-like Connectable prims. Container-like prims
include Material, NodeGraph, Light, LightFilter, and *exclude Shader*"""
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(PrimEncapsulationChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
self.ResetCaches()
def _HasGprimAncestor(self, prim):
from pxr import Sdf, UsdGeom
path = prim.GetPath()
if path in self._hasGprimInPathMap:
return self._hasGprimInPathMap[path]
elif path == Sdf.Path.absoluteRootPath:
self._hasGprimInPathMap[path] = False
return False
else:
val = (self._HasGprimAncestor(prim.GetParent()) or
prim.IsA(UsdGeom.Gprim))
self._hasGprimInPathMap[path] = val
return val
def _FindConnectableAncestor(self, prim):
from pxr import Sdf, UsdShade
path = prim.GetPath()
if path in self._connectableAncestorMap:
return self._connectableAncestorMap[path]
elif path == Sdf.Path.absoluteRootPath:
self._connectableAncestorMap[path] = None
return None
else:
val = self._FindConnectableAncestor(prim.GetParent())
# The GetTypeName() check is to work around a bug in
# ConnectableAPIBehavior registry.
if prim.GetTypeName() and not val:
conn = UsdShade.ConnectableAPI(prim)
if conn:
val = prim
self._connectableAncestorMap[path] = val
return val
def CheckPrim(self, prim):
from pxr import UsdGeom, UsdShade
parent = prim.GetParent()
# Of course we must allow Boundables under other Boundables, so that
# schemas like UsdGeom.Pointinstancer can nest their prototypes. But
# we disallow a PointInstancer under a Mesh just as we disallow a Mesh
# under a Mesh, for the same reason: we cannot then independently
# adjust visibility for the two objects, nor can we reasonably compute
# the parent Mesh's extent.
if prim.IsA(UsdGeom.Boundable):
if parent:
if self._HasGprimAncestor(parent):
self._AddFailedCheck("Gprim <%s> has an ancestor prim that "
"is also a Gprim, which is not allowed."
% prim.GetPath())
connectable = UsdShade.ConnectableAPI(prim)
# The GetTypeName() check is to work around a bug in
# ConnectableAPIBehavior registry.
if prim.GetTypeName() and connectable:
if parent:
pConnectable = UsdShade.ConnectableAPI(parent)
if not parent.GetTypeName():
pConnectable = None
if pConnectable and not pConnectable.IsContainer():
# XXX This should be a failure as it is a violation of the
# UsdShade OM. But pragmatically, there are many
# authoring tools currently producing this structure, which
# does not _currently_ perturb Hydra, so we need to start
# with a warning
self._AddWarning("Connectable %s <%s> cannot reside "
"under a non-Container Connectable %s"
% (prim.GetTypeName(),
prim.GetPath(),
parent.GetTypeName()))
elif not pConnectable:
# it's only OK to have a non-connectable parent if all
# the rest of your ancestors are also non-connectable. The
# error message we give is targeted at the most common
# infraction, using Scope or other grouping prims inside
# a Container like a Material
connAnstr = self._FindConnectableAncestor(parent)
if connAnstr is not None:
self._AddFailedCheck("Connectable %s <%s> can only have"
" Connectable Container ancestors"
" up to %s ancestor <%s>, but its"
" parent %s is a %s." %
(prim.GetTypeName(),
prim.GetPath(),
connAnstr.GetTypeName(),
connAnstr.GetPath(),
parent.GetName(),
parent.GetTypeName()))
def ResetCaches(self):
self._connectableAncestorMap = dict()
self._hasGprimInPathMap = dict()
class NormalMapTextureChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return """UsdUVTexture nodes that feed the _inputs:normals_ of a
UsdPreviewSurface must ensure that the data is encoded and scaled properly.
Specifically:
- Since normals are expected to be in the range [(-1,-1,-1), (1,1,1)],
the Texture node must transform 8-bit textures from their [0..1] range by
setting its _inputs:scale_ to [2, 2, 2, 1] and
_inputs:bias_ to [-1, -1, -1, 0]
- Normal map data is commonly expected to be linearly encoded. However, many
image-writing tools automatically set the profile of three-channel, 8-bit
images to SRGB. To prevent an unwanted transformation, the UsdUVTexture's
_inputs:sourceColorSpace_ must be set to "raw". This program cannot
currently read the texture metadata itself, so for now we emit warnings
about this potential infraction for all 8 bit image formats.
"""
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(NormalMapTextureChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def _GetShaderId(self, shader):
# We might someday try harder to find an identifier...
return shader.GetShaderId()
def _TextureIs8Bit(self, asset):
# Eventually we hope to leverage HioImage through a plugin system,
# when Imaging is present, to answer this and other image queries
# more definitively
from pxr import Ar
ext = Ar.GetResolver().GetExtension(asset.resolvedPath)
# not an exhaustive list, but ones we typically can read
return ext in ["bmp", "tga", "jpg", "png", "tif"]
def _GetInputValue(self, shader, inputName):
from pxr import Usd
input = shader.GetInput(inputName)
if not input:
return None
return input.Get(Usd.TimeCode.EarliestTime())
def CheckPrim(self, prim):
from pxr import UsdShade, Gf
from pxr.UsdShade import Utils as ShadeUtils
if not prim.IsA(UsdShade.Shader):
return
shader = UsdShade.Shader(prim)
if not shader:
self._AddError("Invalid shader prim <%s>." % prim.GetPath())
return
shaderId = self._GetShaderId(shader)
# We may have failed to fetch an identifier for asset/source-based
# nodes. We are only interested in UsdPreviewSurface nodes identified via
# info:id, so it's not an error
if not shaderId or shaderId != NodeTypes.UsdPreviewSurface:
return
normalInput = shader.GetInput(ShaderProps.Normal)
if not normalInput:
return
valueProducingAttrs = ShadeUtils.GetValueProducingAttributes(normalInput)
if not valueProducingAttrs or valueProducingAttrs[0].GetPrim() == prim:
return
sourcePrim = valueProducingAttrs[0].GetPrim()
sourceShader = UsdShade.Shader(sourcePrim)
if not sourceShader:
# In theory, could be connected to an interface attribute of a
# parent connectable... not useful, but not an error
if UsdShade.ConnectableAPI(sourcePrim):
return
self._AddFailedCheck("%s.%s on prim <%s> is connected to a"
" non-Shader prim." % \
(NodeTypes.UsdPreviewSurface,
ShaderProps.Normal))
return
sourceId = self._GetShaderId(sourceShader)
# We may have failed to fetch an identifier for asset/source-based
# nodes. OR, we could potentially be driven by a UsdPrimvarReader,
# in which case we'd have nothing to validate
if not sourceId or sourceId != NodeTypes.UsdUVTexture:
return
texAsset = self._GetInputValue(sourceShader, ShaderProps.File)
if not texAsset or not texAsset.resolvedPath:
self._AddFailedCheck("%s prim <%s> has invalid or unresolvable "
"inputs:file of @%s@" % \
(NodeTypes.UsdUVTexture,
sourcePrim.GetPath(),
texAsset.path if texAsset else ""))
return
if not self._TextureIs8Bit(texAsset):
# really nothing more is required for image depths > 8 bits,
# which we assume FOR NOW, are floating point
return
if not self._GetInputValue(sourceShader, ShaderProps.SourceColorSpace):
self._AddWarning("%s prim <%s> that reads Normal Map @%s@ may need "
"to set inputs:sourceColorSpace to 'raw' as some "
"8-bit image writers always indicate an SRGB "
"encoding." % \
(NodeTypes.UsdUVTexture,
sourcePrim.GetPath(),
texAsset.path))
bias = self._GetInputValue(sourceShader, ShaderProps.Bias)
scale = self._GetInputValue(sourceShader, ShaderProps.Scale)
if not (bias and scale and
isinstance(bias, Gf.Vec4f) and isinstance(scale, Gf.Vec4f)):
# XXX This should be a failure, as it results in broken normal
# maps in Storm and hdPrman, at least. But for the same reason
# as the shader-under-shader check, we cannot fail until at least
# the major authoring tools have been updated.
self._AddWarning("%s prim <%s> reads 8 bit Normal Map @%s@, "
"which requires that inputs:scale be set to "
"[2, 2, 2, 1] and inputs:bias be set to "
"[-1, -1, -1, 0] for proper interpretation." %\
(NodeTypes.UsdUVTexture,
sourcePrim.GetPath(),
texAsset.path))
return
# don't really care about fourth components...
if (bias[0] != -1 or bias[1] != -1 or bias[2] != -1 or
scale[0] != 2 or scale[1] != 2 or scale[2] != 2):
self._AddWarning("%s prim <%s> reads an 8 bit Normal Map, "
"but has non-standard inputs:scale and "
"inputs:bias values of %s and %s" %\
(NodeTypes.UsdUVTexture,
sourcePrim.GetPath(),
str(scale), str(bias)))
class MaterialBindingAPIAppliedChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "A prim providing a material binding, must have "\
"MaterialBindingAPI applied on the prim."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(MaterialBindingAPIAppliedChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckPrim(self, prim):
from pxr import UsdShade
numMaterialBindings = len([rel for rel in prim.GetRelationships() \
if rel.GetName().startswith(UsdShade.Tokens.materialBinding)])
if ( (numMaterialBindings > 0) and
not prim.HasAPI(UsdShade.MaterialBindingAPI)):
self._AddFailedCheck("Found material bindings but no " \
"MaterialBindingAPI applied on the prim <%s>." \
% prim.GetPath())
class ARKitPackageEncapsulationChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "If the root layer is a package, then the composed stage "\
"should not contain references to files outside the package. "\
"In other words, the package should be entirely self-contained."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(ARKitPackageEncapsulationChecker, self).\
__init__(verbose, consumerLevelChecks, assetLevelChecks)
def CheckDependencies(self, usdStage, layerDeps, assetDeps):
rootLayer = usdStage.GetRootLayer()
if not _IsPackageOrPackagedLayer(rootLayer):
return
packagePath = usdStage.GetRootLayer().realPath
if packagePath:
if Ar.IsPackageRelativePath(packagePath):
packagePath = Ar.SplitPackageRelativePathOuter(
packagePath)[0]
for layer in layerDeps:
# In-memory layers like session layers (which we must skip when
# doing this check) won't have a real path.
if layer.realPath:
if not layer.realPath.startswith(packagePath):
self._AddFailedCheck("Found loaded layer '%s' that "
"does not belong to the package '%s'." %
(layer.identifier, packagePath))
for asset in assetDeps:
if not asset.startswith(packagePath):
self._AddFailedCheck("Found asset reference '%s' that "
"does not belong to the package '%s'." %
(asset, packagePath))
class ARKitLayerChecker(BaseRuleChecker):
# Only core USD file formats are allowed.
_allowedLayerFormatIds = ('usd', 'usda', 'usdc', 'usdz')
@staticmethod
def GetDescription():
return "All included layers that participate in composition should"\
" have one of the core supported file formats."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
# Check if the prim has an allowed type.
super(ARKitLayerChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckLayer(self, layer):
self._Msg("Checking layer <%s>." % layer.identifier)
formatId = layer.GetFileFormat().formatId
if not formatId in \
ARKitLayerChecker._allowedLayerFormatIds:
self._AddFailedCheck("Layer '%s' has unsupported formatId "
"'%s'." % (layer.identifier, formatId))
class ARKitPrimTypeChecker(BaseRuleChecker):
# All core prim types other than UsdGeomPointInstancers, Curve types, Nurbs,
# and the types in UsdLux are allowed.
_allowedPrimTypeNames = ('', 'Scope', 'Xform', 'Camera',
'Shader', 'Material',
'Mesh', 'Sphere', 'Cube', 'Cylinder', 'Cone',
'Capsule', 'GeomSubset', 'Points',
'SkelRoot', 'Skeleton', 'SkelAnimation',
'BlendShape', 'SpatialAudio')
@staticmethod
def GetDescription():
return "UsdGeomPointInstancers and custom schemas not provided by "\
"core USD are not allowed."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
# Check if the prim has an allowed type.
super(ARKitPrimTypeChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckPrim(self, prim):
self._Msg("Checking prim <%s>." % prim.GetPath())
if prim.GetTypeName() not in \
ARKitPrimTypeChecker._allowedPrimTypeNames:
self._AddFailedCheck("Prim <%s> has unsupported type '%s'." %
(prim.GetPath(), prim.GetTypeName()))
class ARKitShaderChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "Shader nodes must have \"id\" as the implementationSource, " \
"with id values that begin with \"Usd*\". Also, shader inputs "\
"with connections must each have a single, valid connection " \
"source."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(ARKitShaderChecker, self).__init__(verbose, consumerLevelChecks,
assetLevelChecks)
def CheckPrim(self, prim):
from pxr import UsdShade
if not prim.IsA(UsdShade.Shader):
return
shader = UsdShade.Shader(prim)
if not shader:
# Error has already been issued by a Base-level checker
return
self._Msg("Checking shader <%s>." % prim.GetPath())
implSource = shader.GetImplementationSource()
if implSource != UsdShade.Tokens.id:
self._AddFailedCheck("Shader <%s> has non-id implementation "
"source '%s'." % (prim.GetPath(), implSource))
shaderId = shader.GetShaderId()
if not shaderId or \
not (shaderId in [NodeTypes.UsdPreviewSurface,
NodeTypes.UsdUVTexture,
NodeTypes.UsdTransform2d] or
shaderId.startswith(NodeTypes.UsdPrimvarReader)) :
self._AddFailedCheck("Shader <%s> has unsupported info:id '%s'."
% (prim.GetPath(), shaderId))
# Check shader input connections
shaderInputs = shader.GetInputs()
for shdInput in shaderInputs:
connections = shdInput.GetAttr().GetConnections()
# If an input has one or more connections, ensure that the
# connections are valid.
if len(connections) > 0:
if len(connections) > 1:
self._AddFailedCheck("Shader input <%s> has %s connection "
"sources, but only one is allowed." %
(shdInput.GetAttr.GetPath(), len(connections)))
connectedSource = shdInput.GetConnectedSource()
if connectedSource is None:
self._AddFailedCheck("Connection source <%s> for shader "
"input <%s> is missing." % (connections[0],
shdInput.GetAttr().GetPath()))
else:
# The source must be a valid shader or material prim.
source = connectedSource[0]
if not source.GetPrim().IsA(UsdShade.Shader) and \
not source.GetPrim().IsA(UsdShade.Material):
self._AddFailedCheck("Shader input <%s> has an invalid "
"connection source prim of type '%s'." %
(shdInput.GetAttr().GetPath(),
source.GetPrim().GetTypeName()))
class ARKitMaterialBindingChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "All material binding relationships must have valid targets."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(ARKitMaterialBindingChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckPrim(self, prim):
from pxr import UsdShade
relationships = prim.GetRelationships()
bindingRels = [rel for rel in relationships if
rel.GetName().startswith(UsdShade.Tokens.materialBinding)]
for bindingRel in bindingRels:
targets = bindingRel.GetTargets()
if len(targets) == 1:
directBinding = UsdShade.MaterialBindingAPI.DirectBinding(
bindingRel)
if not directBinding.GetMaterial():
self._AddFailedCheck("Direct material binding <%s> targets "
"an invalid material <%s>." % (bindingRel.GetPath(),
directBinding.GetMaterialPath()))
elif len(targets) == 2:
collBinding = UsdShade.MaterialBindingAPI.CollectionBinding(
bindingRel)
if not collBinding.GetMaterial():
self._AddFailedCheck("Collection-based material binding "
"<%s> targets an invalid material <%s>." %
(bindingRel.GetPath(), collBinding.GetMaterialPath()))
if not collBinding.GetCollection():
self._AddFailedCheck("Collection-based material binding "
"<%s> targets an invalid collection <%s>." %
(bindingRel.GetPath(), collBinding.GetCollectionPath()))
class ARKitFileExtensionChecker(BaseRuleChecker):
_allowedFileExtensions = \
ARKitLayerChecker._allowedLayerFormatIds + \
TextureChecker._basicUSDZImageFormats
@staticmethod
def GetDescription():
return "Only layer files and textures are allowed in a package."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(ARKitFileExtensionChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckZipFile(self, zipFile, packagePath):
fileNames = zipFile.GetFileNames()
for fileName in fileNames:
fileExt = Ar.GetResolver().GetExtension(fileName)
if fileExt not in ARKitFileExtensionChecker._allowedFileExtensions:
self._AddFailedCheck("File '%s' in package '%s' has an "
"unknown or unsupported extension '%s'." %
(fileName, packagePath, fileExt))
class ARKitRootLayerChecker(BaseRuleChecker):
@staticmethod
def GetDescription():
return "The root layer of the package must be a usdc file and " \
"must not include any external dependencies that participate in "\
"stage composition."
def __init__(self, verbose, consumerLevelChecks, assetLevelChecks):
super(ARKitRootLayerChecker, self).__init__(verbose,
consumerLevelChecks,
assetLevelChecks)
def CheckStage(self, usdStage):
usedLayers = usdStage.GetUsedLayers()
# This list excludes any session layers.
usedLayersOnDisk = [i for i in usedLayers if i.realPath]
if len(usedLayersOnDisk) > 1:
self._AddFailedCheck("The stage uses %s layers. It should "
"contain a single usdc layer to be compatible with ARKit's "
"implementation of usdz." % len(usedLayersOnDisk))
rootLayerRealPath = usdStage.GetRootLayer().realPath
if rootLayerRealPath.endswith(".usdz"):
# Check if the root layer in the package is a usdc.
from pxr import Usd
zipFile = Usd.ZipFile.Open(rootLayerRealPath)
if not zipFile:
self._AddError("Could not open package at path '%s'." %
resolvedPath)
return
fileNames = zipFile.GetFileNames()
if not fileNames[0].endswith(".usdc"):
self._AddFailedCheck("First file (%s) in usdz package '%s' "
"does not have the .usdc extension." % (fileNames[0],
rootLayerRealPath))
elif not rootLayerRealPath.endswith(".usdc"):
self._AddFailedCheck("Root layer of the stage '%s' does not "
"have the '.usdc' extension." % (rootLayerRealPath))
class ComplianceChecker(object):
""" A utility class for checking compliance of a given USD asset or a USDZ
package.
Since usdz files are zip files, someone could use generic zip tools to
create an archive and just change the extension, producing a .usdz file that
does not honor the additional constraints that usdz files require. Even if
someone does use our official archive creation tools, though, we
intentionally allow creation of usdz files that can be very "permissive" in
their contents for internal studio uses, where portability outside the
studio is not a concern. For content meant to be delivered over the web
(eg. ARKit assets), however, we must be much more restrictive.
This class provides two levels of compliance checking:
* "structural" validation that is represented by a set of base rules.
* "ARKit" compatibility validation, which includes many more restrictions.
Calling ComplianceChecker.DumpAllRules() will print an enumeration of the
various rules in the two categories of compliance checking.
"""
@staticmethod
def GetBaseRules():
return [ByteAlignmentChecker, CompressionChecker,
MissingReferenceChecker, StageMetadataChecker, TextureChecker,
PrimEncapsulationChecker, NormalMapTextureChecker,
MaterialBindingAPIAppliedChecker]
@staticmethod
def GetARKitRules(skipARKitRootLayerCheck=False):
arkitRules = [ARKitLayerChecker, ARKitPrimTypeChecker,
ARKitShaderChecker,
ARKitMaterialBindingChecker,
ARKitFileExtensionChecker,
ARKitPackageEncapsulationChecker]
if not skipARKitRootLayerCheck:
arkitRules.append(ARKitRootLayerChecker)
return arkitRules
@staticmethod
def GetRules(arkit=False, skipARKitRootLayerCheck=False):
allRules = ComplianceChecker.GetBaseRules()
if arkit:
arkitRules = ComplianceChecker.GetARKitRules(
skipARKitRootLayerCheck=skipARKitRootLayerCheck)
allRules += arkitRules
return allRules
@staticmethod
def DumpAllRules():
print('Base rules:')
for ruleNum, rule in enumerate(GetBaseRules()):
print('[%s] %s' % (ruleNum + 1, rule.GetDescription()))
print('-' * 30)
print('ARKit rules: ')
for ruleNum, rule in enumerate(GetBaseRules()):
print('[%s] %s' % (ruleNum + 1, rule.GetDescription()))
print('-' * 30)
def __init__(self, arkit=False, skipARKitRootLayerCheck=False,
rootPackageOnly=False, skipVariants=False, verbose=False,
assetLevelChecks=True):
self._rootPackageOnly = rootPackageOnly
self._doVariants = not skipVariants
self._verbose = verbose
self._errors = []
self._warnings = []
# Once a package has been checked, it goes into this set.
self._checkedPackages = set()
# Instantiate an instance of every rule checker and store in a list.
self._rules = [Rule(self._verbose, arkit, assetLevelChecks) for Rule in
ComplianceChecker.GetRules(arkit, skipARKitRootLayerCheck)]
def _Msg(self, msg):
if self._verbose:
print(msg)
def _AddError(self, errMsg):
self._errors.append(errMsg)
def _AddWarning(self, errMsg):
self._warnings.append(errMsg)
def GetErrors(self):
errors = self._errors
for rule in self._rules:
errs = rule.GetErrors()
for err in errs:
errors.append("Error checking rule '%s': %s" %
(type(rule).__name__, err))
return errors
def GetWarnings(self):
warnings = self._warnings
for rule in self._rules:
advisories = rule.GetWarnings()
for ad in advisories:
warnings.append("%s (may violate '%s')" % (ad,
type(rule).__name__))
return warnings
def DumpRules(self):
print('Checking rules: ')
for rule in self._rules:
print('-' * 30)
print('[%s]:\n %s' % (type(rule).__name__, rule.GetDescription()))
print('-' * 30)
def GetFailedChecks(self):
failedChecks = []
for rule in self._rules:
fcs = rule.GetFailedChecks()
for fc in fcs:
failedChecks.append("%s (fails '%s')" % (fc,
type(rule).__name__))
return failedChecks
def CheckCompliance(self, inputFile):
from pxr import Sdf, Usd, UsdUtils
if not Usd.Stage.IsSupportedFile(inputFile):
_AddError("Cannot open file '%s' on a USD stage." % args.inputFile)
return
# Collect all warnings using a diagnostic delegate.
delegate = UsdUtils.CoalescingDiagnosticDelegate()
usdStage = Usd.Stage.Open(inputFile)
stageOpenDiagnostics = delegate.TakeUncoalescedDiagnostics()
for rule in self._rules:
rule.CheckStage(usdStage)
rule.CheckDiagnostics(stageOpenDiagnostics)
with Ar.ResolverContextBinder(usdStage.GetPathResolverContext()):
# This recursively computes all of inputFiles's external
# dependencies.
(allLayers, allAssets, unresolvedPaths) = \
UsdUtils.ComputeAllDependencies(Sdf.AssetPath(inputFile))
for rule in self._rules:
rule.CheckUnresolvedPaths(unresolvedPaths)
rule.CheckDependencies(usdStage, allLayers, allAssets)
if self._rootPackageOnly:
rootLayer = usdStage.GetRootLayer()
if rootLayer.GetFileFormat().IsPackage():
packagePath = Ar.SplitPackageRelativePathInner(
rootLayer.identifier)[0]
self._CheckPackage(packagePath)
else:
self._AddError("Root layer of the USD stage (%s) doesn't belong to "
"a package, but 'rootPackageOnly' is True!" %
Usd.Describe(usdStage))
else:
# Process every package just once by storing them all in a set.
packages = set()
for layer in allLayers:
if _IsPackageOrPackagedLayer(layer):
packagePath = Ar.SplitPackageRelativePathInner(
layer.identifier)[0]
packages.add(packagePath)
self._CheckLayer(layer)
for package in packages:
self._CheckPackage(package)
# Traverse the entire stage and check every prim.
from pxr import Usd
# Author all variant switches in the session layer.
usdStage.SetEditTarget(usdStage.GetSessionLayer())
allPrimsIt = iter(Usd.PrimRange.Stage(usdStage,
Usd.TraverseInstanceProxies()))
self._TraverseRange(allPrimsIt, isStageRoot=True)
def _CheckPackage(self, packagePath):
self._Msg("Checking package <%s>." % packagePath)
# XXX: Should we open the package on a stage to ensure that it is valid
# and entirely self-contained.
from pxr import Usd
pkgExt = Ar.GetResolver().GetExtension(packagePath)
if pkgExt != "usdz":
self._AddError("Package at path %s has an invalid extension."
% packagePath)
return
# Check the parent package first.
if Ar.IsPackageRelativePath(packagePath):
parentPackagePath = Ar.SplitPackageRelativePathInner(packagePath)[0]
self._CheckPackage(parentPackagePath)
# Avoid checking the same parent package multiple times.
if packagePath in self._checkedPackages:
return
self._checkedPackages.add(packagePath)
resolvedPath = Ar.GetResolver().Resolve(packagePath)
if not resolvedPath:
self._AddError("Failed to resolve package path '%s'." % packagePath)
return
zipFile = Usd.ZipFile.Open(resolvedPath)
if not zipFile:
self._AddError("Could not open package at path '%s'." %
resolvedPath)
return
for rule in self._rules:
rule.CheckZipFile(zipFile, packagePath)
def _CheckLayer(self, layer):
for rule in self._rules:
rule.CheckLayer(layer)
def _CheckPrim(self, prim):
for rule in self._rules:
rule.CheckPrim(prim)
def _TraverseRange(self, primRangeIt, isStageRoot):
primsWithVariants = []
rootPrim = primRangeIt.GetCurrentPrim()
for prim in primRangeIt:
# Skip variant set check on the root prim if it is the stage'.
if not self._doVariants or (not isStageRoot and prim == rootPrim):
self._CheckPrim(prim)
continue
vSets = prim.GetVariantSets()
vSetNames = vSets.GetNames()
if len(vSetNames) == 0:
self._CheckPrim(prim)
else:
primsWithVariants.append(prim)
primRangeIt.PruneChildren()
for prim in primsWithVariants:
self._TraverseVariants(prim)
def _TraverseVariants(self, prim):
from pxr import Usd
if prim.IsInstanceProxy():
return True
vSets = prim.GetVariantSets()
vSetNames = vSets.GetNames()
allVariantNames = []
for vSetName in vSetNames:
vSet = vSets.GetVariantSet(vSetName)
vNames = vSet.GetVariantNames()
allVariantNames.append(vNames)
import itertools
allVariations = itertools.product(*allVariantNames)
for variation in allVariations:
self._Msg("Testing variation %s of prim <%s>" %
(variation, prim.GetPath()))
for (idx, sel) in enumerate(variation):
vSets.SetSelection(vSetNames[idx], sel)
for rule in self._rules:
rule.ResetCaches()
primRangeIt = iter(Usd.PrimRange(prim,
Usd.TraverseInstanceProxies()))
self._TraverseRange(primRangeIt, isStageRoot=False)
| 49,090 | Python | 43.027803 | 88 | 0.581605 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdUtils/usdzUtils.py | #
# Copyright 2022 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.
#
# - method to extract usdz package contents to a given location
# this should be trivial and just use zipfile module to extract all contents
from __future__ import print_function
import sys
import os
import glob
import zipfile
import shutil
import tempfile
from contextlib import contextmanager
def _Print(msg):
print(msg)
def _Err(msg):
sys.stderr.write(msg + '\n')
def _AllowedUsdzExtensions():
return [".usdz"]
def _AllowedUsdExtensions():
return [".usd", ".usda", ".usdc"]
# Runs UsdUtils.ComplianceChecker on the given layer
def CheckUsdzCompliance(rootLayer, arkit=False):
"""
Runs UsdUtils.ComplianceChecker on the given layer and reports errors.
Returns True if no errors or failed checks were reported, False otherwise.
"""
from pxr import UsdUtils
checker = UsdUtils.ComplianceChecker(arkit=arkit,
# We're going to flatten the USD stage and convert the root layer to
# crate file format before packaging, if necessary. Hence, skip these
# checks.
skipARKitRootLayerCheck=True)
checker.CheckCompliance(rootLayer)
errors = checker.GetErrors()
failedChecks = checker.GetFailedChecks()
warnings = checker.GetWarnings()
for msg in errors + failedChecks:
_Err(msg)
if len(warnings) > 0:
_Err("*********************************************\n"
"Possible correctness problems to investigate:\n"
"*********************************************\n")
for msg in warnings:
_Err(msg)
return len(errors) == 0 and len(failedChecks) == 0
# Creates a usdz package under usdzFile
def CreateUsdzPackage(usdzFile, filesToAdd, recurse, checkCompliance, verbose):
"""
Creates a usdz package with the files provided in filesToAdd and saves as
the usdzFile.
If filesToAdd contains nested subdirectories, recurse flag can be specified,
which will make sure to recurse through the directory structure and include
the files in the usdz archive.
Specifying checkCompliance, will make sure run UsdUtils.ComplianceChecker on
the rootLayer of the usdz package being created.
"""
if (not usdzFile.endswith('.usdz')):
return False
from pxr import Usd, Tf
with Usd.ZipFileWriter.CreateNew(usdzFile) as usdzWriter:
fileList = []
while filesToAdd:
# Pop front (first file) from the list of files to add.
f = filesToAdd[0]
filesToAdd = filesToAdd[1:]
if os.path.isdir(f):
# If a directory is specified, add all files in the directory.
filesInDir = glob.glob(os.path.join(f, '*'))
# If the recurse flag is not specified, remove sub-directories.
if not recurse:
filesInDir = [f for f in filesInDir if not os.path.isdir(f)]
# glob.glob returns files in arbitrary order. Hence, sort them
# here to get consistent ordering of files in the package.
filesInDir.sort()
filesToAdd += filesInDir
else:
if verbose:
print('.. adding: %s' % f)
if os.path.getsize(f) > 0:
fileList.append(f)
else:
_Err("Skipping empty file '%s'." % f)
if checkCompliance and len(fileList) > 0:
rootLayer = fileList[0]
if not CheckUsdzCompliance(rootLayer):
return False
for f in fileList:
try:
usdzWriter.AddFile(f)
except Tf.ErrorException as e:
_Err('Failed to add file \'%s\' to package. Discarding '
'package.' % f)
# When the "with" block exits, Discard() will be called on
# usdzWriter automatically if an exception occurs.
raise
return True
def ExtractUsdzPackage(usdzFile, extractDir, recurse, verbose, force):
"""
Given a usdz package usdzFile, extracts the contents of the archive under
the extractDir directory. Since usdz packages can contain other usdz
packages, recurse flag can be used to extract the nested structure
appropriately.
"""
if (not usdzFile.endswith('.usdz')):
_Print("\'%s\' does not have .usdz extension" % usdzFile)
return False
if (not os.path.exists(usdzFile)):
_Print("usdz file \'%s\' does not exist." % usdzFile)
if (not extractDir):
_Print("No extract dir specified")
return False
if force and os.path.isdir(os.path.abspath(extractDir)):
shutil.rmtree(os.path.abspath(extractDir))
if os.path.isdir(extractDir):
_Print("Extract Dir: \'%s\' already exists." % extractDir)
return False
def _ExtractZip(zipFile, extractedDir, recurse, verbose):
with zipfile.ZipFile(zipFile) as usdzArchive:
if verbose:
_Print("Extracting usdz file \'%s\' to \'%s\'" \
%(zipFile, extractedDir))
usdzArchive.extractall(extractedDir)
if recurse:
for item in os.listdir(extractedDir):
if item.endswith('.usdz'):
_Print("Extracting item \'%s\'." %item)
itemPath = os.path.join(extractedDir, item)
_ExtractZip(itemPath, os.path.splitext(itemPath)[0],
recurse, verbose)
os.remove(os.path.abspath(itemPath))
# Extract to a temp directory then move to extractDir, this makes sure
# in-complete extraction does not dirty the extractDir and only all
# extracted contents are moved to extractDir
tmpExtractPath = tempfile.mkdtemp()
try:
_ExtractZip(usdzFile, tmpExtractPath, recurse, verbose)
shutil.move(os.path.abspath(tmpExtractPath), os.path.abspath(extractDir))
except:
shutil.rmtree(tmpExtractPath)
return True
class UsdzAssetIterator(object):
"""
Class that provides an iterator for usdz assets. Within context, it
extracts the contents of the usdz package, provides gennerators for all usd
files and all assets and on exit packs the extracted files back recursively
into a usdz package.
"""
def __init__(self, usdzFile, verbose, parentDir=None):
# If a parentDir is provided extractDir is created under the parent dir,
# else a temp directory is created which is cleared on exit. This is
# specially useful when iterating on a nested usdz package.
if parentDir:
self._tmpDir = None
else:
self._tmpDir = tempfile.mkdtemp()
usdzFileDir = os.path.splitext(usdzFile)[0]
self.extractDir = os.path.join(parentDir, usdzFileDir) if parentDir \
else os.path.join(self._tmpDir, usdzFileDir)
self.usdzFile = os.path.abspath(usdzFile)
self.verbose = verbose
if self.verbose:
_Print("Initializing UsdzAssetIterator for (%s) with (%s) temp " \
"extract dir" %(self.usdzFile, self.extractDir))
def _ExtractedFiles(self):
return [os.path.relpath(os.path.join(root, f), self.extractDir) \
for root, dirs, files in os.walk(self.extractDir) \
for f in files]
def __enter__(self):
# unpacks usdz into the extractDir set in the constructor
ExtractUsdzPackage(self.usdzFile, self.extractDir, False, self.verbose,
True)
return self
def __exit__(self, excType, excVal, excTB):
# repacks (modified) files to original usdz package
from pxr import Tf
# If extraction failed, we won't have a extractDir, exit early
if not os.path.exists(self.extractDir):
return
os.chdir(self.extractDir)
filesToAdd = self._ExtractedFiles()
try:
if self.verbose:
_Print("Packing files [%s] in (%s) directory as (%s) usdz " \
"package." %(", ".join(filesToAdd), self.extractDir,
self.usdzFile))
# Package creation can error out
packed = CreateUsdzPackage(self.usdzFile, filesToAdd, True, True,
self.verbose)
except Tf.ErrorException as e:
_Err("Failed to pack files [%s] as usdzFile '%s' because following "
"exception was thrown: (%s)" %(",".join(filesToAdd), \
self.usdzFile, e))
finally:
# Make sure context is not on the directory being removed
os.chdir(os.path.dirname(self.extractDir))
shutil.rmtree(self.extractDir)
def UsdAssets(self):
"""
Generator for UsdAssets respecting nested usdz assets.
"""
if not os.path.exists(self.extractDir):
yield
return
# generator that yields all usd, usda, usdz assets from the package
allowedExtensions = _AllowedUsdzExtensions() + _AllowedUsdExtensions()
extractedFiles = [f for f in self._ExtractedFiles() if \
os.path.splitext(f)[1] in allowedExtensions]
os.chdir(self.extractDir)
for extractedFile in extractedFiles:
if os.path.splitext(extractedFile)[1] in _AllowedUsdzExtensions():
if self.verbose:
_Print("Iterating nested usdz asset: %s" %extractedFile)
# Create another UsdzAssetIterator to handle nested usdz package
with UsdzAssetIterator(extractedFile, self.verbose,
self.extractDir) as nestedUsdz:
# On python3.5+ we can use "yield from" instead of
# iterating on the nested yield's results
for nestedUsdAsset in nestedUsdz.UsdAssets():
yield nestedUsdAsset
else:
if self.verbose:
_Print("Iterating usd asset: %s" %extractedFile)
yield extractedFile
def AllAssets(self):
"""
Generator for all assets packed in the usdz package, respecting nested
usdz assets.
"""
if not os.path.exists(self.extractDir):
yield
return
# generator that yields all assets
extractedFiles = self._ExtractedFiles()
os.chdir(self.extractDir)
for extractedFile in extractedFiles:
if os.path.splitext(extractedFile)[1] in _AllowedUsdzExtensions():
if self.verbose:
_Print("Iterating nested usdz asset: %s" %extractedFile)
with UsdzAssetIterator(extractedFile, self.verbose,
self.extractDir) as nestedUsdz:
# On python3.5+ we can use "yield from" instead of
# iterating on the nested yield's results
for nestedAllAsset in nestedUsdz.AllAssets():
yield nestedAllAsset
else:
if self.verbose:
_Print("Iterating usd asset: %s" %extractedFile)
yield extractedFile
| 12,355 | Python | 40.743243 | 81 | 0.606799 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdUtils/updateSchemaWithSdrNode.py | #!/pxrpythonsubst
#
# Copyright 2021 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.
#
from pxr import Tf, Sdf, Sdr, Usd, UsdShade, Vt
from pxr.UsdUtils.constantsGroup import ConstantsGroup
class SchemaDefiningKeys(ConstantsGroup):
API_SCHEMAS_FOR_ATTR_PRUNING = "apiSchemasForAttrPruning"
API_SCHEMA_AUTO_APPLY_TO = "apiSchemaAutoApplyTo"
API_SCHEMA_CAN_ONLY_APPLY_TO = "apiSchemaCanOnlyApplyTo"
IS_USD_SHADE_CONTAINER = "isUsdShadeContainer"
SCHEMA_PROPERTY_NS_PREFIX_OVERRIDE = "schemaPropertyNSPrefixOverride"
PROVIDES_USD_SHADE_CONNECTABLE_API_BEHAVIOR = \
"providesUsdShadeConnectableAPIBehavior"
REQUIRES_USD_SHADE_ENCAPSULATION = "requiresUsdShadeEncapsulation"
SCHEMA_BASE = "schemaBase"
SCHEMA_KIND = "schemaKind"
SCHEMA_NAME = "schemaName"
TF_TYPENAME_SUFFIX = "tfTypeNameSuffix"
TYPED_SCHEMA_FOR_ATTR_PRUNING = "typedSchemaForAttrPruning"
class SchemaDefiningMiscConstants(ConstantsGroup):
API_SCHEMA_BASE = "APISchemaBase"
API_STRING = "API"
NodeDefAPI = "NodeDefAPI"
SINGLE_APPLY_SCHEMA = "singleApply"
TYPED_SCHEMA = "Typed"
USD_SOURCE_TYPE = "USD"
class PropertyDefiningKeys(ConstantsGroup):
CONNECTABILITY = "connectability"
INTERNAL_DISPLAY_GROUP = "Internal"
NULL_VALUE = "null"
PROPERTY_NS_PREFIX_OVERRIDE = "propertyNSPrefixOverride"
SDF_VARIABILITY_UNIFORM_STRING = "Uniform"
SHADER_ID = "shaderId"
USD_SUPPRESS_PROPERTY = "usdSuppressProperty"
USD_VARIABILITY = "usdVariability"
WIDGET = "widget"
def _IsNSPrefixConnectableAPICompliant(nsPrefix):
return (nsPrefix == UsdShade.Tokens.inputs[:1] or \
nsPrefix == UsdShade.Tokens.outputs[:1])
def _CreateAttrSpecFromNodeAttribute(primSpec, prop, primDefForAttrPruning,
schemaPropertyNSPrefixOverride, isSdrInput=True):
propMetadata = prop.GetMetadata()
# Early out if the property should be suppressed from being translated to
# propertySpec
if ((PropertyDefiningKeys.USD_SUPPRESS_PROPERTY in propMetadata) and
propMetadata[PropertyDefiningKeys.USD_SUPPRESS_PROPERTY] == "True"):
return
propertyNSPrefixOverride = schemaPropertyNSPrefixOverride
if PropertyDefiningKeys.PROPERTY_NS_PREFIX_OVERRIDE in propMetadata:
propertyNSPrefixOverride = \
propMetadata[PropertyDefiningKeys.PROPERTY_NS_PREFIX_OVERRIDE]
propName = prop.GetName()
# Error out if trying to use an explicit propertyNSPrefixOverride on an
# output attr
if (not isSdrInput and propertyNSPrefixOverride is not None and \
propertyNSPrefixOverride != UsdShade.Tokens.outputs[:-1]):
Tf.RaiseRuntimeError("Presence of (%s) output parameter contradicts " \
"the presence of propertyNSPrefixOverride (\"%s\"), as it is " \
"illegal for non-shader nodes to contain output parameters, or " \
"shader nodes' outputs to not have the \"outputs\" namespace " \
"prefix." %(propName, propertyNSPrefixOverride))
attrType = prop.GetTypeAsSdfType()[0]
if not Sdf.Path.IsValidNamespacedIdentifier(propName):
Tf.RaiseRuntimeError("Property name (%s) for schema (%s) is an " \
"invalid namespace identifier." %(propName, primSpec.name))
# if propertyNSPrefixOverride is provided and we are an output then already
# thrown exception
# Note that UsdShade inputs and outputs tokens contain the ":" delimiter, so
# we need to strip this to be used with JoinIdentifier
if propertyNSPrefixOverride is None:
propertyNSPrefixOverride = UsdShade.Tokens.inputs[:-1] if isSdrInput \
else UsdShade.Tokens.outputs[:-1]
# Apply propertyNSPrefixOverride
propName = Sdf.Path.JoinIdentifier([propertyNSPrefixOverride, propName])
# error and early out if duplicate property on primDefForAttrPruning exists
# and has different types
if primDefForAttrPruning:
primDefAttr = primDefForAttrPruning.GetSchemaAttributeSpec(propName)
if primDefAttr:
usdAttrType = primDefAttr.typeName
if (usdAttrType != attrType):
Tf.Warn("Generated schema's property type '%s', "
"differs usd schema's property type '%s', for "
"duplicated property '%s'" %(attrType, usdAttrType,
propName))
return
# Copy over property parameters
options = prop.GetOptions()
if options and attrType == Sdf.ValueTypeNames.String:
attrType = Sdf.ValueTypeNames.Token
attrVariability = Sdf.VariabilityUniform \
if ((PropertyDefiningKeys.USD_VARIABILITY in propMetadata) and
propMetadata[PropertyDefiningKeys.USD_VARIABILITY] ==
PropertyDefiningKeys.SDF_VARIABILITY_UNIFORM_STRING) \
else Sdf.VariabilityVarying
attrSpec = Sdf.AttributeSpec(primSpec, propName, attrType,
attrVariability)
if PropertyDefiningKeys.WIDGET in prop.GetMetadata().keys():
if (prop.GetMetadata()[PropertyDefiningKeys.WIDGET] == \
PropertyDefiningKeys.NULL_VALUE):
attrSpec.hidden = True
if prop.GetHelp():
attrSpec.documentation = prop.GetHelp()
elif prop.GetLabel(): # fallback documentation can be label
attrSpec.documentation = prop.GetLabel()
if prop.GetPage():
attrSpec.displayGroup = prop.GetPage()
if prop.GetLabel():
attrSpec.displayName = prop.GetLabel()
if options and attrType == Sdf.ValueTypeNames.Token:
# If the value for token list is empty then use the name
# If options list has a mix of empty and non-empty value thats an error.
tokenList = []
hasEmptyValue = len(options[0][1]) == 0
for option in options:
if len(option[1]) == 0:
if not hasEmptyValue:
Tf.Warn("Property (%s) for schema (%s) has mix of empty " \
"non-empty values for token options (%s)." \
%(propName, primSpec.name, options))
hasEmptyValue = True
tokenList.append(option[0])
else:
if hasEmptyValue:
Tf.Warn("Property (%s) for schema (%s) has mix of empty " \
"non-empty values for token options (%s)." \
%(propName, primSpec.name, options))
hasEmptyValue = False
tokenList.append(option[1])
attrSpec.allowedTokens = tokenList
defaultValue = prop.GetDefaultValueAsSdfType()
if (attrType == Sdf.ValueTypeNames.String or
attrType == Sdf.ValueTypeNames.Token) and defaultValue is not None:
attrSpec.default = defaultValue.replace('"', r'\"')
else:
attrSpec.default = defaultValue
# The input property should remain connectable (interfaceOnly)
# even if sdrProperty marks the input as not connectable
if propertyNSPrefixOverride == UsdShade.Tokens.inputs[:-1] and \
not prop.IsConnectable():
attrSpec.SetInfo(PropertyDefiningKeys.CONNECTABILITY,
UsdShade.Tokens.interfaceOnly)
def UpdateSchemaWithSdrNode(schemaLayer, sdrNode, renderContext="",
overrideIdentifier=""):
"""
Updates the given schemaLayer with primSpec and propertySpecs from sdrNode
metadata.
A renderContext can be provided which is used in determining the
shaderId namespace, which follows the pattern:
"<renderContext>:<SdrShaderNodeContext>:shaderId". Note that we are using a
node's context (SDR_NODE_CONTEXT_TOKENS) here to construct the shaderId
namespace, so shader parsers should make sure to use appropriate
SDR_NODE_CONTEXT_TOKENS in the node definitions.
overrideIdentifier parameter is the identifier which should be used when
the identifier of the node being processed differs from the one Sdr will
discover at runtime, such as when this function is def a node constructed
from an explicit asset path. This should only be used when clients know the
identifier being passed is the true identifier which sdr Runtime will
provide when querying using GetShaderNodeByIdentifierAndType, etc.
It consumes the following attributes (that manifest as Sdr
metadata) in addition to many of the standard Sdr metadata
specified and parsed (via its parser plugin).
Node Level Metadata:
- "schemaName": Name of the new schema populated from the given sdrNode
(Required)
- "schemaKind": Specifies the UsdSchemaKind for the schema being
populated from the sdrNode. (Note that this does not support
multiple apply schema kinds).
- "schemaBase": Base schema from which the new schema should inherit
from. Note this defaults to "APISchemaBase" for an API schema or
"Typed" for a concrete scheme.
- "apiSchemasForAttrPruning": A list of core API schemas which will be
composed together and any shared shader property from this prim
definition is pruned from the resultant schema.
- "typedSchemaForAttrPruning": A core typed schema which will be
composed together with the apiSchemasForAttrPruning and any shared
shader property from this prim definition is pruned from the
resultant schema. If no typedSchemaForAttrPruning is provided then
only the apiSchemasForAttrPruning are composed to create a prim
definition. This will only be used when creating an APISchema.
- "apiSchemaAutoApplyTo": The schemas to which the sdrNode populated
API schema will autoApply to.
- "apiSchemaCanOnlyApplyTo": If specified, the API schema generated
from the sdrNode can only be validly applied to this set of schemas.
- "providesUsdShadeConnectableAPIBehavior": Used to enable a
connectability behavior for an API schema.
- "isUsdShadeContainer": Only used when
providesUsdShadeConnectableAPIBehavior is set to true. Marks the
connectable prim as a UsdShade container type.
- "requiresUsdShadeEncapsulation": Only used when
providesUsdShadeConnectableAPIBehavior is set to true. Configures the
UsdShade encapsulation rules governing its connectableBehavior.
- "tfTypeNameSuffix": Class name which will get registered with TfType
system. This gets appended to the domain name to register with TfType.
- "schemaPropertyNSPrefixOverride": Node level metadata which can drive
all node's properties namespace prefix. This can be useful for
non connectable nodes which should not get UsdShade inputs and outputs
namespace prefix.
Property Level Metadata:
- "usdVariability": Property level metadata which specifies a specific
sdrNodeProperty should have its USD variability set to Uniform or
Varying
- "usdSuppressProperty": A property level metadata which determines if
the property should be suppressed from translation from args to
property spec.
- "propertyNSPrefixOverride": Provides a way to override a property's
namespace from the default (inputs:/outputs:) or from a node's
schemaPropertyNSPrefixOverride metadata.
Sdr Property Metadata to SdfPropertySpec Translations
- A "null" value for Widget sdrProperty metadata translates to
SdfPropertySpec Hidden metadata.
- SdrProperty's Help metadata (Label metadata if Help metadata not
provided) translates to SdfPropertySpec's Documentation string
metadata.
- SdrProperty's Page metadata translates to SdfPropertySpec's
DisplayGroup metadata.
- SdrProperty's Label metadata translates to SdfPropertySpec's
DisplayName metadata.
- SdrProperty's Options translates to SdfPropertySpec's AllowedTokens.
- SdrProperty's Default value translates to SdfPropertySpec's Default
value.
- Connectable input properties translates to InterfaceOnly
SdfPropertySpec's CONNECTABILITY.
"""
import distutils.util
import os
# Early exit on invalid parameters
if not schemaLayer:
Tf.Warn("No Schema Layer provided")
return
if sdrNode is None:
# This is a workaround to iterate through invalid sdrNodes (nodes not
# having any input or output properties). Currently these nodes return
# false when queried for IsValid().
# Refer: pxr/usd/ndr/node.h#140-149
Tf.Warn("No valid sdrNode provided")
return
sdrNodeMetadata = sdrNode.GetMetadata()
if SchemaDefiningKeys.SCHEMA_NAME not in sdrNodeMetadata:
Tf.Warn("Sdr Node (%s) does not define a schema name metadata." \
%(sdrNode.GetName()))
return
schemaName = sdrNodeMetadata[SchemaDefiningKeys.SCHEMA_NAME]
if not Tf.IsValidIdentifier(schemaName):
Tf.RaiseRuntimeError("schemaName (%s) is an invalid identifier; "
"Provide a valid USD identifer for schemaName, example (%s) "
%(schemaName, Tf.MakeValidIdentifier(schemaName)))
tfTypeNameSuffix = None
if SchemaDefiningKeys.TF_TYPENAME_SUFFIX in sdrNodeMetadata:
tfTypeNameSuffix = sdrNodeMetadata[SchemaDefiningKeys.TF_TYPENAME_SUFFIX]
if not Tf.IsValidIdentifier(tfTypeNameSuffix):
Tf.RaiseRuntimeError("tfTypeNameSuffix (%s) is an invalid " \
"identifier" %(tfTypeNameSuffix))
if SchemaDefiningKeys.SCHEMA_KIND not in sdrNodeMetadata:
schemaKind = SchemaDefiningMiscConstants.TYPED_SCHEMA
else:
schemaKind = sdrNodeMetadata[SchemaDefiningKeys.SCHEMA_KIND]
# Note: We are not working on dynamic multiple apply schemas right now.
isAPI = schemaKind == SchemaDefiningMiscConstants.SINGLE_APPLY_SCHEMA
# Fix schemaName and warn if needed
if isAPI and \
not schemaName.endswith(SchemaDefiningMiscConstants.API_STRING):
Tf.Warn("node metadata implies the generated schema being created is "
"an API schema, fixing schemaName to reflect that")
schemaName = schemaName + SchemaDefiningMiscConstants.API_STRING
if isAPI and tfTypeNameSuffix and \
not tfTypeNameSuffix.endswith(SchemaDefiningMiscConstants.API_STRING):
Tf.Warn("node metadata implies the generated schema being created "
"is an API schema, fixing tfTypeNameSuffix to reflect that")
tfTypeNameSuffix = tfTypeNameSuffix + \
SchemaDefiningMiscConstants.API_STRING
if SchemaDefiningKeys.SCHEMA_BASE not in sdrNodeMetadata:
Tf.Warn("No schemaBase specified in node metadata, defaulting to "
"APISchemaBase for API schemas else Typed")
schemaBase = SchemaDefiningMiscConstants.API_SCHEMA_BASE if isAPI \
else SchemaDefiningMiscConstants.TYPED_SCHEMA
else:
schemaBase = sdrNodeMetadata[SchemaDefiningKeys.SCHEMA_BASE]
apiSchemaAutoApplyTo = None
if SchemaDefiningKeys.API_SCHEMA_AUTO_APPLY_TO in sdrNodeMetadata:
apiSchemaAutoApplyTo = \
sdrNodeMetadata[SchemaDefiningKeys.API_SCHEMA_AUTO_APPLY_TO] \
.split('|')
apiSchemaCanOnlyApplyTo = None
if SchemaDefiningKeys.API_SCHEMA_CAN_ONLY_APPLY_TO in sdrNodeMetadata:
apiSchemaCanOnlyApplyTo = \
sdrNodeMetadata[SchemaDefiningKeys.API_SCHEMA_CAN_ONLY_APPLY_TO] \
.split('|')
providesUsdShadeConnectableAPIBehavior = False
if SchemaDefiningKeys.PROVIDES_USD_SHADE_CONNECTABLE_API_BEHAVIOR in \
sdrNodeMetadata:
providesUsdShadeConnectableAPIBehavior = \
distutils.util.strtobool(sdrNodeMetadata[SchemaDefiningKeys. \
PROVIDES_USD_SHADE_CONNECTABLE_API_BEHAVIOR])
apiSchemasForAttrPruning = None
if SchemaDefiningKeys.API_SCHEMAS_FOR_ATTR_PRUNING in sdrNodeMetadata:
apiSchemasForAttrPruning = \
sdrNodeMetadata[SchemaDefiningKeys.API_SCHEMAS_FOR_ATTR_PRUNING] \
.split('|')
typedSchemaForAttrPruning = ""
if isAPI and \
SchemaDefiningKeys.TYPED_SCHEMA_FOR_ATTR_PRUNING in sdrNodeMetadata:
typedSchemaForAttrPruning = \
sdrNodeMetadata[SchemaDefiningKeys.TYPED_SCHEMA_FOR_ATTR_PRUNING]
schemaPropertyNSPrefixOverride = None
if SchemaDefiningKeys.SCHEMA_PROPERTY_NS_PREFIX_OVERRIDE in sdrNodeMetadata:
schemaPropertyNSPrefixOverride = \
sdrNodeMetadata[ \
SchemaDefiningKeys.SCHEMA_PROPERTY_NS_PREFIX_OVERRIDE]
usdSchemaReg = Usd.SchemaRegistry()
# determine if the node being processed provides UsdShade-Connectability,
# this helps in determining what namespace to use and also to report error
# if a non-connectable node has outputs properties, which is malformed.
# - Does the node derive from a schemaBase which provides connectable
# behavior. Warn if schemaPropertyNSPrefixOverride is also specified, as
# these metadata won't be used.
# - If no schemaBase then we default to UsdShade connectable node's
# inputs:/outputs: namespace prefix, unless schemaPropertyNSPrefixOverride
# is provided.
# - We also report an error if schemaPropertyNSPrefixOverride is provided
# and an output property is found on the node being processed.
schemaBaseProvidesConnectability = UsdShade.ConnectableAPI. \
HasConnectableAPI(usdSchemaReg.GetTypeFromName(schemaBase))
emitSdrOutput = True
for outputName in sdrNode.GetOutputNames():
if PropertyDefiningKeys.USD_SUPPRESS_PROPERTY in \
sdrNode.GetOutput(outputName).GetMetadata():
emitSdrOutput = False
break;
if (emitSdrOutput and \
len(sdrNode.GetOutputNames()) > 0 and \
schemaPropertyNSPrefixOverride is not None and \
not _IsNSPrefixConnectableAPICompliant( \
schemaPropertyNSPrefixOverride)):
Tf.RaiseRuntimeError("Presence of (%s) output parameters contradicts " \
"the presence of schemaPropertyNSPrefixOverride (\"%s\"), as it " \
"is illegal for non-connectable nodes to contain output " \
"parameters, or shader nodes' outputs to not have the \"outputs\"" \
"namespace prefix." %(len(sdrNode.GetOutputNames()), \
schemaPropertyNSPrefixOverride))
if (schemaBaseProvidesConnectability and \
schemaPropertyNSPrefixOverride is not None and \
not _IsNSPrefixConnectableAPICompliant( \
schemaPropertyNSPrefixOverride)):
Tf.Warn("Node %s provides UsdShade-Connectability as it derives from " \
"%s, schemaPropertyNSPrefixOverride \"%s\" will not be used." \
%(schemaName, schemaBase, schemaPropertyNSPrefixOverride))
# set schemaPropertyNSPrefixOverride to "inputs", assuming default
# UsdShade Connectability namespace prefix
schemaPropertyNSPrefixOverride = "inputs"
primSpec = schemaLayer.GetPrimAtPath(schemaName)
if (primSpec):
# if primSpec already exist, remove entirely and recreate using the
# parsed sdr node
if primSpec.nameParent:
del primSpec.nameParent.nameChildren[primSpec.name]
else:
del primSpec.nameRoot.nameChildren[primSpec.name]
primSpec = Sdf.PrimSpec(schemaLayer, schemaName, Sdf.SpecifierClass,
"" if isAPI else schemaName)
primSpec.inheritPathList.explicitItems = ["/" + schemaBase]
primSpecCustomData = {}
if isAPI:
primSpecCustomData["apiSchemaType"] = schemaKind
if tfTypeNameSuffix:
# Defines this classname for TfType system
# can help avoid duplicate prefix with domain and className
# Tf type system will automatically pick schemaName as tfTypeName if
# this is not set!
primSpecCustomData["className"] = tfTypeNameSuffix
if apiSchemaAutoApplyTo:
primSpecCustomData['apiSchemaAutoApplyTo'] = \
Vt.TokenArray(apiSchemaAutoApplyTo)
if apiSchemaCanOnlyApplyTo:
primSpecCustomData['apiSchemaCanOnlyApplyTo'] = \
Vt.TokenArray(apiSchemaCanOnlyApplyTo)
if providesUsdShadeConnectableAPIBehavior:
extraPlugInfo = {
SchemaDefiningKeys.PROVIDES_USD_SHADE_CONNECTABLE_API_BEHAVIOR \
: True
}
for propKey in [SchemaDefiningKeys.IS_USD_SHADE_CONTAINER, \
SchemaDefiningKeys.REQUIRES_USD_SHADE_ENCAPSULATION]:
if propKey in sdrNodeMetadata:
# Since we want to assign the types for these to bool and
# because in python boolean type is a subset of int, we need to
# do following instead of assign the propValue directly.
propValue = distutils.util.strtobool(sdrNodeMetadata[propKey])
extraPlugInfo[propKey] = bool(propValue)
primSpecCustomData['extraPlugInfo'] = extraPlugInfo
primSpec.customData = primSpecCustomData
doc = sdrNode.GetHelp()
if doc != "":
primSpec.documentation = doc
# gather properties from a prim definition generated by composing apiSchemas
# provided by apiSchemasForAttrPruning metadata.
primDefForAttrPruning = None
if apiSchemasForAttrPruning:
primDefForAttrPruning = usdSchemaReg.BuildComposedPrimDefinition(
typedSchemaForAttrPruning, apiSchemasForAttrPruning)
else:
primDefForAttrPruning = \
usdSchemaReg.FindConcretePrimDefinition(typedSchemaForAttrPruning)
# Create attrSpecs from input parameters
for propName in sdrNode.GetInputNames():
_CreateAttrSpecFromNodeAttribute(primSpec, sdrNode.GetInput(propName),
primDefForAttrPruning, schemaPropertyNSPrefixOverride)
# Create attrSpecs from output parameters
# Note that we always want outputs: namespace prefix for output attributes.
for propName in sdrNode.GetOutputNames():
_CreateAttrSpecFromNodeAttribute(primSpec, sdrNode.GetOutput(propName),
primDefForAttrPruning, UsdShade.Tokens.outputs[:-1], False)
# Create token shaderId attrSpec -- only for shader nodes
if (schemaBaseProvidesConnectability or \
schemaPropertyNSPrefixOverride is None or \
_IsNSPrefixConnectableAPICompliant(schemaPropertyNSPrefixOverride)):
shaderIdAttrName = Sdf.Path.JoinIdentifier( \
[renderContext, sdrNode.GetContext(),
PropertyDefiningKeys.SHADER_ID])
shaderIdAttrSpec = Sdf.AttributeSpec(primSpec, shaderIdAttrName,
Sdf.ValueTypeNames.Token, Sdf.VariabilityUniform)
# Since users shouldn't need to be aware of shaderId attribute, we put
# this in "Internal" displayGroup.
shaderIdAttrSpec.displayGroup = \
PropertyDefiningKeys.INTERNAL_DISPLAY_GROUP
# Use the identifier if explicitly provided, (it could be a shader node
# queried using an explicit path), else use sdrNode's registered
# identifier.
nodeIdentifier = overrideIdentifier if overrideIdentifier else \
sdrNode.GetIdentifier()
shaderIdAttrSpec.default = nodeIdentifier
# Extra attrSpec
schemaBasePrimDefinition = \
Usd.SchemaRegistry().FindConcretePrimDefinition(schemaBase)
if schemaBasePrimDefinition and \
SchemaDefiningMiscConstants.NodeDefAPI in \
schemaBasePrimDefinition.GetAppliedAPISchemas():
infoIdAttrSpec = Sdf.AttributeSpec(primSpec, \
UsdShade.Tokens.infoId, Sdf.ValueTypeNames.Token, \
Sdf.VariabilityUniform)
infoIdAttrSpec.default = nodeIdentifier
schemaLayer.Save()
| 25,069 | Python | 46.212806 | 81 | 0.69201 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdUtils/fixBrokenPixarSchemas.py | #
# Copyright 2022 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.
#
class FixBrokenPixarSchemas(object):
"""
A class which takes a usdLayer and clients can apply appropriate fixes
defined as utility methods of this class, example FixupMaterialBindingAPI.
Every Fixup method iterates on each prim in the layer and applies specific
fixes.
"""
def __init__(self, usdLayer):
self._usdLayer = usdLayer
self._skelBindingAPIProps = None
# Keeps track if the Layer was updated by any of the Fixer method
self._layerUpdated = False
def _ApplyAPI(self, listOp, apiSchema):
if listOp.isExplicit:
items = listOp.explicitItems
items.append(apiSchema)
listOp.explicitItems = items
else:
items = listOp.prependedItems
items.append(apiSchema)
listOp.prependedItems = items
return listOp
def IsLayerUpdated(self):
"""
Returns the update status of the usdLayer, an instance of
FixBrokenPixarSchemas is holding. Fixer methods will set
self._layerUpdated to True if any of the Fixer methods applies fixes to
the layer.
"""
return self._layerUpdated
def FixupMaterialBindingAPI(self):
"""
Makes sure MaterialBindingAPI is applied on the prim, which defines a
material:binding property spec. Marks the layer updated if fixes are
applied.
"""
def _PrimSpecProvidesMaterialBinding(path):
if not path.IsPrimPath():
return
primSpec = self._usdLayer.GetPrimAtPath(path)
hasMaterialBindingRel = \
any(prop.name.startswith("material:binding") \
for prop in primSpec.properties)
apiSchemas = primSpec.GetInfo("apiSchemas")
hasMaterialBindingAPI = "MaterialBindingAPI" in \
apiSchemas.GetAddedOrExplicitItems()
if hasMaterialBindingRel and not hasMaterialBindingAPI:
self._layerUpdated = True
newApiSchemas = self._ApplyAPI(apiSchemas, "MaterialBindingAPI")
primSpec.SetInfo("apiSchemas", newApiSchemas)
self._usdLayer.Traverse("/", _PrimSpecProvidesMaterialBinding)
def FixupSkelBindingAPI(self):
"""
Makes sure SkelBindingAPI is applied on the prim, which defines
appropriate UsdSkel properties which are imparted by SkelBindingAPI.
Marks the layer as updated if fixes are applied.
"""
def _PrimSpecProvidesSkelBindingProperties(path):
if not path.IsPrimPath():
return
# get skelBindingAPI props if not already populated
if not self._skelBindingAPIProps:
from pxr import Usd, UsdSkel
usdSchemaRegistry = Usd.SchemaRegistry()
primDef = usdSchemaRegistry.BuildComposedPrimDefinition("",
["SkelBindingAPI"])
self._skelBindingAPIProps = primDef.GetPropertyNames()
primSpec = self._usdLayer.GetPrimAtPath(path)
primSpecProps = [prop.name for prop in primSpec.properties]
apiSchemas = primSpec.GetInfo("apiSchemas")
hasSkelBindingAPI = "SkelBindingAPI" in \
apiSchemas.GetAddedOrExplicitItems()
for skelProperty in self._skelBindingAPIProps:
if (skelProperty in primSpecProps) and not hasSkelBindingAPI:
self._layerUpdated = True
newApiSchemas = self._ApplyAPI(apiSchemas, "SkelBindingAPI")
primSpec.SetInfo("apiSchemas", newApiSchemas)
return
self._usdLayer.Traverse("/", _PrimSpecProvidesSkelBindingProperties)
def FixupUpAxis(self):
"""
Makes sure the layer specifies a upAxis metadata, and if not upAxis
metadata is set to the default provided by UsdGeom. Marks the layer as
updated if fixes are applied.
"""
from pxr import Usd, UsdGeom
usdStage = Usd.Stage.Open(self._usdLayer)
if not usdStage.HasAuthoredMetadata(UsdGeom.Tokens.upAxis):
self._layerUpdated = True
usdStage.SetMetadata(UsdGeom.Tokens.upAxis,
UsdGeom.GetFallbackUpAxis())
| 5,398 | Python | 40.852713 | 80 | 0.650241 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdUtils/__DOC.py | def Execute(result):
result["CoalescingDiagnosticDelegate"].__doc__ = """
A class which collects warnings and statuses from the Tf diagnostic
manager system in a thread safe manner.
This class allows clients to get both the unfiltered results, as well
as a compressed view which deduplicates diagnostic events by their
source line number, function and file from which they occurred.
"""
result["CoalescingDiagnosticDelegate"].__init__.func_doc = """__init__()
"""
result["CoalescingDiagnosticDelegate"].DumpUncoalescedDiagnostics.func_doc = """DumpUncoalescedDiagnostics(ostr) -> None
Print all pending diagnostics without any coalescing to ``ostr`` .
This method clears the pending diagnostics.
Parameters
----------
ostr : ostream
"""
result["CoalescingDiagnosticDelegate"].TakeCoalescedDiagnostics.func_doc = """TakeCoalescedDiagnostics() -> list[UsdUtilsCoalescingDiagnosticDelegate]
Get all pending diagnostics in a coalesced form.
This method clears the pending diagnostics.
"""
result["CoalescingDiagnosticDelegate"].TakeUncoalescedDiagnostics.func_doc = """TakeUncoalescedDiagnostics() -> list[TfDiagnosticBase]
Get all pending diagnostics without any coalescing.
This method clears the pending diagnostics.
"""
result["CoalescingDiagnosticDelegateItem"].__doc__ = """
An item used in coalesced results, containing a shared component: the
file/function/line number, and a set of unshared components: the call
context and commentary.
"""
result["CoalescingDiagnosticDelegateSharedItem"].__doc__ = """
The shared component in a coalesced result This type can be thought of
as the key by which we coalesce our diagnostics.
"""
result["CoalescingDiagnosticDelegateUnsharedItem"].__doc__ = """
The unshared component in a coalesced result.
"""
result["ConditionalAbortDiagnosticDelegate"].__doc__ = """
A class that allows client application to instantiate a diagnostic
delegate that can be used to abort operations for a non fatal USD
error or warning based on immutable include exclude rules defined for
this instance.
These rules are regex strings where case sensitive matching is done on
error/warning text or the location of the code path where the
error/warning occured. Note that these rules will be respected only
during the lifetime of the delegate. Include Rules determine what
errors or warnings will cause a fatal abort. Exclude Rules determine
what errors or warnings matched from the Include Rules should not
cause the fatal abort. Example: to abort on all errors and warnings
coming from"\\*pxr\\*"codepath but not
from"\\*ConditionalAbortDiagnosticDelegate\\*", a client can create
the following delegate:
.. code-block:: text
UsdUtilsConditionalAbortDiagnosticDelegateErrorFilters includeFilters;
UsdUtilsConditionalAbortDiagnosticDelegateErrorFilters excludeFilters;
includeFilters.SetCodePathFilters({"\\*pxr\\*"});
excludeFilters.SetCodePathFilters({"\\*ConditionalAbortDiagnosticDelegate\\*"});
UsdUtilsConditionalAbortDiagnosticDelegate delegate =
UsdUtilsConditionalAbortDiagnosticDelegate(includeFilters,
excludeFilters);
"""
result["ConditionalAbortDiagnosticDelegate"].__init__.func_doc = """__init__(includeFilters, excludeFilters)
Constructor to initialize conditionalAbortDiagnosticDelegate.
Responsible for adding this delegate instance to TfDiagnosticMgr and
also sets the ``includeFilters`` and ``excludeFilters``
The _includeFilters and _excludeFilters are immutable
Parameters
----------
includeFilters : ConditionalAbortDiagnosticDelegateErrorFilters
excludeFilters : ConditionalAbortDiagnosticDelegateErrorFilters
----------------------------------------------------------------------
__init__()
----------------------------------------------------------------------
__init__(delegate)
Parameters
----------
delegate : ConditionalAbortDiagnosticDelegate
"""
result["ConditionalAbortDiagnosticDelegateErrorFilters"].__doc__ = """
A class which represents the inclusion exclusion filters on which
errors will be matched stringFilters: matching and filtering will be
done on explicit string of the error/warning codePathFilters: matching
and filtering will be done on errors/warnings coming from a specific
usd code path.
"""
result["ConditionalAbortDiagnosticDelegateErrorFilters"].__init__.func_doc = """__init__()
----------------------------------------------------------------------
__init__(stringFilters, codePathFilters)
Parameters
----------
stringFilters : list[str]
codePathFilters : list[str]
"""
result["ConditionalAbortDiagnosticDelegateErrorFilters"].GetStringFilters.func_doc = """GetStringFilters() -> list[str]
"""
result["ConditionalAbortDiagnosticDelegateErrorFilters"].GetCodePathFilters.func_doc = """GetCodePathFilters() -> list[str]
"""
result["ConditionalAbortDiagnosticDelegateErrorFilters"].SetStringFilters.func_doc = """SetStringFilters(stringFilters) -> None
Parameters
----------
stringFilters : list[str]
"""
result["ConditionalAbortDiagnosticDelegateErrorFilters"].SetCodePathFilters.func_doc = """SetCodePathFilters(codePathFilters) -> None
Parameters
----------
codePathFilters : list[str]
"""
result["RegisteredVariantSet"].SelectionExportPolicy.__doc__ = """
This specifies how the variantSet should be treated during export.
Note, in the plugInfo.json, the values for these enum's are
lowerCamelCase.
"""
result["SparseAttrValueWriter"].__doc__ = """
A utility class for authoring time-varying attribute values with
simple run-length encoding, by skipping any redundant time-samples.
Time-samples that are close enough to each other, with relative
difference smaller than a fixed epsilon value are considered to be
equivalent. This is to avoid unnecessary authoring of time-samples
caused by numerical fuzz in certain computations.
For vectors, matrices, and other composite types (like quaternions and
arrays), each component is compared with the corresponding component
for closeness. The chosen epsilon value for double precision floating
point numbers is 1e-12. For single-precision, it is 1e-6 and for half-
precision, it is 1e-2.
Example c++ usage:
.. code-block:: text
UsdGeomSphere sphere = UsdGeomSphere::Define(stage, SdfPath("/Sphere"));
UsdAttribute radius = sphere.CreateRadiusAttr();
UsdUtilsSparseAttrValueWriter attrValueWriter(radius,
/\\*defaultValue\\*/ VtValue(1.0));
attrValueWriter.SetTimeSample(VtValue(10.0), UsdTimeCode(1.0));
attrValueWriter.SetTimeSample(VtValue(10.0), UsdTimeCode(2.0));
attrValueWriter.SetTimeSample(VtValue(10.0), UsdTimeCode(3.0));
attrValueWriter.SetTimeSample(VtValue(20.0), UsdTimeCode(4.0));
Equivalent python example:
.. code-block:: text
sphere = UsdGeom.Sphere.Define(stage, Sdf.Path("/Sphere"))
radius = sphere.CreateRadiusAttr()
attrValueWriter = UsdUtils.SparseAttrValueWriter(radius, defaultValue=1.0)
attrValueWriter.SetTimeSample(10.0, 1.0)
attrValueWriter.SetTimeSample(10.0, 2.0)
attrValueWriter.SetTimeSample(10.0, 3.0)
attrValueWriter.SetTimeSample(20.0, 4.0)
In the above examples, the specified default value of radius (1.0)
will not be authored into scene description since it matches the
fallback value. Additionally, the time-sample authored at time=2.0
will be skipped since it is redundant. Also note that for correct
behavior, the calls to SetTimeSample() must be made with sequentially
increasing time values. If not, a coding error is issued and the
authored animation may be incorrect.
"""
result["SparseAttrValueWriter"].__init__.func_doc = """__init__(attr, defaultValue)
The constructor initializes the data required for run-length encoding
of time-samples.
It also sets the default value of ``attr`` to ``defaultValue`` , if
``defaultValue`` is non-empty and different from the existing default
value of ``attr`` .
``defaultValue`` can be unspecified (or left empty) if you don't care
about authoring a default value. In this case, the sparse authoring
logic is initialized with the existing authored default value or the
fallback value, if ``attr`` has one.
Parameters
----------
attr : Attribute
defaultValue : VtValue
----------------------------------------------------------------------
__init__(attr, defaultValue)
The constructor initializes the data required for run-length encoding
of time-samples.
It also sets the default value of ``attr`` to ``defaultValue`` , if
``defaultValue`` is non-empty and different from the existing default
value of ``attr`` .
It ``defaultValue`` is null or points to an empty VtValue, the sparse
authoring logic is initialized with the existing authored default
value or the fallback value, if ``attr`` has one.
For efficiency, this function swaps out the given ``defaultValue`` ,
leaving it empty.
Parameters
----------
attr : Attribute
defaultValue : VtValue
"""
result["SparseAttrValueWriter"].SetTimeSample.func_doc = """SetTimeSample(value, time) -> bool
Sets a new time-sample on the attribute with given ``value`` at the
given ``time`` .
The time-sample is only authored if it's different from the previously
set time-sample, in which case the previous time-sample is also
authored, in order to to end the previous run of contiguous identical
values and start a new run.
This incurs a copy of ``value`` . Also, the value will be held in
memory at least until the next time-sample is written or until the
SparseAttrValueWriter instance is destroyed.
Parameters
----------
value : VtValue
time : TimeCode
----------------------------------------------------------------------
SetTimeSample(value, time) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
For efficiency, this function swaps out the given ``value`` , leaving
it empty.
The value will be held in memory at least until the next time-sample
is written or until the SparseAttrValueWriter instance is destroyed.
Parameters
----------
value : VtValue
time : TimeCode
"""
result["SparseValueWriter"].__doc__ = """
Utility class that manages sparse authoring of a set of UsdAttributes.
It does this by maintaining a map of UsdAttributes to their
corresponding UsdUtilsSparseAttrValueWriter objects.
To use this class, simply instantiate an instance of it and invoke the
SetAttribute() method with various attributes and their associated
time-samples.
If the attribute has a default value, SetAttribute() must be called
with time=Default first (multiple times, if necessary), followed by
calls to author time-samples in sequentially increasing time order.
This class is not threadsafe. In general, authoring to a single USD
layer from multiple threads isn't threadsafe. Hence, there is little
value in making this class threadsafe. Example c++ usage:
.. code-block:: text
UsdGeomCylinder cylinder = UsdGeomCylinder::Define(stage, SdfPath("/Cylinder"));
UsdAttribute radius = cylinder.CreateRadiusAttr();
UsdAttribute height = cylinder.CreateHeightAttr();
UsdUtilsSparseValueWriter valueWriter;
valueWriter.SetAttribute(radius, 2.0, UsdTimeCode::Default());
valueWriter.SetAttribute(height, 2.0, UsdTimeCode::Default());
valueWriter.SetAttribute(radius, 10.0, UsdTimeCode(1.0));
valueWriter.SetAttribute(radius, 20.0, UsdTimeCode(2.0));
valueWriter.SetAttribute(radius, 20.0, UsdTimeCode(3.0));
valueWriter.SetAttribute(radius, 20.0, UsdTimeCode(4.0));
valueWriter.SetAttribute(height, 2.0, UsdTimeCode(1.0));
valueWriter.SetAttribute(height, 2.0, UsdTimeCode(2.0));
valueWriter.SetAttribute(height, 3.0, UsdTimeCode(3.0));
valueWriter.SetAttribute(height, 3.0, UsdTimeCode(4.0));
Equivalent python code:
.. code-block:: text
cylinder = UsdGeom.Cylinder.Define(stage, Sdf.Path("/Cylinder"))
radius = cylinder.CreateRadiusAttr()
height = cylinder.CreateHeightAttr()
valueWriter = UsdUtils.SparseValueWriter()
valueWriter.SetAttribute(radius, 2.0, Usd.TimeCode.Default())
valueWriter.SetAttribute(height, 2.0, Usd.TimeCode.Default())
valueWriter.SetAttribute(radius, 10.0, 1.0)
valueWriter.SetAttribute(radius, 20.0, 2.0)
valueWriter.SetAttribute(radius, 20.0, 3.0)
valueWriter.SetAttribute(radius, 20.0, 4.0)
valueWriter.SetAttribute(height, 2.0, 1.0)
valueWriter.SetAttribute(height, 2.0, 2.0)
valueWriter.SetAttribute(height, 3.0, 3.0)
valueWriter.SetAttribute(height, 3.0, 4.0)
In the above example,
- The default value of the"height"attribute is not authored into
scene description since it matches the fallback value.
- Time-samples at time=3.0 and time=4.0 will be skipped for the
radius attribute.
- For the"height"attribute, the first timesample at time=1.0 will
be skipped since it matches the default value.
- The last time-sample at time=4.0 will also be skipped
for"height"since it matches the previously written value at time=3.0.
"""
result["SparseValueWriter"].SetAttribute.func_doc = """SetAttribute(attr, value, time) -> bool
Sets the value of ``attr`` to ``value`` at time ``time`` .
The value is written sparsely, i.e., the default value is authored
only if it is different from the fallback value or the existing
default value, and any redundant time-samples are skipped when the
attribute value does not change significantly between consecutive
time-samples.
Parameters
----------
attr : Attribute
value : VtValue
time : TimeCode
----------------------------------------------------------------------
SetAttribute(attr, value, time) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
For efficiency, this function swaps out the given ``value`` , leaving
it empty.
The value will be held in memory at least until the next time-sample
is written or until the SparseAttrValueWriter instance is destroyed.
Parameters
----------
attr : Attribute
value : VtValue
time : TimeCode
----------------------------------------------------------------------
SetAttribute(attr, value, time) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Parameters
----------
attr : Attribute
value : T
time : TimeCode
"""
result["SparseValueWriter"].GetSparseAttrValueWriters.func_doc = """GetSparseAttrValueWriters() -> list[SparseAttrValueWriter]
Returns a new vector of UsdUtilsSparseAttrValueWriter populated from
the attrValueWriter map.
"""
result["StageCache"].__doc__ = """
The UsdUtilsStageCache class provides a simple interface for handling
a singleton usd stage cache for use by all USD clients. This way code
from any location can make use of the same cache to maximize stage
reuse.
"""
result["StageCache"].Get.func_doc = """**classmethod** Get() -> StageCache
Returns the singleton stage cache.
"""
result["StageCache"].GetSessionLayerForVariantSelections.func_doc = """**classmethod** GetSessionLayerForVariantSelections(modelName, variantSelections) -> Layer
Given variant selections as a vector of pairs (vector in case order
matters to the client), constructs a session layer with overs on the
given root modelName with the variant selections, or returns a cached
session layer with those opinions.
Parameters
----------
modelName : str
variantSelections : list[tuple[str, str]]
"""
result["TimeCodeRange"].__doc__ = """
Represents a range of UsdTimeCode values as start and end time codes
and a stride value.
A UsdUtilsTimeCodeRange can be iterated to retrieve all time code
values in the range. The range may be empty, it may contain a single
time code, or it may represent multiple time codes from start to end.
The interval defined by the start and end time codes is closed on both
ends.
Note that when constructing a UsdUtilsTimeCodeRange,
UsdTimeCode::EarliestTime() and UsdTimeCode::Default() cannot be used
as the start or end time codes. Also, the end time code cannot be less
than the start time code for positive stride values, and the end time
code cannot be greater than the start time code for negative stride
values. Finally, the stride value cannot be zero. If any of these
conditions are not satisfied, then an invalid empty range will be
returned.
"""
result["TimeCodeRange"].CreateFromFrameSpec.func_doc = """**classmethod** CreateFromFrameSpec(frameSpec) -> TimeCodeRange
Create a time code range from ``frameSpec`` .
A FrameSpec is a compact string representation of a time code range. A
FrameSpec may contain up to three floating point values for the start
time code, end time code, and stride values of a time code range.
A FrameSpec containing just a single floating point value represents a
time code range containing only that time code.
A FrameSpec containing two floating point values separated by the
range separator (':') represents a time code range from the first
value as the start time code to the second values as the end time
code.
A FrameSpec that specifies both a start and end time code value may
also optionally specify a third floating point value as the stride,
separating it from the first two values using the stride separator
('x').
The following are examples of valid FrameSpecs: 123 101:105 105:101
101:109x2 101:110x2 101:104x0.5
An empty string corresponds to an invalid empty time code range.
A coding error will be issued if the given string is malformed.
Parameters
----------
frameSpec : str
"""
result["TimeCodeRange"].__init__.func_doc = """__init__()
Construct an invalid empty range.
The start time code will be initialized to zero, and any iteration of
the range will yield no time codes.
----------------------------------------------------------------------
__init__(timeCode)
Construct a range containing only the given ``timeCode`` .
An iteration of the range will yield only that time code.
Parameters
----------
timeCode : TimeCode
----------------------------------------------------------------------
__init__(startTimeCode, endTimeCode)
Construct a range containing the time codes from ``startTimeCode`` to
``endTimeCode`` .
If ``endTimeCode`` is greater than or equal to ``startTimeCode`` ,
then the stride will be 1.0. Otherwise, the stride will be -1.0.
Parameters
----------
startTimeCode : TimeCode
endTimeCode : TimeCode
----------------------------------------------------------------------
__init__(startTimeCode, endTimeCode, stride)
Construct a range containing the time codes from ``startTimeCode`` to
``endTimeCode`` using the stride value ``stride`` .
UsdTimeCode::EarliestTime() and UsdTimeCode::Default() cannot be used
as ``startTimeCode`` or ``endTimeCode`` . If ``stride`` is a positive
value, then ``endTimeCode`` cannot be less than ``startTimeCode`` . If
``stride`` is a negative value, then ``endTimeCode`` cannot be greater
than ``startTimeCode`` . Finally, the stride value cannot be zero. If
any of these conditions are not satisfied, then a coding error will be
issued and an invalid empty range will be returned.
Parameters
----------
startTimeCode : TimeCode
endTimeCode : TimeCode
stride : float
"""
result["TimeCodeRange"].empty.func_doc = """empty() -> bool
Return true if this range contains no time codes, or false otherwise.
"""
result["TimeCodeRange"].IsValid.func_doc = """IsValid() -> bool
Return true if this range contains one or more time codes, or false
otherwise.
"""
result["TimeCodeRange"].startTimeCode = property(result["TimeCodeRange"].startTimeCode.fget, result["TimeCodeRange"].startTimeCode.fset, result["TimeCodeRange"].startTimeCode.fdel, """type : TimeCode
Return the start time code of this range.
""")
result["TimeCodeRange"].endTimeCode = property(result["TimeCodeRange"].endTimeCode.fget, result["TimeCodeRange"].endTimeCode.fset, result["TimeCodeRange"].endTimeCode.fdel, """type : TimeCode
Return the end time code of this range.
""")
result["TimeCodeRange"].stride = property(result["TimeCodeRange"].stride.fget, result["TimeCodeRange"].stride.fset, result["TimeCodeRange"].stride.fdel, """type : float
Return the stride value of this range.
""") | 20,274 | Python | 27.840683 | 202 | 0.732071 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdUtils/constantsGroup.py | #
# 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.
#
"""A module for creating groups of constants. This is similar to the enum
module, but enum is not available in Python 2's standard library.
"""
import sys
import types
class _MetaConstantsGroup(type):
"""A meta-class which handles the creation and behavior of ConstantsGroups.
"""
def __new__(metacls, cls, bases, classdict):
"""Discover constants and create a new ConstantsGroup class."""
# If this is just the base ConstantsGroup class, simply create it and do
# not search for constants.
if cls == "ConstantsGroup":
return super(_MetaConstantsGroup, metacls).__new__(metacls, cls, bases, classdict)
# Search through the class-level properties and convert them into
# constants.
allConstants = list()
for key, value in classdict.items():
if (key.startswith("_") or isinstance(value, classmethod) or
isinstance(value, staticmethod)):
# Ignore variables which start with an underscore, and
# static/class methods.
pass
else:
# Found a new constant.
allConstants.append(value)
# If the constant is a function/lambda, ensure that it is not
# converted into a method.
if isinstance(value, types.FunctionType):
classdict[key] = staticmethod(value)
# All constants discovered, now create the `_all` property.
classdict["_all"] = tuple(allConstants)
# Finally, create the new ConstantsGroup class.
return super(_MetaConstantsGroup, metacls).__new__(metacls, cls, bases, classdict)
def __setattr__(cls, name, value):
"""Prevent modification of properties after a group is created."""
raise AttributeError("Constant groups cannot be modified.")
def __delattr__(cls, name):
"""Prevent deletion of properties after a group is created."""
raise AttributeError("Constant groups cannot be modified.")
def __len__(self):
"""Get the number of constants in the group."""
return len(self._all)
def __contains__(self, value):
"""Check if a constant exists in the group."""
return (value in self._all)
def __iter__(self):
"""Iterate over each constant in the group."""
return iter(self._all)
# We want to define a ConstantsGroup class that uses _MetaConstantsGroup
# as its metaclass. The syntax for doing so in Python 3 is not backwards
# compatible for Python 2, so we cannot just conditionally define one
# form or the other because that will cause syntax errors when compiling
# this file. To avoid this we add a layer of indirection through exec().
if sys.version_info.major >= 3:
defineConstantsGroup = '''
class ConstantsGroup(object, metaclass=_MetaConstantsGroup):
"""The base constant group class, intended to be inherited by actual groups
of constants.
"""
def __new__(cls, *args, **kwargs):
raise TypeError("ConstantsGroup objects cannot be created.")
'''
else:
defineConstantsGroup = '''
class ConstantsGroup(object):
"""The base constant group class, intended to be inherited by actual groups
of constants.
"""
__metaclass__ = _MetaConstantsGroup
def __new__(cls, *args, **kwargs):
raise TypeError("ConstantsGroup objects cannot be created.")
'''
exec(defineConstantsGroup)
| 4,517 | Python | 38.286956 | 94 | 0.67412 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Sdr/__DOC.py | def Execute(result):
result["Registry"].__doc__ = """
The shading-specialized version of ``NdrRegistry`` .
"""
result["Registry"].GetShaderNodeByIdentifier.func_doc = """GetShaderNodeByIdentifier(identifier, typePriority) -> ShaderNode
Exactly like ``NdrRegistry::GetNodeByIdentifier()`` , but returns a
``SdrShaderNode`` pointer instead of a ``NdrNode`` pointer.
Parameters
----------
identifier : NdrIdentifier
typePriority : NdrTokenVec
"""
result["Registry"].GetShaderNodeByIdentifierAndType.func_doc = """GetShaderNodeByIdentifierAndType(identifier, nodeType) -> ShaderNode
Exactly like ``NdrRegistry::GetNodeByIdentifierAndType()`` , but
returns a ``SdrShaderNode`` pointer instead of a ``NdrNode`` pointer.
Parameters
----------
identifier : NdrIdentifier
nodeType : str
"""
result["Registry"].GetShaderNodeByName.func_doc = """GetShaderNodeByName(name, typePriority, filter) -> ShaderNode
Exactly like ``NdrRegistry::GetNodeByName()`` , but returns a
``SdrShaderNode`` pointer instead of a ``NdrNode`` pointer.
Parameters
----------
name : str
typePriority : NdrTokenVec
filter : VersionFilter
"""
result["Registry"].GetShaderNodeByNameAndType.func_doc = """GetShaderNodeByNameAndType(name, nodeType, filter) -> ShaderNode
Exactly like ``NdrRegistry::GetNodeByNameAndType()`` , but returns a
``SdrShaderNode`` pointer instead of a ``NdrNode`` pointer.
Parameters
----------
name : str
nodeType : str
filter : VersionFilter
"""
result["Registry"].GetShaderNodeFromAsset.func_doc = """GetShaderNodeFromAsset(shaderAsset, metadata, subIdentifier, sourceType) -> ShaderNode
Wrapper method for NdrRegistry::GetNodeFromAsset() .
Returns a valid SdrShaderNode pointer upon success.
Parameters
----------
shaderAsset : AssetPath
metadata : NdrTokenMap
subIdentifier : str
sourceType : str
"""
result["Registry"].GetShaderNodeFromSourceCode.func_doc = """GetShaderNodeFromSourceCode(sourceCode, sourceType, metadata) -> ShaderNode
Wrapper method for NdrRegistry::GetNodeFromSourceCode() .
Returns a valid SdrShaderNode pointer upon success.
Parameters
----------
sourceCode : str
sourceType : str
metadata : NdrTokenMap
"""
result["Registry"].GetShaderNodesByIdentifier.func_doc = """GetShaderNodesByIdentifier(identifier) -> SdrShaderNodePtrVec
Exactly like ``NdrRegistry::GetNodesByIdentifier()`` , but returns a
vector of ``SdrShaderNode`` pointers instead of a vector of
``NdrNode`` pointers.
Parameters
----------
identifier : NdrIdentifier
"""
result["Registry"].GetShaderNodesByName.func_doc = """GetShaderNodesByName(name, filter) -> SdrShaderNodePtrVec
Exactly like ``NdrRegistry::GetNodesByName()`` , but returns a vector
of ``SdrShaderNode`` pointers instead of a vector of ``NdrNode``
pointers.
Parameters
----------
name : str
filter : VersionFilter
"""
result["Registry"].GetShaderNodesByFamily.func_doc = """GetShaderNodesByFamily(family, filter) -> SdrShaderNodePtrVec
Exactly like ``NdrRegistry::GetNodesByFamily()`` , but returns a
vector of ``SdrShaderNode`` pointers instead of a vector of
``NdrNode`` pointers.
Parameters
----------
family : str
filter : VersionFilter
"""
result["Registry"].__init__.func_doc = """__init__()
"""
result["ShaderNode"].__doc__ = """
A specialized version of ``NdrNode`` which holds shading information.
"""
result["ShaderNode"].GetShaderInput.func_doc = """GetShaderInput(inputName) -> ShaderProperty
Get a shader input property by name.
``nullptr`` is returned if an input with the given name does not
exist.
Parameters
----------
inputName : str
"""
result["ShaderNode"].GetShaderOutput.func_doc = """GetShaderOutput(outputName) -> ShaderProperty
Get a shader output property by name.
``nullptr`` is returned if an output with the given name does not
exist.
Parameters
----------
outputName : str
"""
result["ShaderNode"].GetAssetIdentifierInputNames.func_doc = """GetAssetIdentifierInputNames() -> NdrTokenVec
Returns the list of all inputs that are tagged as asset identifier
inputs.
"""
result["ShaderNode"].GetDefaultInput.func_doc = """GetDefaultInput() -> ShaderProperty
Returns the first shader input that is tagged as the default input.
A default input and its value can be used to acquire a fallback value
for a node when the node is considered'disabled'or otherwise incapable
of producing an output value.
"""
result["ShaderNode"].GetLabel.func_doc = """GetLabel() -> str
The label assigned to this node, if any.
Distinct from the name returned from ``GetName()`` . In the context of
a UI, the label value might be used as the display name for the node
instead of the name.
"""
result["ShaderNode"].GetCategory.func_doc = """GetCategory() -> str
The category assigned to this node, if any.
Distinct from the family returned from ``GetFamily()`` .
"""
result["ShaderNode"].GetRole.func_doc = """GetRole() -> str
Returns the role of this node.
This is used to annotate the role that the shader node plays inside a
shader network. We can tag certain shaders to indicate their role
within a shading network. We currently tag primvar reading nodes,
texture reading nodes and nodes that access volume fields (like
extinction or scattering). This is done to identify resources used by
a shading network.
"""
result["ShaderNode"].GetHelp.func_doc = """GetHelp() -> str
The help message assigned to this node, if any.
"""
result["ShaderNode"].GetDepartments.func_doc = """GetDepartments() -> NdrTokenVec
The departments this node is associated with, if any.
"""
result["ShaderNode"].GetPages.func_doc = """GetPages() -> NdrTokenVec
Gets the pages on which the node's properties reside (an aggregate of
the unique ``SdrShaderProperty::GetPage()`` values for all of the
node's properties).
Nodes themselves do not reside on pages. In an example scenario,
properties might be divided into two pages,'Simple'and'Advanced'.
"""
result["ShaderNode"].GetPrimvars.func_doc = """GetPrimvars() -> NdrTokenVec
The list of primvars this node knows it requires / uses.
For example, a shader node may require the'normals'primvar to function
correctly. Additional, user specified primvars may have been authored
on the node. These can be queried via
``GetAdditionalPrimvarProperties()`` . Together, ``GetPrimvars()`` and
``GetAdditionalPrimvarProperties()`` , provide the complete list of
primvar requirements for the node.
"""
result["ShaderNode"].GetAdditionalPrimvarProperties.func_doc = """GetAdditionalPrimvarProperties() -> NdrTokenVec
The list of string input properties whose values provide the names of
additional primvars consumed by this node.
For example, this may return a token named ``varname`` . This
indicates that the client should query the value of a (presumed to be
string-valued) input attribute named varname from its scene
description to determine the name of a primvar the node will consume.
See ``GetPrimvars()`` for additional information.
"""
result["ShaderNode"].GetImplementationName.func_doc = """GetImplementationName() -> str
Returns the implementation name of this node.
The name of the node is how to refer to the node in shader networks.
The label is how to present this node to users. The implementation
name is the name of the function (or something) this node represents
in the implementation. Any client using the implementation **must**
call this method to get the correct name; using ``getName()`` is not
correct.
"""
result["ShaderNode"].GetPropertyNamesForPage.func_doc = """GetPropertyNamesForPage(pageName) -> NdrTokenVec
Gets the names of the properties on a certain page (one that was
returned by ``GetPages()`` ).
To get properties that are not assigned to a page, an empty string can
be used for ``pageName`` .
Parameters
----------
pageName : str
"""
result["ShaderNode"].GetAllVstructNames.func_doc = """GetAllVstructNames() -> NdrTokenVec
Gets all vstructs that are present in the shader.
"""
result["ShaderProperty"].__doc__ = """
A specialized version of ``NdrProperty`` which holds shading
information.
"""
result["ShaderProperty"].GetLabel.func_doc = """GetLabel() -> str
The label assigned to this property, if any.
Distinct from the name returned from ``GetName()`` . In the context of
a UI, the label value might be used as the display name for the
property instead of the name.
"""
result["ShaderProperty"].GetHelp.func_doc = """GetHelp() -> str
The help message assigned to this property, if any.
"""
result["ShaderProperty"].GetPage.func_doc = """GetPage() -> str
The page (group), eg"Advanced", this property appears on, if any.
Note that the page for a shader property can be nested, delimited
by":", representing the hierarchy of sub-pages a property is defined
in.
"""
result["ShaderProperty"].GetWidget.func_doc = """GetWidget() -> str
The widget"hint"that indicates the widget that can best display the
type of data contained in this property, if any.
Examples of this value could include"number","slider", etc.
"""
result["ShaderProperty"].GetHints.func_doc = """GetHints() -> NdrTokenMap
Any UI"hints"that are associated with this property.
"Hints"are simple key/value pairs.
"""
result["ShaderProperty"].GetOptions.func_doc = """GetOptions() -> NdrOptionVec
If the property has a set of valid values that are pre-determined,
this will return the valid option names and corresponding string
values (if the option was specified with a value).
"""
result["ShaderProperty"].GetImplementationName.func_doc = """GetImplementationName() -> str
Returns the implementation name of this property.
The name of the property is how to refer to the property in shader
networks. The label is how to present this property to users. The
implementation name is the name of the parameter this property
represents in the implementation. Any client using the implementation
**must** call this method to get the correct name; using ``getName()``
is not correct.
"""
result["ShaderProperty"].GetVStructMemberOf.func_doc = """GetVStructMemberOf() -> str
If this field is part of a vstruct, this is the name of the struct.
"""
result["ShaderProperty"].GetVStructMemberName.func_doc = """GetVStructMemberName() -> str
If this field is part of a vstruct, this is its name in the struct.
"""
result["ShaderProperty"].IsVStructMember.func_doc = """IsVStructMember() -> bool
Returns true if this field is part of a vstruct.
"""
result["ShaderProperty"].IsVStruct.func_doc = """IsVStruct() -> bool
Returns true if the field is the head of a vstruct.
"""
result["ShaderProperty"].GetVStructConditionalExpr.func_doc = """GetVStructConditionalExpr() -> str
If this field is part of a vstruct, this is the conditional
expression.
"""
result["ShaderProperty"].IsConnectable.func_doc = """IsConnectable() -> bool
Whether this property can be connected to other properties.
If this returns ``true`` , connectability to a specific property can
be tested via ``CanConnectTo()`` .
"""
result["ShaderProperty"].GetValidConnectionTypes.func_doc = """GetValidConnectionTypes() -> NdrTokenVec
Gets the list of valid connection types for this property.
This value comes from shader metadata, and may not be specified. The
value from ``NdrProperty::GetType()`` can be used as a fallback, or
you can use the connectability test in ``CanConnectTo()`` .
"""
result["ShaderProperty"].CanConnectTo.func_doc = """CanConnectTo(other) -> bool
Determines if this property can be connected to the specified
property.
Parameters
----------
other : Property
"""
result["ShaderProperty"].GetTypeAsSdfType.func_doc = """GetTypeAsSdfType() -> NdrSdfTypeIndicator
Converts the property's type from ``GetType()`` into a
``SdfValueTypeName`` .
Two scenarios can result: an exact mapping from property type to Sdf
type, and an inexact mapping. In the first scenario, the first element
in the pair will be the cleanly-mapped Sdf type, and the second
element, a TfToken, will be empty. In the second scenario, the Sdf
type will be set to ``Token`` to indicate an unclean mapping, and the
second element will be set to the original type returned by
``GetType()`` .
GetDefaultValueAsSdfType
"""
result["ShaderProperty"].GetDefaultValueAsSdfType.func_doc = """GetDefaultValueAsSdfType() -> VtValue
Accessor for default value corresponding to the SdfValueTypeName
returned by GetTypeAsSdfType.
Note that this is different than GetDefaultValue which returns the
default value associated with the SdrPropertyType and may differ from
the SdfValueTypeName, example when sdrUsdDefinitionType metadata is
specified for a sdr property.
GetTypeAsSdfType
"""
result["ShaderProperty"].IsAssetIdentifier.func_doc = """IsAssetIdentifier() -> bool
Determines if the value held by this property is an asset identifier
(eg, a file path); the logic for this is left up to the parser.
Note: The type returned from ``GetTypeAsSdfType()`` will be ``Asset``
if this method returns ``true`` (even though its true underlying data
type is string).
"""
result["ShaderProperty"].IsDefaultInput.func_doc = """IsDefaultInput() -> bool
Determines if the value held by this property is the default input for
this node.
""" | 13,369 | Python | 21.738095 | 145 | 0.735582 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Sdr/shaderParserTestUtils.py | #!/pxrpythonsubst
#
# Copyright 2018 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.
"""
Common utilities that shader-based parser plugins can use in their tests.
This is mostly focused on dealing with OSL and Args files. This may need to be
expanded/generalized to accommodate other types in the future.
"""
from __future__ import print_function
from pxr import Ndr
from pxr import Sdr
from pxr.Sdf import ValueTypeNames as SdfTypes
from pxr import Tf
def IsNodeOSL(node):
"""
Determines if the given node has an OSL source type.
"""
return node.GetSourceType() == "OSL"
# XXX Maybe rename this to GetSdfType (as opposed to the Sdr type)
def GetType(property):
"""
Given a property (SdrShaderProperty), return the SdfValueTypeName type.
"""
sdfTypeIndicator = property.GetTypeAsSdfType()
sdfValueTypeName = sdfTypeIndicator[0]
tfType = sdfValueTypeName.type
return tfType
def TestBasicProperties(node):
"""
Test the correctness of the properties on the specified node (only the
non-shading-specific aspects).
"""
isOSL = IsNodeOSL(node)
# Data that varies between OSL/Args
# --------------------------------------------------------------------------
metadata = {
"widget": "number",
"label": "inputA label",
"page": "inputs1",
"help": "inputA help message",
"uncategorized": "1"
}
if not isOSL:
metadata["name"] = "inputA"
metadata["default"] = "0.0"
metadata["type"] = "float"
# --------------------------------------------------------------------------
properties = {
"inputA": node.GetInput("inputA"),
"inputB": node.GetInput("inputB"),
"inputC": node.GetInput("inputC"),
"inputD": node.GetInput("inputD"),
"inputF2": node.GetInput("inputF2"),
"inputStrArray": node.GetInput("inputStrArray"),
"resultF": node.GetOutput("resultF"),
"resultI": node.GetOutput("resultI"),
}
assert properties["inputA"].GetName() == "inputA"
assert properties["inputA"].GetType() == "float"
assert properties["inputA"].GetDefaultValue() == 0.0
assert not properties["inputA"].IsOutput()
assert not properties["inputA"].IsArray()
assert not properties["inputA"].IsDynamicArray()
assert properties["inputA"].GetArraySize() == 0
assert properties["inputA"].GetInfoString() == "inputA (type: 'float'); input"
assert properties["inputA"].IsConnectable()
assert properties["inputA"].CanConnectTo(properties["resultF"])
assert not properties["inputA"].CanConnectTo(properties["resultI"])
assert properties["inputA"].GetMetadata() == metadata
# --------------------------------------------------------------------------
# Check some array variations
# --------------------------------------------------------------------------
assert properties["inputD"].IsDynamicArray()
assert properties["inputD"].GetArraySize() == 1 if isOSL else -1
assert properties["inputD"].IsArray()
assert list(properties["inputD"].GetDefaultValue()) == [1]
assert not properties["inputF2"].IsDynamicArray()
assert properties["inputF2"].GetArraySize() == 2
assert properties["inputF2"].IsArray()
assert not properties["inputF2"].IsConnectable()
assert list(properties["inputF2"].GetDefaultValue()) == [1.0, 2.0]
assert properties["inputStrArray"].GetArraySize() == 4
assert list(properties["inputStrArray"].GetDefaultValue()) == \
["test", "string", "array", "values"]
def TestShadingProperties(node):
"""
Test the correctness of the properties on the specified node (only the
shading-specific aspects).
"""
isOSL = IsNodeOSL(node)
properties = {
"inputA": node.GetShaderInput("inputA"),
"inputB": node.GetShaderInput("inputB"),
"inputC": node.GetShaderInput("inputC"),
"inputD": node.GetShaderInput("inputD"),
"inputF2": node.GetShaderInput("inputF2"),
"inputF3": node.GetShaderInput("inputF3"),
"inputF4": node.GetShaderInput("inputF4"),
"inputF5": node.GetShaderInput("inputF5"),
"inputInterp": node.GetShaderInput("inputInterp"),
"inputOptions": node.GetShaderInput("inputOptions"),
"inputPoint": node.GetShaderInput("inputPoint"),
"inputNormal": node.GetShaderInput("inputNormal"),
"inputStruct": node.GetShaderInput("inputStruct"),
"inputAssetIdentifier": node.GetShaderInput("inputAssetIdentifier"),
"resultF": node.GetShaderOutput("resultF"),
"resultF2": node.GetShaderOutput("resultF2"),
"resultF3": node.GetShaderOutput("resultF3"),
"resultI": node.GetShaderOutput("resultI"),
"vstruct1": node.GetShaderOutput("vstruct1"),
"vstruct1_bump": node.GetShaderOutput("vstruct1_bump"),
"outputPoint": node.GetShaderOutput("outputPoint"),
"outputNormal": node.GetShaderOutput("outputNormal"),
"outputColor": node.GetShaderOutput("outputColor"),
"outputVector": node.GetShaderOutput("outputVector"),
}
assert properties["inputA"].GetLabel() == "inputA label"
assert properties["inputA"].GetHelp() == "inputA help message"
assert properties["inputA"].GetPage() == "inputs1"
assert properties["inputA"].GetWidget() == "number"
assert properties["inputA"].GetHints() == {
"uncategorized": "1"
}
assert properties["inputA"].GetOptions() == []
assert properties["inputA"].GetVStructMemberOf() == ""
assert properties["inputA"].GetVStructMemberName() == ""
assert not properties["inputA"].IsVStructMember()
assert not properties["inputA"].IsVStruct()
assert properties["inputA"].IsConnectable()
assert properties["inputA"].GetValidConnectionTypes() == []
assert properties["inputA"].CanConnectTo(properties["resultF"])
assert not properties["inputA"].CanConnectTo(properties["resultI"])
# --------------------------------------------------------------------------
# Check correct options parsing
# --------------------------------------------------------------------------
assert set(properties["inputOptions"].GetOptions()) == {
("opt1", "opt1val"),
("opt2", "opt2val")
}
assert set(properties["inputInterp"].GetOptions()) == {
("linear", ""),
("catmull-rom", ""),
("bspline", ""),
("constant", ""),
}
# --------------------------------------------------------------------------
# Check cross-type connection allowances
# --------------------------------------------------------------------------
assert properties["inputPoint"].CanConnectTo(properties["outputNormal"])
assert properties["inputNormal"].CanConnectTo(properties["outputPoint"])
assert properties["inputNormal"].CanConnectTo(properties["outputColor"])
assert properties["inputNormal"].CanConnectTo(properties["outputVector"])
assert properties["inputNormal"].CanConnectTo(properties["resultF3"])
assert properties["inputF2"].CanConnectTo(properties["resultF2"])
assert properties["inputD"].CanConnectTo(properties["resultI"])
assert not properties["inputNormal"].CanConnectTo(properties["resultF2"])
assert not properties["inputF4"].CanConnectTo(properties["resultF2"])
assert not properties["inputF2"].CanConnectTo(properties["resultF3"])
# --------------------------------------------------------------------------
# Check clean and unclean mappings to Sdf types
# --------------------------------------------------------------------------
assert properties["inputB"].GetTypeAsSdfType() == (SdfTypes.Int, "")
assert properties["inputF2"].GetTypeAsSdfType() == (SdfTypes.Float2, "")
assert properties["inputF3"].GetTypeAsSdfType() == (SdfTypes.Float3, "")
assert properties["inputF4"].GetTypeAsSdfType() == (SdfTypes.Float4, "")
assert properties["inputF5"].GetTypeAsSdfType() == (SdfTypes.FloatArray, "")
assert properties["inputStruct"].GetTypeAsSdfType() == \
(SdfTypes.Token, Sdr.PropertyTypes.Struct)
# --------------------------------------------------------------------------
# Ensure asset identifiers are detected correctly
# --------------------------------------------------------------------------
assert properties["inputAssetIdentifier"].IsAssetIdentifier()
assert not properties["inputOptions"].IsAssetIdentifier()
assert properties["inputAssetIdentifier"].GetTypeAsSdfType() == \
(SdfTypes.Asset, "")
# Nested pages and VStructs are only possible in args files
if not isOSL:
# ----------------------------------------------------------------------
# Check nested page correctness
# ----------------------------------------------------------------------
assert properties["vstruct1"].GetPage() == "VStructs:Nested"
assert properties["vstruct1_bump"].GetPage() == "VStructs:Nested:More"
# ----------------------------------------------------------------------
# Check VStruct correctness
# ----------------------------------------------------------------------
assert properties["vstruct1"].IsVStruct()
assert properties["vstruct1"].GetVStructMemberOf() == ""
assert properties["vstruct1"].GetVStructMemberName() == ""
assert not properties["vstruct1"].IsVStructMember()
assert not properties["vstruct1_bump"].IsVStruct()
assert properties["vstruct1_bump"].GetVStructMemberOf() == "vstruct1"
assert properties["vstruct1_bump"].GetVStructMemberName() == "bump"
assert properties["vstruct1_bump"].IsVStructMember()
def TestBasicNode(node, nodeSourceType, nodeDefinitionURI, nodeImplementationURI):
"""
Test basic, non-shader-specific correctness on the specified node.
"""
# Implementation notes:
# ---
# The source type needs to be passed manually in order to ensure the utils
# do not have a dependency on the plugin (where the source type resides).
# The URIs are manually specified because the utils cannot know ahead of
# time where the node originated.
isOSL = IsNodeOSL(node)
nodeContext = "OSL" if isOSL else "pattern"
# Data that varies between OSL/Args
# --------------------------------------------------------------------------
nodeName = "TestNodeOSL" if isOSL else "TestNodeARGS"
numOutputs = 8 if isOSL else 10
outputNames = {
"resultF", "resultF2", "resultF3", "resultI", "outputPoint",
"outputNormal", "outputColor", "outputVector"
}
metadata = {
"category": "testing",
"departments": "testDept",
"help": "This is the test node",
"label": "TestNodeLabel",
"primvars": "primvar1|primvar2|primvar3|$primvarNamingProperty|"
"$invalidPrimvarNamingProperty",
"uncategorizedMetadata": "uncategorized"
}
if not isOSL:
metadata.pop("category")
metadata.pop("label")
metadata.pop("uncategorizedMetadata")
outputNames.add("vstruct1")
outputNames.add("vstruct1_bump")
# --------------------------------------------------------------------------
nodeInputs = {propertyName: node.GetShaderInput(propertyName)
for propertyName in node.GetInputNames()}
nodeOutputs = {propertyName: node.GetShaderOutput(propertyName)
for propertyName in node.GetOutputNames()}
assert node.GetName() == nodeName
assert node.GetContext() == nodeContext
assert node.GetSourceType() == nodeSourceType
assert node.GetFamily() == ""
assert node.GetResolvedDefinitionURI() == nodeDefinitionURI
assert node.GetResolvedImplementationURI() == nodeImplementationURI
assert node.IsValid()
assert len(nodeInputs) == 17
assert len(nodeOutputs) == numOutputs
assert nodeInputs["inputA"] is not None
assert nodeInputs["inputB"] is not None
assert nodeInputs["inputC"] is not None
assert nodeInputs["inputD"] is not None
assert nodeInputs["inputF2"] is not None
assert nodeInputs["inputF3"] is not None
assert nodeInputs["inputF4"] is not None
assert nodeInputs["inputF5"] is not None
assert nodeInputs["inputInterp"] is not None
assert nodeInputs["inputOptions"] is not None
assert nodeInputs["inputPoint"] is not None
assert nodeInputs["inputNormal"] is not None
assert nodeOutputs["resultF2"] is not None
assert nodeOutputs["resultI"] is not None
assert nodeOutputs["outputPoint"] is not None
assert nodeOutputs["outputNormal"] is not None
assert nodeOutputs["outputColor"] is not None
assert nodeOutputs["outputVector"] is not None
print(set(node.GetInputNames()))
assert set(node.GetInputNames()) == {
"inputA", "inputB", "inputC", "inputD", "inputF2", "inputF3", "inputF4",
"inputF5", "inputInterp", "inputOptions", "inputPoint", "inputNormal",
"inputStruct", "inputAssetIdentifier", "primvarNamingProperty",
"invalidPrimvarNamingProperty", "inputStrArray"
}
assert set(node.GetOutputNames()) == outputNames
# There may be additional metadata passed in via the NdrNodeDiscoveryResult.
# So, ensure that the bits we expect to see are there instead of doing
# an equality check.
nodeMetadata = node.GetMetadata()
for i,j in metadata.items():
assert i in nodeMetadata
assert nodeMetadata[i] == metadata[i]
# Test basic property correctness
TestBasicProperties(node)
def TestShaderSpecificNode(node):
"""
Test shader-specific correctness on the specified node.
"""
isOSL = IsNodeOSL(node)
# Data that varies between OSL/Args
# --------------------------------------------------------------------------
numOutputs = 8 if isOSL else 10
label = "TestNodeLabel" if isOSL else ""
category = "testing" if isOSL else ""
vstructNames = [] if isOSL else ["vstruct1"]
pages = {"", "inputs1", "inputs2", "results"} if isOSL else \
{"", "inputs1", "inputs2", "results", "VStructs:Nested",
"VStructs:Nested:More"}
# --------------------------------------------------------------------------
shaderInputs = {propertyName: node.GetShaderInput(propertyName)
for propertyName in node.GetInputNames()}
shaderOutputs = {propertyName: node.GetShaderOutput(propertyName)
for propertyName in node.GetOutputNames()}
assert len(shaderInputs) == 17
assert len(shaderOutputs) == numOutputs
assert shaderInputs["inputA"] is not None
assert shaderInputs["inputB"] is not None
assert shaderInputs["inputC"] is not None
assert shaderInputs["inputD"] is not None
assert shaderInputs["inputF2"] is not None
assert shaderInputs["inputF3"] is not None
assert shaderInputs["inputF4"] is not None
assert shaderInputs["inputF5"] is not None
assert shaderInputs["inputInterp"] is not None
assert shaderInputs["inputOptions"] is not None
assert shaderInputs["inputPoint"] is not None
assert shaderInputs["inputNormal"] is not None
assert shaderOutputs["resultF"] is not None
assert shaderOutputs["resultF2"] is not None
assert shaderOutputs["resultF3"] is not None
assert shaderOutputs["resultI"] is not None
assert shaderOutputs["outputPoint"] is not None
assert shaderOutputs["outputNormal"] is not None
assert shaderOutputs["outputColor"] is not None
assert shaderOutputs["outputVector"] is not None
assert node.GetLabel() == label
assert node.GetCategory() == category
assert node.GetHelp() == "This is the test node"
assert node.GetDepartments() == ["testDept"]
assert set(node.GetPages()) == pages
assert set(node.GetPrimvars()) == {"primvar1", "primvar2", "primvar3"}
assert set(node.GetAdditionalPrimvarProperties()) == {"primvarNamingProperty"}
assert set(node.GetPropertyNamesForPage("results")) == {
"resultF", "resultF2", "resultF3", "resultI"
}
assert set(node.GetPropertyNamesForPage("")) == {
"outputPoint", "outputNormal", "outputColor", "outputVector"
}
assert set(node.GetPropertyNamesForPage("inputs1")) == {"inputA"}
assert set(node.GetPropertyNamesForPage("inputs2")) == {
"inputB", "inputC", "inputD", "inputF2", "inputF3", "inputF4", "inputF5",
"inputInterp", "inputOptions", "inputPoint", "inputNormal",
"inputStruct", "inputAssetIdentifier", "primvarNamingProperty",
"invalidPrimvarNamingProperty", "inputStrArray"
}
assert node.GetAllVstructNames() == vstructNames
# Test shading-specific property correctness
TestShadingProperties(node)
def TestShaderPropertiesNode(node):
"""
Tests property correctness on the specified shader node, which must be
one of the following pre-defined nodes:
* 'TestShaderPropertiesNodeOSL'
* 'TestShaderPropertiesNodeARGS'
* 'TestShaderPropertiesNodeUSD'
These pre-defined nodes have a property of every type that Sdr supports.
Property correctness is defined as:
* The shader property has the expected SdrPropertyType
* The shader property has the expected SdfValueTypeName
* If the shader property has a default value, the default value's type
matches the shader property's type
"""
# This test should only be run on the following allowed node names
# --------------------------------------------------------------------------
allowedNodeNames = ["TestShaderPropertiesNodeOSL",
"TestShaderPropertiesNodeARGS",
"TestShaderPropertiesNodeUSD"]
# If this assertion on the name fails, then this test was called with the
# wrong node.
assert node.GetName() in allowedNodeNames
# If we have the correct node name, double check that the source type is
# also correct
if node.GetName() == "TestShaderPropertiesNodeOSL":
assert node.GetSourceType() == "OSL"
elif node.GetName() == "TestShaderPropertiesNodeARGS":
assert node.GetSourceType() == "RmanCpp"
elif node.GetName() == "TestShaderPropertiesNodeUSD":
assert node.GetSourceType() == "glslfx"
nodeInputs = {propertyName: node.GetShaderInput(propertyName)
for propertyName in node.GetInputNames()}
nodeOutputs = {propertyName: node.GetShaderOutput(propertyName)
for propertyName in node.GetOutputNames()}
# For each property, we test that:
# * The property has the expected SdrPropertyType
# * The property has the expected TfType (from SdfValueTypeName)
# * The property's type and default value's type match
property = nodeInputs["inputInt"]
assert property.GetType() == Sdr.PropertyTypes.Int
assert GetType(property) == Tf.Type.FindByName("int")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputString"]
assert property.GetType() == Sdr.PropertyTypes.String
assert GetType(property) == Tf.Type.FindByName("string")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloat"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("float")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputColor"]
assert property.GetType() == Sdr.PropertyTypes.Color
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputPoint"]
assert property.GetType() == Sdr.PropertyTypes.Point
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputNormal"]
assert property.GetType() == Sdr.PropertyTypes.Normal
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputVector"]
assert property.GetType() == Sdr.PropertyTypes.Vector
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputMatrix"]
assert property.GetType() == Sdr.PropertyTypes.Matrix
assert GetType(property) == Tf.Type.FindByName("GfMatrix4d")
assert Ndr._ValidateProperty(node, property)
if node.GetName() != "TestShaderPropertiesNodeUSD":
# XXX Note that 'struct' and 'vstruct' types are currently unsupported
# by the UsdShadeShaderDefParserPlugin, which parses shaders defined in
# usd files. Please see UsdShadeShaderDefParserPlugin implementation for
# details.
property = nodeInputs["inputStruct"]
assert property.GetType() == Sdr.PropertyTypes.Struct
assert GetType(property) == Tf.Type.FindByName("TfToken")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputVstruct"]
assert property.GetType() == Sdr.PropertyTypes.Vstruct
assert GetType(property) == Tf.Type.FindByName("TfToken")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputIntArray"]
assert property.GetType() == Sdr.PropertyTypes.Int
assert GetType(property) == Tf.Type.FindByName("VtArray<int>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputStringArray"]
assert property.GetType() == Sdr.PropertyTypes.String
assert GetType(property) == Tf.Type.FindByName("VtArray<string>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloatArray"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("VtArray<float>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputColorArray"]
assert property.GetType() == Sdr.PropertyTypes.Color
assert GetType(property) == Tf.Type.FindByName("VtArray<GfVec3f>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputPointArray"]
assert property.GetType() == Sdr.PropertyTypes.Point
assert GetType(property) == Tf.Type.FindByName("VtArray<GfVec3f>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputNormalArray"]
assert property.GetType() == Sdr.PropertyTypes.Normal
assert GetType(property) == Tf.Type.FindByName("VtArray<GfVec3f>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputVectorArray"]
assert property.GetType() == Sdr.PropertyTypes.Vector
assert GetType(property) == Tf.Type.FindByName("VtArray<GfVec3f>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputMatrixArray"]
assert property.GetType() == Sdr.PropertyTypes.Matrix
assert GetType(property) == Tf.Type.FindByName("VtArray<GfMatrix4d>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloat2"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec2f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloat3"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputFloat4"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec4f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputAsset"]
assert property.GetType() == Sdr.PropertyTypes.String
assert GetType(property) == Tf.Type.FindByName("SdfAssetPath")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputAssetArray"]
assert property.GetType() == Sdr.PropertyTypes.String
assert GetType(property) == Tf.Type.FindByName("VtArray<SdfAssetPath>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputColorRoleNone"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputPointRoleNone"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputNormalRoleNone"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputVectorRoleNone"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec3f")
assert Ndr._ValidateProperty(node, property)
property = nodeOutputs["outputSurface"]
assert property.GetType() == Sdr.PropertyTypes.Terminal
assert GetType(property) == Tf.Type.FindByName("TfToken")
assert Ndr._ValidateProperty(node, property)
# Specific test of implementationName feature, we can skip type-tests
property = nodeInputs["normal"]
assert property.GetImplementationName() == "aliasedNormalInput"
assert Ndr._ValidateProperty(node, property)
if node.GetName() != "TestShaderPropertiesNodeOSL" and \
node.GetName() != "TestShaderPropertiesNodeARGS" :
# We will parse color4 in MaterialX and UsdShade. Not currently
# supported in OSL. rman Args also do not support / require color4 type.
property = nodeInputs["inputColor4"]
assert property.GetType() == Sdr.PropertyTypes.Color4
assert GetType(property) == Tf.Type.FindByName("GfVec4f")
assert Ndr._ValidateProperty(node, property)
# oslc v1.11.14 does not allow arrays of structs as parameter.
property = nodeInputs["inputColor4Array"]
assert property.GetType() == Sdr.PropertyTypes.Color4
assert GetType(property) == Tf.Type.FindByName("VtArray<GfVec4f>")
assert Ndr._ValidateProperty(node, property)
property = nodeInputs["inputColor4RoleNone"]
assert property.GetType() == Sdr.PropertyTypes.Float
assert GetType(property) == Tf.Type.FindByName("GfVec4f")
assert Ndr._ValidateProperty(node, property)
| 27,467 | Python | 42.393365 | 82 | 0.65089 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdHydra/__DOC.py | def Execute(result):
result["GenerativeProceduralAPI"].__doc__ = """
This API extends and configures the core UsdProcGenerativeProcedural
schema defined within usdProc for use with hydra generative
procedurals as defined within hdGp.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdHydraTokens. So to set an attribute to the value"rightHanded",
use UsdHydraTokens->rightHanded as the value.
"""
result["GenerativeProceduralAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdHydraGenerativeProceduralAPI on UsdPrim ``prim`` .
Equivalent to UsdHydraGenerativeProceduralAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdHydraGenerativeProceduralAPI on the prim held by
``schemaObj`` .
Should be preferred over UsdHydraGenerativeProceduralAPI
(schemaObj.GetPrim()), as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["GenerativeProceduralAPI"].GetProceduralTypeAttr.func_doc = """GetProceduralTypeAttr() -> Attribute
The registered name of a HdGpGenerativeProceduralPlugin to be
executed.
Declaration
``token primvars:hdGp:proceduralType``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["GenerativeProceduralAPI"].CreateProceduralTypeAttr.func_doc = """CreateProceduralTypeAttr(defaultValue, writeSparsely) -> Attribute
See GetProceduralTypeAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["GenerativeProceduralAPI"].GetProceduralSystemAttr.func_doc = """GetProceduralSystemAttr() -> Attribute
This value should correspond to a configured instance of
HdGpGenerativeProceduralResolvingSceneIndex which will evaluate the
procedural.
The default value of"hydraGenerativeProcedural"matches the equivalent
default of HdGpGenerativeProceduralResolvingSceneIndex. Multiple
instances of the scene index can be used to determine where within a
scene index chain a given procedural will be evaluated.
Declaration
``token proceduralSystem ="hydraGenerativeProcedural"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
"""
result["GenerativeProceduralAPI"].CreateProceduralSystemAttr.func_doc = """CreateProceduralSystemAttr(defaultValue, writeSparsely) -> Attribute
See GetProceduralSystemAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["GenerativeProceduralAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["GenerativeProceduralAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> GenerativeProceduralAPI
Return a UsdHydraGenerativeProceduralAPI holding the prim adhering to
this schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdHydraGenerativeProceduralAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["GenerativeProceduralAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["GenerativeProceduralAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> GenerativeProceduralAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"HydraGenerativeProceduralAPI"to
the token-valued, listOp metadata *apiSchemas* on the prim.
A valid UsdHydraGenerativeProceduralAPI object is returned upon
success. An invalid (or empty) UsdHydraGenerativeProceduralAPI object
is returned upon failure. See UsdPrim::ApplyAPI() for conditions
resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["GenerativeProceduralAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
""" | 5,684 | Python | 21.559524 | 149 | 0.746129 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Vt/__init__.py | #
# Copyright 2016 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.
#
"""Vt Value Types library
This package defines classes for creating objects that behave like value
types. It contains facilities for creating simple copy-on-write
implicitly shared types.
"""
from pxr import Tf
Tf.PreparePythonModule()
del Tf
# For ease-of-use, put each XXXArrayFromBuffer method on its corresponding array
# wrapper class, also alias it as 'FromNumpy' for compatibility.
def _CopyArrayFromBufferFuncs(moduleContents):
funcs = dict([(key, val) for (key, val) in moduleContents.items()
if key.endswith('FromBuffer')])
classes = dict([(key, val) for (key, val) in moduleContents.items()
if key.endswith('Array') and isinstance(val, type)])
for funcName, func in funcs.items():
className = funcName[:-len('FromBuffer')]
cls = classes.get(className)
if cls:
setattr(cls, 'FromBuffer', staticmethod(func))
setattr(cls, 'FromNumpy', staticmethod(func))
_CopyArrayFromBufferFuncs(dict(vars()))
del _CopyArrayFromBufferFuncs
| 2,097 | Python | 39.346153 | 80 | 0.729614 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdGeom/__DOC.py | def Execute(result):
result["BasisCurves"].__doc__ = """
BasisCurves are a batched curve representation analogous to the
classic RIB definition via Basis and Curves statements. BasisCurves
are often used to render dense aggregate geometry like hair or grass.
A'matrix'and'vstep'associated with the *basis* are used to interpolate
the vertices of a cubic BasisCurves. (The basis attribute is unused
for linear BasisCurves.)
A single prim may have many curves whose count is determined
implicitly by the length of the *curveVertexCounts* vector. Each
individual curve is composed of one or more segments. Each segment is
defined by four vertices for cubic curves and two vertices for linear
curves. See the next section for more information on how to map curve
vertex counts to segment counts.
Segment Indexing
================
Interpolating a curve requires knowing how to decompose it into its
individual segments.
The segments of a cubic curve are determined by the vertex count, the
*wrap* (periodicity), and the vstep of the basis. For linear curves,
the basis token is ignored and only the vertex count and wrap are
needed.
cubic basis
vstep
bezier
3
catmullRom
1
bspline
1
The first segment of a cubic (nonperiodic) curve is always defined by
its first four points. The vstep is the increment used to determine
what vertex indices define the next segment. For a two segment
(nonperiodic) bspline basis curve (vstep = 1), the first segment will
be defined by interpolating vertices [0, 1, 2, 3] and the second
segment will be defined by [1, 2, 3, 4]. For a two segment bezier
basis curve (vstep = 3), the first segment will be defined by
interpolating vertices [0, 1, 2, 3] and the second segment will be
defined by [3, 4, 5, 6]. If the vstep is not one, then you must take
special care to make sure that the number of cvs properly divides by
your vstep. (The indices described are relative to the initial vertex
index for a batched curve.)
For periodic curves, at least one of the curve's initial vertices are
repeated to close the curve. For cubic curves, the number of vertices
repeated is'4 - vstep'. For linear curves, only one vertex is repeated
to close the loop.
Pinned curves are a special case of nonperiodic curves that only
affects the behavior of cubic Bspline and Catmull-Rom curves. To
evaluate or render pinned curves, a client must effectively
add'phantom points'at the beginning and end of every curve in a batch.
These phantom points are injected to ensure that the interpolated
curve begins at P[0] and ends at P[n-1].
For a curve with initial point P[0] and last point P[n-1], the phantom
points are defined as. P[-1] = 2 \\* P[0] - P[1] P[n] = 2 \\* P[n-1] -
P[n-2]
Pinned cubic curves will (usually) have to be unpacked into the
standard nonperiodic representation before rendering. This unpacking
can add some additional overhead. However, using pinned curves reduces
the amount of data recorded in a scene and (more importantly) better
records the authors'intent for interchange.
The additional phantom points mean that the minimum curve vertex count
for cubic bspline and catmullRom curves is 2. Linear curve segments
are defined by two vertices. A two segment linear curve's first
segment would be defined by interpolating vertices [0, 1]. The second
segment would be defined by vertices [1, 2]. (Again, for a batched
curve, indices are relative to the initial vertex index.)
When validating curve topology, each renderable entry in the
curveVertexCounts vector must pass this check.
type
wrap
validitity
linear
nonperiodic
curveVertexCounts[i]>2
linear
periodic
curveVertexCounts[i]>3
cubic
nonperiodic
(curveVertexCounts[i] - 4) % vstep == 0
cubic
periodic
(curveVertexCounts[i]) % vstep == 0
cubic
pinned (catmullRom/bspline)
(curveVertexCounts[i] - 2)>= 0
Cubic Vertex Interpolation
==========================
Linear Vertex Interpolation
===========================
Linear interpolation is always used on curves of type linear.'t'with
domain [0, 1], the curve is defined by the equation P0 \\* (1-t) + P1
\\* t. t at 0 describes the first point and t at 1 describes the end
point.
Primvar Interpolation
=====================
For cubic curves, primvar data can be either interpolated cubically
between vertices or linearly across segments. The corresponding token
for cubic interpolation is'vertex'and for linear interpolation
is'varying'. Per vertex data should be the same size as the number of
vertices in your curve. Segment varying data is dependent on the wrap
(periodicity) and number of segments in your curve. For linear curves,
varying and vertex data would be interpolated the same way. By
convention varying is the preferred interpolation because of the
association of varying with linear interpolation.
To convert an entry in the curveVertexCounts vector into a segment
count for an individual curve, apply these rules. Sum up all the
results in order to compute how many total segments all curves have.
The following tables describe the expected segment count for the'i'th
curve in a curve batch as well as the entire batch. Python syntax
like'[:]'(to describe all members of an array) and'len(\\.\\.\\.)'(to
describe the length of an array) are used.
type
wrap
curve segment count
batch segment count
linear
nonperiodic
curveVertexCounts[i] - 1
sum(curveVertexCounts[:]) - len(curveVertexCounts)
linear
periodic
curveVertexCounts[i]
sum(curveVertexCounts[:])
cubic
nonperiodic
(curveVertexCounts[i] - 4) / vstep + 1
sum(curveVertexCounts[:] - 4) / vstep + len(curveVertexCounts)
cubic
periodic
curveVertexCounts[i] / vstep
sum(curveVertexCounts[:]) / vstep
cubic
pinned (catmullRom/bspline)
(curveVertexCounts[i] - 2) + 1
sum(curveVertexCounts[:] - 2) + len(curveVertexCounts)
The following table descrives the expected size of varying (linearly
interpolated) data, derived from the segment counts computed above.
wrap
curve varying count
batch varying count
nonperiodic/pinned
segmentCounts[i] + 1
sum(segmentCounts[:]) + len(curveVertexCounts)
periodic
segmentCounts[i]
sum(segmentCounts[:])
Both curve types additionally define'constant'interpolation for the
entire prim and'uniform'interpolation as per curve data.
Take care when providing support for linearly interpolated data for
cubic curves. Its shape doesn't provide a one to one mapping with
either the number of curves (like'uniform') or the number of vertices
(like'vertex') and so it is often overlooked. This is the only
primitive in UsdGeom (as of this writing) where this is true. For
meshes, while they use different interpolation
methods,'varying'and'vertex'are both specified per point. It's common
to assume that curves follow a similar pattern and build in structures
and language for per primitive, per element, and per point data only
to come upon these arrays that don't quite fit into either of those
categories. It is also common to conflate'varying'with being per
segment data and use the segmentCount rules table instead of its
neighboring varying data table rules. We suspect that this is because
for the common case of nonperiodic cubic curves, both the provided
segment count and varying data size formula end with'+ 1'. While
debugging, users may look at the double'+ 1'as a mistake and try to
remove it. We take this time to enumerate these issues because we've
fallen into them before and hope that we save others time in their own
implementations. As an example of deriving per curve segment and
varying primvar data counts from the wrap, type, basis, and
curveVertexCount, the following table is provided.
wrap
type
basis
curveVertexCount
curveSegmentCount
varyingDataCount
nonperiodic
linear
N/A
[2 3 2 5]
[1 2 1 4]
[2 3 2 5]
nonperiodic
cubic
bezier
[4 7 10 4 7]
[1 2 3 1 2]
[2 3 4 2 3]
nonperiodic
cubic
bspline
[5 4 6 7]
[2 1 3 4]
[3 2 4 5]
periodic
cubic
bezier
[6 9 6]
[2 3 2]
[2 3 2]
periodic
linear
N/A
[3 7]
[3 7]
[3 7]
Tubes and Ribbons
=================
The strictest definition of a curve as an infinitely thin wire is not
particularly useful for describing production scenes. The additional
*widths* and *normals* attributes can be used to describe cylindrical
tubes and or flat oriented ribbons.
Curves with only widths defined are imaged as tubes with radius'width
/ 2'. Curves with both widths and normals are imaged as ribbons
oriented in the direction of the interpolated normal vectors.
While not technically UsdGeomPrimvars, widths and normals also have
interpolation metadata. It's common for authored widths to have
constant, varying, or vertex interpolation (see
UsdGeomCurves::GetWidthsInterpolation() ). It's common for authored
normals to have varying interpolation (see
UsdGeomPointBased::GetNormalsInterpolation() ).
The file used to generate these curves can be found in
pxr/extras/examples/usdGeomExamples/basisCurves.usda. It's provided as
a reference on how to properly image both tubes and ribbons. The first
row of curves are linear; the second are cubic bezier. (We aim in
future releases of HdSt to fix the discontinuity seen with broken
tangents to better match offline renderers like RenderMan.) The yellow
and violet cubic curves represent cubic vertex width interpolation for
which there is no equivalent for linear curves.
How did this prim type get its name? This prim is a portmanteau of two
different statements in the original RenderMan
specification:'Basis'and'Curves'. For any described attribute
*Fallback* *Value* or *Allowed* *Values* below that are text/tokens,
the actual token is published and defined in UsdGeomTokens. So to set
an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded
as the value.
"""
result["BasisCurves"].ComputeInterpolationForSize.func_doc = """ComputeInterpolationForSize(n, timeCode, info) -> str
Computes interpolation token for ``n`` .
If this returns an empty token and ``info`` was non-None, it'll
contain the expected value for each token.
The topology is determined using ``timeCode`` .
Parameters
----------
n : int
timeCode : TimeCode
info : ComputeInterpolationInfo
"""
result["BasisCurves"].ComputeUniformDataSize.func_doc = """ComputeUniformDataSize(timeCode) -> int
Computes the expected size for data with"uniform"interpolation.
If you're trying to determine what interpolation to use, it is more
efficient to use ``ComputeInterpolationForSize``
Parameters
----------
timeCode : TimeCode
"""
result["BasisCurves"].ComputeVaryingDataSize.func_doc = """ComputeVaryingDataSize(timeCode) -> int
Computes the expected size for data with"varying"interpolation.
If you're trying to determine what interpolation to use, it is more
efficient to use ``ComputeInterpolationForSize``
Parameters
----------
timeCode : TimeCode
"""
result["BasisCurves"].ComputeVertexDataSize.func_doc = """ComputeVertexDataSize(timeCode) -> int
Computes the expected size for data with"vertex"interpolation.
If you're trying to determine what interpolation to use, it is more
efficient to use ``ComputeInterpolationForSize``
Parameters
----------
timeCode : TimeCode
"""
result["BasisCurves"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomBasisCurves on UsdPrim ``prim`` .
Equivalent to UsdGeomBasisCurves::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomBasisCurves on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomBasisCurves (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["BasisCurves"].GetTypeAttr.func_doc = """GetTypeAttr() -> Attribute
Linear curves interpolate linearly between two vertices.
Cubic curves use a basis matrix with four vertices to interpolate a
segment.
Declaration
``uniform token type ="cubic"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
linear, cubic
"""
result["BasisCurves"].CreateTypeAttr.func_doc = """CreateTypeAttr(defaultValue, writeSparsely) -> Attribute
See GetTypeAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BasisCurves"].GetBasisAttr.func_doc = """GetBasisAttr() -> Attribute
The basis specifies the vstep and matrix used for cubic interpolation.
The'hermite'and'power'tokens have been removed. We've provided
UsdGeomHermiteCurves as an alternative for the'hermite'basis.
Declaration
``uniform token basis ="bezier"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
bezier, bspline, catmullRom
"""
result["BasisCurves"].CreateBasisAttr.func_doc = """CreateBasisAttr(defaultValue, writeSparsely) -> Attribute
See GetBasisAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BasisCurves"].GetWrapAttr.func_doc = """GetWrapAttr() -> Attribute
If wrap is set to periodic, the curve when rendered will repeat the
initial vertices (dependent on the vstep) to close the curve.
If wrap is set to'pinned', phantom points may be created to ensure
that the curve interpolation starts at P[0] and ends at P[n-1].
Declaration
``uniform token wrap ="nonperiodic"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
nonperiodic, periodic, pinned
"""
result["BasisCurves"].CreateWrapAttr.func_doc = """CreateWrapAttr(defaultValue, writeSparsely) -> Attribute
See GetWrapAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["BasisCurves"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["BasisCurves"].Get.func_doc = """**classmethod** Get(stage, path) -> BasisCurves
Return a UsdGeomBasisCurves holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomBasisCurves(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["BasisCurves"].Define.func_doc = """**classmethod** Define(stage, path) -> BasisCurves
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["BasisCurves"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["BBoxCache"].__doc__ = """
Caches bounds by recursively computing and aggregating bounds of
children in world space and aggregating the result back into local
space.
The cache is configured for a specific time and
UsdGeomImageable::GetPurposeAttr() set of purposes. When querying a
bound, transforms and extents are read either from the time specified
or UsdTimeCode::Default() , following TimeSamples, Defaults, and Value
Resolution standard time-sample value resolution. As noted in
SetIncludedPurposes() , changing the included purposes does not
invalidate the cache, because we cache purpose along with the
geometric data.
Child prims that are invisible at the requested time are excluded when
computing a prim's bounds. However, if a bound is requested directly
for an excluded prim, it will be computed. Additionally, only prims
deriving from UsdGeomImageable are included in child bounds
computations.
Unlike standard UsdStage traversals, the traversal performed by the
UsdGeomBBoxCache includesprims that are unloaded (see
UsdPrim::IsLoaded() ). This makes it possible to fetch bounds for a
UsdStage that has been opened without *forcePopulate*, provided the
unloaded model prims have authored extent hints (see
UsdGeomModelAPI::GetExtentsHint() ).
This class is optimized for computing tight
**untransformed"object"space** bounds for component-models. In the
absence of component models, bounds are optimized for world-space,
since there is no other easily identifiable space for which to
optimize, and we cannot optimize for every prim's local space without
performing quadratic work.
The TfDebug flag, USDGEOM_BBOX, is provided for debugging.
Warnings:
- This class should only be used with valid UsdPrim objects.
- This cache does not listen for change notifications; the user is
responsible for clearing the cache when changes occur.
- Thread safety: instances of this class may not be used
concurrently.
- Plugins may be loaded in order to compute extents for prim types
provided by that plugin. See
UsdGeomBoundable::ComputeExtentFromPlugins
"""
result["BBoxCache"].__init__.func_doc = """__init__(time, includedPurposes, useExtentsHint, ignoreVisibility)
Construct a new BBoxCache for a specific ``time`` and set of
``includedPurposes`` .
Only prims with a purpose that matches the ``includedPurposes`` will
be considered when accumulating child bounds. See UsdGeomImageable for
allowed purpose values.
If ``useExtentsHint`` is true, then when computing the bounds for any
model-root prim, if the prim is visible at ``time`` , we will fetch
its extents hint (via UsdGeomModelAPI::GetExtentsHint() ). If it is
authored, we use it to compute the bounding box for the selected
combination of includedPurposes by combining bounding box hints that
have been cached for various values of purposes.
If ``ignoreVisibility`` is true invisible prims will be included
during bounds computations.
Parameters
----------
time : TimeCode
includedPurposes : list[TfToken]
useExtentsHint : bool
ignoreVisibility : bool
----------------------------------------------------------------------
__init__(other)
Copy constructor.
Parameters
----------
other : BBoxCache
"""
result["BBoxCache"].ComputeWorldBound.func_doc = """ComputeWorldBound(prim) -> BBox3d
Compute the bound of the given prim in world space, leveraging any
pre-existing, cached bounds.
The bound of the prim is computed, including the transform (if any)
authored on the node itself, and then transformed to world space.
Error handling note: No checking of ``prim`` validity is performed. If
``prim`` is invalid, this method will abort the program; therefore it
is the client's responsibility to ensure ``prim`` is valid.
Parameters
----------
prim : Prim
"""
result["BBoxCache"].ComputeWorldBoundWithOverrides.func_doc = """ComputeWorldBoundWithOverrides(prim, pathsToSkip, primOverride, ctmOverrides) -> BBox3d
Computes the bound of the prim's descendents in world space while
excluding the subtrees rooted at the paths in ``pathsToSkip`` .
Additionally, the parameter ``primOverride`` overrides the local-to-
world transform of the prim and ``ctmOverrides`` is used to specify
overrides the local-to-world transforms of certain paths underneath
the prim.
This leverages any pre-existing, cached bounds, but does not include
the transform (if any) authored on the prim itself.
See ComputeWorldBound() for notes on performance and error handling.
Parameters
----------
prim : Prim
pathsToSkip : SdfPathSet
primOverride : Matrix4d
ctmOverrides : TfHashMap[Path, Matrix4d, Path.Hash]
"""
result["BBoxCache"].ComputeRelativeBound.func_doc = """ComputeRelativeBound(prim, relativeToAncestorPrim) -> BBox3d
Compute the bound of the given prim in the space of an ancestor prim,
``relativeToAncestorPrim`` , leveraging any pre-existing cached
bounds.
The computed bound excludes the local transform at
``relativeToAncestorPrim`` . The computed bound may be incorrect if
``relativeToAncestorPrim`` is not an ancestor of ``prim`` .
Parameters
----------
prim : Prim
relativeToAncestorPrim : Prim
"""
result["BBoxCache"].ComputeLocalBound.func_doc = """ComputeLocalBound(prim) -> BBox3d
Computes the oriented bounding box of the given prim, leveraging any
pre-existing, cached bounds.
The computed bound includes the transform authored on the prim itself,
but does not include any ancestor transforms (it does not include the
local-to-world transform).
See ComputeWorldBound() for notes on performance and error handling.
Parameters
----------
prim : Prim
"""
result["BBoxCache"].ComputeUntransformedBound.func_doc = """ComputeUntransformedBound(prim) -> BBox3d
Computes the bound of the prim's children leveraging any pre-existing,
cached bounds, but does not include the transform (if any) authored on
the prim itself.
**IMPORTANT:** while the BBox does not contain the local
transformation, in general it may still contain a non-identity
transformation matrix to put the bounds in the correct space.
Therefore, to obtain the correct axis-aligned bounding box, the client
must call ComputeAlignedRange().
See ComputeWorldBound() for notes on performance and error handling.
Parameters
----------
prim : Prim
----------------------------------------------------------------------
ComputeUntransformedBound(prim, pathsToSkip, ctmOverrides) -> BBox3d
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the bound of the prim's descendents while excluding the
subtrees rooted at the paths in ``pathsToSkip`` .
Additionally, the parameter ``ctmOverrides`` is used to specify
overrides to the CTM values of certain paths underneath the prim. The
CTM values in the ``ctmOverrides`` map are in the space of the given
prim, ``prim`` .
This leverages any pre-existing, cached bounds, but does not include
the transform (if any) authored on the prim itself.
**IMPORTANT:** while the BBox does not contain the local
transformation, in general it may still contain a non-identity
transformation matrix to put the bounds in the correct space.
Therefore, to obtain the correct axis-aligned bounding box, the client
must call ComputeAlignedRange().
See ComputeWorldBound() for notes on performance and error handling.
Parameters
----------
prim : Prim
pathsToSkip : SdfPathSet
ctmOverrides : TfHashMap[Path, Matrix4d, Path.Hash]
"""
result["BBoxCache"].ComputePointInstanceWorldBounds.func_doc = """ComputePointInstanceWorldBounds(instancer, instanceIdBegin, numIds, result) -> bool
Compute the bound of the given point instances in world space.
The bounds of each instance is computed and then transformed to world
space. The ``result`` pointer must point to ``numIds`` GfBBox3d
instances to be filled.
Parameters
----------
instancer : PointInstancer
instanceIdBegin : int
numIds : int
result : BBox3d
"""
result["BBoxCache"].ComputePointInstanceWorldBound.func_doc = """ComputePointInstanceWorldBound(instancer, instanceId) -> BBox3d
Compute the bound of the given point instance in world space.
Parameters
----------
instancer : PointInstancer
instanceId : int
"""
result["BBoxCache"].ComputePointInstanceRelativeBounds.func_doc = """ComputePointInstanceRelativeBounds(instancer, instanceIdBegin, numIds, relativeToAncestorPrim, result) -> bool
Compute the bounds of the given point instances in the space of an
ancestor prim ``relativeToAncestorPrim`` .
Write the results to ``result`` .
The computed bound excludes the local transform at
``relativeToAncestorPrim`` . The computed bound may be incorrect if
``relativeToAncestorPrim`` is not an ancestor of ``prim`` .
The ``result`` pointer must point to ``numIds`` GfBBox3d instances to
be filled.
Parameters
----------
instancer : PointInstancer
instanceIdBegin : int
numIds : int
relativeToAncestorPrim : Prim
result : BBox3d
"""
result["BBoxCache"].ComputePointInstanceRelativeBound.func_doc = """ComputePointInstanceRelativeBound(instancer, instanceId, relativeToAncestorPrim) -> BBox3d
Compute the bound of the given point instance in the space of an
ancestor prim ``relativeToAncestorPrim`` .
Parameters
----------
instancer : PointInstancer
instanceId : int
relativeToAncestorPrim : Prim
"""
result["BBoxCache"].ComputePointInstanceLocalBounds.func_doc = """ComputePointInstanceLocalBounds(instancer, instanceIdBegin, numIds, result) -> bool
Compute the oriented bounding boxes of the given point instances.
The computed bounds include the transform authored on the instancer
itself, but does not include any ancestor transforms (it does not
include the local-to-world transform).
The ``result`` pointer must point to ``numIds`` GfBBox3d instances to
be filled.
Parameters
----------
instancer : PointInstancer
instanceIdBegin : int
numIds : int
result : BBox3d
"""
result["BBoxCache"].ComputePointInstanceLocalBound.func_doc = """ComputePointInstanceLocalBound(instancer, instanceId) -> BBox3d
Compute the oriented bounding boxes of the given point instances.
Parameters
----------
instancer : PointInstancer
instanceId : int
"""
result["BBoxCache"].ComputePointInstanceUntransformedBounds.func_doc = """ComputePointInstanceUntransformedBounds(instancer, instanceIdBegin, numIds, result) -> bool
Computes the bound of the given point instances, but does not include
the transform (if any) authored on the instancer itself.
**IMPORTANT:** while the BBox does not contain the local
transformation, in general it may still contain a non-identity
transformation matrix to put the bounds in the correct space.
Therefore, to obtain the correct axis-aligned bounding box, the client
must call ComputeAlignedRange().
The ``result`` pointer must point to ``numIds`` GfBBox3d instances to
be filled.
Parameters
----------
instancer : PointInstancer
instanceIdBegin : int
numIds : int
result : BBox3d
"""
result["BBoxCache"].ComputePointInstanceUntransformedBound.func_doc = """ComputePointInstanceUntransformedBound(instancer, instanceId) -> BBox3d
Computes the bound of the given point instances, but does not include
the instancer's transform.
Parameters
----------
instancer : PointInstancer
instanceId : int
"""
result["BBoxCache"].Clear.func_doc = """Clear() -> None
Clears all pre-cached values.
"""
result["BBoxCache"].SetIncludedPurposes.func_doc = """SetIncludedPurposes(includedPurposes) -> None
Indicate the set of ``includedPurposes`` to use when resolving child
bounds.
Each child's purpose must match one of the elements of this set to be
included in the computation; if it does not, child is excluded.
Note the use of *child* in the docs above, purpose is ignored for the
prim for whose bounds are directly queried.
Changing this value **does not invalidate existing caches**.
Parameters
----------
includedPurposes : list[TfToken]
"""
result["BBoxCache"].GetIncludedPurposes.func_doc = """GetIncludedPurposes() -> list[TfToken]
Get the current set of included purposes.
"""
result["BBoxCache"].GetUseExtentsHint.func_doc = """GetUseExtentsHint() -> bool
Returns whether authored extent hints are used to compute bounding
boxes.
"""
result["BBoxCache"].SetTime.func_doc = """SetTime(time) -> None
Use the new ``time`` when computing values and may clear any existing
values cached for the previous time.
Setting ``time`` to the current time is a no-op.
Parameters
----------
time : TimeCode
"""
result["BBoxCache"].GetTime.func_doc = """GetTime() -> TimeCode
Get the current time from which this cache is reading values.
"""
result["BBoxCache"].SetBaseTime.func_doc = """SetBaseTime(baseTime) -> None
Set the base time value for this bbox cache.
This value is used only when computing bboxes for point instancer
instances (see ComputePointInstanceWorldBounds() , for example). See
UsdGeomPointInstancer::ComputeExtentAtTime() for more information. If
unset, the bbox cache uses its time ( GetTime() / SetTime() ) for this
value.
Note that setting the base time does not invalidate any cache entries.
Parameters
----------
baseTime : TimeCode
"""
result["BBoxCache"].GetBaseTime.func_doc = """GetBaseTime() -> TimeCode
Return the base time if set, otherwise GetTime() .
Use HasBaseTime() to observe if a base time has been set.
"""
result["BBoxCache"].ClearBaseTime.func_doc = """ClearBaseTime() -> None
Clear this cache's baseTime if one has been set.
After calling this, the cache will use its time as the baseTime value.
"""
result["BBoxCache"].HasBaseTime.func_doc = """HasBaseTime() -> bool
Return true if this cache has a baseTime that's been explicitly set,
false otherwise.
"""
result["Boundable"].__doc__ = """
Boundable introduces the ability for a prim to persistently cache a
rectilinear, local-space, extent.
Why Extent and not Bounds ?
===========================
Boundable introduces the notion of"extent", which is a cached
computation of a prim's local-space 3D range for its resolved
attributes **at the layer and time in which extent is authored**. We
have found that with composed scene description, attempting to cache
pre-computed bounds at interior prims in a scene graph is very
fragile, given the ease with which one can author a single attribute
in a stronger layer that can invalidate many authored caches - or with
which a re-published, referenced asset can do the same.
Therefore, we limit to precomputing (generally) leaf-prim extent,
which avoids the need to read in large point arrays to compute bounds,
and provides UsdGeomBBoxCache the means to efficiently compute and
(session-only) cache intermediate bounds. You are free to compute and
author intermediate bounds into your scenes, of course, which may work
well if you have sufficient locks on your pipeline to guarantee that
once authored, the geometry and transforms upon which they are based
will remain unchanged, or if accuracy of the bounds is not an ironclad
requisite.
When intermediate bounds are authored on Boundable parents, the child
prims will be pruned from BBox computation; the authored extent is
expected to incorporate all child bounds.
"""
result["Boundable"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomBoundable on UsdPrim ``prim`` .
Equivalent to UsdGeomBoundable::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomBoundable on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomBoundable (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Boundable"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute
Extent is a three dimensional range measuring the geometric extent of
the authored gprim in its own local space (i.e.
its own transform not applied), *without* accounting for any shader-
induced displacement. If **any** extent value has been authored for a
given Boundable, then it should be authored at every timeSample at
which geometry-affecting properties are authored, to ensure correct
evaluation via ComputeExtent() . If **no** extent value has been
authored, then ComputeExtent() will call the Boundable's registered
ComputeExtentFunction(), which may be expensive, which is why we
strongly encourage proper authoring of extent.
ComputeExtent()
Why Extent and not Bounds? . An authored extent on a prim which has
children is expected to include the extent of all children, as they
will be pruned from BBox computation during traversal.
Declaration
``float3[] extent``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Float3Array
"""
result["Boundable"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute
See GetExtentAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Boundable"].ComputeExtent.func_doc = """ComputeExtent(time, extent) -> bool
If an extent is authored on this boundable, it queries the ``extent``
from the extent attribute, otherwise if ComputeExtentFunction is
registered for the boundable's type, it computes the ``extent`` at
``time`` .
Returns true when extent is successfully populated, false otherwise.
ComputeExtentFromPlugins
UsdGeomRegisterComputeExtentFunction
Parameters
----------
time : TimeCode
extent : Vec3fArray
"""
result["Boundable"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Boundable"].Get.func_doc = """**classmethod** Get(stage, path) -> Boundable
Return a UsdGeomBoundable holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomBoundable(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Boundable"].ComputeExtentFromPlugins.func_doc = """**classmethod** ComputeExtentFromPlugins(boundable, time, extent) -> bool
Compute the extent for the Boundable prim ``boundable`` at time
``time`` .
If successful, populates ``extent`` with the result and returns
``true`` , otherwise returns ``false`` .
The extent computation is based on the concrete type of the prim
represented by ``boundable`` . Plugins that provide a Boundable prim
type may implement and register an extent computation for that type
using UsdGeomRegisterComputeExtentFunction. ComputeExtentFromPlugins
will use this function to compute extents for all prims of that type.
If no function has been registered for a prim type, but a function has
been registered for one of its base types, that function will be used
instead.
This function may load plugins in order to access the extent
computation for a prim type.
Parameters
----------
boundable : Boundable
time : TimeCode
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtentFromPlugins(boundable, time, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
boundable : Boundable
time : TimeCode
transform : Matrix4d
extent : Vec3fArray
"""
result["Boundable"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Camera"].__doc__ = """
Transformable camera.
Describes optical properties of a camera via a common set of
attributes that provide control over the camera's frustum as well as
its depth of field. For stereo, the left and right camera are
individual prims tagged through the stereoRole attribute.
There is a corresponding class GfCamera, which can hold the state of a
camera (at a particular time). UsdGeomCamera::GetCamera() and
UsdGeomCamera::SetFromCamera() convert between a USD camera prim and a
GfCamera.
To obtain the camera's location in world space, call the following on
a UsdGeomCamera 'camera':
.. code-block:: text
GfMatrix4d camXform = camera.ComputeLocalToWorldTransform(time);
**Cameras in USD are always"Y up", regardless of the stage's
orientation (i.e. UsdGeomGetStageUpAxis() ).** This means that the
inverse of'camXform'(the VIEW half of the MODELVIEW transform in
OpenGL parlance) will transform the world such that the camera is at
the origin, looking down the -Z axis, with +Y as the up axis, and +X
pointing to the right. This describes a **right handed coordinate
system**.
Units of Measure for Camera Properties
======================================
Despite the familiarity of millimeters for specifying some physical
camera properties, UsdGeomCamera opts for greater consistency with all
other UsdGeom schemas, which measure geometric properties in scene
units, as determined by UsdGeomGetStageMetersPerUnit() . We do make a
concession, however, in that lens and filmback properties are measured
in **tenths of a scene unit** rather than"raw"scene units. This means
that with the fallback value of.01 for *metersPerUnit* - i.e. scene
unit of centimeters - then these"tenth of scene unit"properties are
effectively millimeters.
If one adds a Camera prim to a UsdStage whose scene unit is not
centimeters, the fallback values for filmback properties will be
incorrect (or at the least, unexpected) in an absolute sense; however,
proper imaging through a"default camera"with focusing disabled depends
only on ratios of the other properties, so the camera is still usable.
However, it follows that if even one property is authored in the
correct scene units, then they all must be.
Linear Algebra in UsdGeom For any described attribute *Fallback*
*Value* or *Allowed* *Values* below that are text/tokens, the actual
token is published and defined in UsdGeomTokens. So to set an
attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as
the value.
"""
result["Camera"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomCamera on UsdPrim ``prim`` .
Equivalent to UsdGeomCamera::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomCamera on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomCamera (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Camera"].GetProjectionAttr.func_doc = """GetProjectionAttr() -> Attribute
Declaration
``token projection ="perspective"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Allowed Values
perspective, orthographic
"""
result["Camera"].CreateProjectionAttr.func_doc = """CreateProjectionAttr(defaultValue, writeSparsely) -> Attribute
See GetProjectionAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetHorizontalApertureAttr.func_doc = """GetHorizontalApertureAttr() -> Attribute
Horizontal aperture in tenths of a scene unit; see Units of Measure
for Camera Properties.
Default is the equivalent of the standard 35mm spherical projector
aperture.
Declaration
``float horizontalAperture = 20.955``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Camera"].CreateHorizontalApertureAttr.func_doc = """CreateHorizontalApertureAttr(defaultValue, writeSparsely) -> Attribute
See GetHorizontalApertureAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetVerticalApertureAttr.func_doc = """GetVerticalApertureAttr() -> Attribute
Vertical aperture in tenths of a scene unit; see Units of Measure for
Camera Properties.
Default is the equivalent of the standard 35mm spherical projector
aperture.
Declaration
``float verticalAperture = 15.2908``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Camera"].CreateVerticalApertureAttr.func_doc = """CreateVerticalApertureAttr(defaultValue, writeSparsely) -> Attribute
See GetVerticalApertureAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetHorizontalApertureOffsetAttr.func_doc = """GetHorizontalApertureOffsetAttr() -> Attribute
Horizontal aperture offset in the same units as horizontalAperture.
Defaults to 0.
Declaration
``float horizontalApertureOffset = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Camera"].CreateHorizontalApertureOffsetAttr.func_doc = """CreateHorizontalApertureOffsetAttr(defaultValue, writeSparsely) -> Attribute
See GetHorizontalApertureOffsetAttr() , and also Create vs Get
Property Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetVerticalApertureOffsetAttr.func_doc = """GetVerticalApertureOffsetAttr() -> Attribute
Vertical aperture offset in the same units as verticalAperture.
Defaults to 0.
Declaration
``float verticalApertureOffset = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Camera"].CreateVerticalApertureOffsetAttr.func_doc = """CreateVerticalApertureOffsetAttr(defaultValue, writeSparsely) -> Attribute
See GetVerticalApertureOffsetAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetFocalLengthAttr.func_doc = """GetFocalLengthAttr() -> Attribute
Perspective focal length in tenths of a scene unit; see Units of
Measure for Camera Properties.
Declaration
``float focalLength = 50``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Camera"].CreateFocalLengthAttr.func_doc = """CreateFocalLengthAttr(defaultValue, writeSparsely) -> Attribute
See GetFocalLengthAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetClippingRangeAttr.func_doc = """GetClippingRangeAttr() -> Attribute
Near and far clipping distances in scene units; see Units of Measure
for Camera Properties.
Declaration
``float2 clippingRange = (1, 1000000)``
C++ Type
GfVec2f
Usd Type
SdfValueTypeNames->Float2
"""
result["Camera"].CreateClippingRangeAttr.func_doc = """CreateClippingRangeAttr(defaultValue, writeSparsely) -> Attribute
See GetClippingRangeAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetClippingPlanesAttr.func_doc = """GetClippingPlanesAttr() -> Attribute
Additional, arbitrarily oriented clipping planes.
A vector (a,b,c,d) encodes a clipping plane that cuts off (x,y,z) with
a \\* x + b \\* y + c \\* z + d \\* 1<0 where (x,y,z) are the
coordinates in the camera's space.
Declaration
``float4[] clippingPlanes = []``
C++ Type
VtArray<GfVec4f>
Usd Type
SdfValueTypeNames->Float4Array
"""
result["Camera"].CreateClippingPlanesAttr.func_doc = """CreateClippingPlanesAttr(defaultValue, writeSparsely) -> Attribute
See GetClippingPlanesAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetFStopAttr.func_doc = """GetFStopAttr() -> Attribute
Lens aperture.
Defaults to 0.0, which turns off focusing.
Declaration
``float fStop = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Camera"].CreateFStopAttr.func_doc = """CreateFStopAttr(defaultValue, writeSparsely) -> Attribute
See GetFStopAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetFocusDistanceAttr.func_doc = """GetFocusDistanceAttr() -> Attribute
Distance from the camera to the focus plane in scene units; see Units
of Measure for Camera Properties.
Declaration
``float focusDistance = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Camera"].CreateFocusDistanceAttr.func_doc = """CreateFocusDistanceAttr(defaultValue, writeSparsely) -> Attribute
See GetFocusDistanceAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetStereoRoleAttr.func_doc = """GetStereoRoleAttr() -> Attribute
If different from mono, the camera is intended to be the left or right
camera of a stereo setup.
Declaration
``uniform token stereoRole ="mono"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
mono, left, right
"""
result["Camera"].CreateStereoRoleAttr.func_doc = """CreateStereoRoleAttr(defaultValue, writeSparsely) -> Attribute
See GetStereoRoleAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetShutterOpenAttr.func_doc = """GetShutterOpenAttr() -> Attribute
Frame relative shutter open time in UsdTimeCode units (negative value
indicates that the shutter opens before the current frame time).
Used for motion blur.
Declaration
``double shutter:open = 0``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Camera"].CreateShutterOpenAttr.func_doc = """CreateShutterOpenAttr(defaultValue, writeSparsely) -> Attribute
See GetShutterOpenAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetShutterCloseAttr.func_doc = """GetShutterCloseAttr() -> Attribute
Frame relative shutter close time, analogous comments from
shutter:open apply.
A value greater or equal to shutter:open should be authored, otherwise
there is no exposure and a renderer should produce a black image.
Declaration
``double shutter:close = 0``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Camera"].CreateShutterCloseAttr.func_doc = """CreateShutterCloseAttr(defaultValue, writeSparsely) -> Attribute
See GetShutterCloseAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetExposureAttr.func_doc = """GetExposureAttr() -> Attribute
Exposure adjustment, as a log base-2 value.
The default of 0.0 has no effect. A value of 1.0 will double the
image-plane intensities in a rendered image; a value of -1.0 will
halve them.
Declaration
``float exposure = 0``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["Camera"].CreateExposureAttr.func_doc = """CreateExposureAttr(defaultValue, writeSparsely) -> Attribute
See GetExposureAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Camera"].GetCamera.func_doc = """GetCamera(time) -> Camera
Creates a GfCamera object from the attribute values at ``time`` .
Parameters
----------
time : TimeCode
"""
result["Camera"].SetFromCamera.func_doc = """SetFromCamera(camera, time) -> None
Write attribute values from ``camera`` for ``time`` .
These attributes will be updated:
- projection
- horizontalAperture
- horizontalApertureOffset
- verticalAperture
- verticalApertureOffset
- focalLength
- clippingRange
- clippingPlanes
- fStop
- focalDistance
- xformOpOrder and xformOp:transform
This will clear any existing xformOpOrder and replace it with a single
xformOp:transform entry. The xformOp:transform property is created or
updated here to match the transform on ``camera`` . This operation
will fail if there are stronger xform op opinions in the composed
layer stack that are stronger than that of the current edit target.
Parameters
----------
camera : Camera
time : TimeCode
"""
result["Camera"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Camera"].Get.func_doc = """**classmethod** Get(stage, path) -> Camera
Return a UsdGeomCamera holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomCamera(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Camera"].Define.func_doc = """**classmethod** Define(stage, path) -> Camera
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Camera"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Capsule"].__doc__ = """
Defines a primitive capsule, i.e. a cylinder capped by two half
spheres, centered at the origin, whose spine is along the specified
*axis*.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["Capsule"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomCapsule on UsdPrim ``prim`` .
Equivalent to UsdGeomCapsule::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomCapsule on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomCapsule (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Capsule"].GetHeightAttr.func_doc = """GetHeightAttr() -> Attribute
The size of the capsule's spine along the specified *axis* excluding
the size of the two half spheres, i.e.
the size of the cylinder portion of the capsule. If you author
*height* you must also author *extent*.
GetExtentAttr()
Declaration
``double height = 1``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Capsule"].CreateHeightAttr.func_doc = """CreateHeightAttr(defaultValue, writeSparsely) -> Attribute
See GetHeightAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Capsule"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute
The radius of the capsule.
If you author *radius* you must also author *extent*.
GetExtentAttr()
Declaration
``double radius = 0.5``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Capsule"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute
See GetRadiusAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Capsule"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute
The axis along which the spine of the capsule is aligned.
Declaration
``uniform token axis ="Z"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
X, Y, Z
"""
result["Capsule"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute
See GetAxisAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Capsule"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute
Extent is re-defined on Capsule only to provide a fallback value.
UsdGeomGprim::GetExtentAttr() .
Declaration
``float3[] extent = [(-0.5, -0.5, -1), (0.5, 0.5, 1)]``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Float3Array
"""
result["Capsule"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute
See GetExtentAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Capsule"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Capsule"].Get.func_doc = """**classmethod** Get(stage, path) -> Capsule
Return a UsdGeomCapsule holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomCapsule(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Capsule"].Define.func_doc = """**classmethod** Define(stage, path) -> Capsule
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Capsule"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(height, radius, axis, extent) -> bool
Compute the extent for the capsule defined by the height, radius, and
axis.
true upon success, false if unable to calculate extent. On success,
extent will contain an approximate axis-aligned bounding box of the
capsule defined by the height, radius, and axis.
This function is to provide easy authoring of extent for usd authoring
tools, hence it is static and acts outside a specific prim (as in
attribute based methods).
Parameters
----------
height : float
radius : float
axis : str
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtent(height, radius, axis, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
height : float
radius : float
axis : str
transform : Matrix4d
extent : Vec3fArray
"""
result["Capsule"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Cone"].__doc__ = """
Defines a primitive cone, centered at the origin, whose spine is along
the specified *axis*, with the apex of the cone pointing in the
direction of the positive axis.
The fallback values for Cube, Sphere, Cone, and Cylinder are set so
that they all pack into the same volume/bounds.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["Cone"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomCone on UsdPrim ``prim`` .
Equivalent to UsdGeomCone::Get (prim.GetStage(), prim.GetPath()) for a
*valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomCone on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomCone (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Cone"].GetHeightAttr.func_doc = """GetHeightAttr() -> Attribute
The size of the cone's spine along the specified *axis*.
If you author *height* you must also author *extent*.
GetExtentAttr()
Declaration
``double height = 2``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Cone"].CreateHeightAttr.func_doc = """CreateHeightAttr(defaultValue, writeSparsely) -> Attribute
See GetHeightAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cone"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute
The radius of the cone.
If you author *radius* you must also author *extent*.
GetExtentAttr()
Declaration
``double radius = 1``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Cone"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute
See GetRadiusAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cone"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute
The axis along which the spine of the cone is aligned.
Declaration
``uniform token axis ="Z"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
X, Y, Z
"""
result["Cone"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute
See GetAxisAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cone"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute
Extent is re-defined on Cone only to provide a fallback value.
UsdGeomGprim::GetExtentAttr() .
Declaration
``float3[] extent = [(-1, -1, -1), (1, 1, 1)]``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Float3Array
"""
result["Cone"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute
See GetExtentAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cone"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Cone"].Get.func_doc = """**classmethod** Get(stage, path) -> Cone
Return a UsdGeomCone holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomCone(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Cone"].Define.func_doc = """**classmethod** Define(stage, path) -> Cone
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Cone"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(height, radius, axis, extent) -> bool
Compute the extent for the cone defined by the height, radius, and
axis.
true upon success, false if unable to calculate extent. On success,
extent will contain an approximate axis-aligned bounding box of the
cone defined by the height, radius, and axis.
This function is to provide easy authoring of extent for usd authoring
tools, hence it is static and acts outside a specific prim (as in
attribute based methods).
Parameters
----------
height : float
radius : float
axis : str
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtent(height, radius, axis, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
height : float
radius : float
axis : str
transform : Matrix4d
extent : Vec3fArray
"""
result["Cone"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["ConstraintTarget"].__doc__ = """
Schema wrapper for UsdAttribute for authoring and introspecting
attributes that are constraint targets.
Constraint targets correspond roughly to what some DCC's call
locators. They are coordinate frames, represented as (animated or
static) GfMatrix4d values. We represent them as attributes in USD
rather than transformable prims because generally we require no other
coordinated information about a constraint target other than its name
and its matrix value, and because attributes are more concise than
prims.
Because consumer clients often care only about the identity and value
of constraint targets and may be able to usefully consume them without
caring about the actual geometry with which they may logically
correspond, UsdGeom aggregates all constraint targets onto a model's
root prim, assuming that an exporter will use property namespacing
within the constraint target attribute's name to indicate a path to a
prim within the model with which the constraint target may correspond.
To facilitate instancing, and also position-tweaking of baked assets,
we stipulate that constraint target values always be recorded in
**model-relative transformation space**. In other words, to get the
world-space value of a constraint target, transform it by the local-
to-world transformation of the prim on which it is recorded.
ComputeInWorldSpace() will perform this calculation.
"""
result["ConstraintTarget"].GetAttr.func_doc = """GetAttr() -> Attribute
Explicit UsdAttribute extractor.
"""
result["ConstraintTarget"].IsDefined.func_doc = """IsDefined() -> bool
Return true if the wrapped UsdAttribute::IsDefined() , and in addition
the attribute is identified as a ConstraintTarget.
"""
result["ConstraintTarget"].Get.func_doc = """Get(value, time) -> bool
Get the attribute value of the ConstraintTarget at ``time`` .
Parameters
----------
value : Matrix4d
time : TimeCode
"""
result["ConstraintTarget"].Set.func_doc = """Set(value, time) -> bool
Set the attribute value of the ConstraintTarget at ``time`` .
Parameters
----------
value : Matrix4d
time : TimeCode
"""
result["ConstraintTarget"].GetIdentifier.func_doc = """GetIdentifier() -> str
Get the stored identifier unique to the enclosing model's namespace
for this constraint target.
SetIdentifier()
"""
result["ConstraintTarget"].SetIdentifier.func_doc = """SetIdentifier(identifier) -> None
Explicitly sets the stored identifier to the given string.
Clients are responsible for ensuring the uniqueness of this identifier
within the enclosing model's namespace.
Parameters
----------
identifier : str
"""
result["ConstraintTarget"].ComputeInWorldSpace.func_doc = """ComputeInWorldSpace(time, xfCache) -> Matrix4d
Computes the value of the constraint target in world space.
If a valid UsdGeomXformCache is provided in the argument ``xfCache`` ,
it is used to evaluate the CTM of the model to which the constraint
target belongs.
To get the constraint value in model-space (or local space), simply
use UsdGeomConstraintTarget::Get() , since the authored values must
already be in model-space.
Parameters
----------
time : TimeCode
xfCache : XformCache
"""
result["ConstraintTarget"].GetConstraintAttrName.func_doc = """**classmethod** GetConstraintAttrName(constraintName) -> str
Returns the fully namespaced constraint attribute name, given the
constraint name.
Parameters
----------
constraintName : str
"""
result["ConstraintTarget"].__init__.func_doc = """__init__()
----------------------------------------------------------------------
__init__(attr)
Speculative constructor that will produce a valid
UsdGeomConstraintTarget when ``attr`` already represents an attribute
that is a UsdGeomConstraintTarget, and produces an *invalid*
UsdGeomConstraintTarget otherwise (i.e.
UsdGeomConstraintTarget_explicit_bool will return false).
Calling ``UsdGeomConstraintTarget::IsValid(attr)`` will return the
same truth value as the object returned by this constructor, but if
you plan to subsequently use the ConstraintTarget anyways, just
construct the object and bool-evaluate it before proceeding.
Parameters
----------
attr : Attribute
"""
result["ConstraintTarget"].IsValid.func_doc = """**classmethod** IsValid(attr) -> bool
Test whether a given UsdAttribute represents valid ConstraintTarget,
which implies that creating a UsdGeomConstraintTarget from the
attribute will succeed.
Success implies that ``attr.IsDefined()`` is true.
Parameters
----------
attr : Attribute
"""
result["Cube"].__doc__ = """
Defines a primitive rectilinear cube centered at the origin.
The fallback values for Cube, Sphere, Cone, and Cylinder are set so
that they all pack into the same volume/bounds.
"""
result["Cube"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomCube on UsdPrim ``prim`` .
Equivalent to UsdGeomCube::Get (prim.GetStage(), prim.GetPath()) for a
*valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomCube on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomCube (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Cube"].GetSizeAttr.func_doc = """GetSizeAttr() -> Attribute
Indicates the length of each edge of the cube.
If you author *size* you must also author *extent*.
GetExtentAttr()
Declaration
``double size = 2``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Cube"].CreateSizeAttr.func_doc = """CreateSizeAttr(defaultValue, writeSparsely) -> Attribute
See GetSizeAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cube"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute
Extent is re-defined on Cube only to provide a fallback value.
UsdGeomGprim::GetExtentAttr() .
Declaration
``float3[] extent = [(-1, -1, -1), (1, 1, 1)]``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Float3Array
"""
result["Cube"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute
See GetExtentAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cube"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Cube"].Get.func_doc = """**classmethod** Get(stage, path) -> Cube
Return a UsdGeomCube holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomCube(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Cube"].Define.func_doc = """**classmethod** Define(stage, path) -> Cube
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Cube"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(size, extent) -> bool
Compute the extent for the cube defined by the size of each dimension.
true upon success, false if unable to calculate extent. On success,
extent will contain an approximate axis-aligned bounding box of the
cube defined by the size of each dimension.
This function is to provide easy authoring of extent for usd authoring
tools, hence it is static and acts outside a specific prim (as in
attribute based methods).
Parameters
----------
size : float
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtent(size, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
size : float
transform : Matrix4d
extent : Vec3fArray
"""
result["Cube"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Curves"].__doc__ = """
Base class for UsdGeomBasisCurves, UsdGeomNurbsCurves, and
UsdGeomHermiteCurves. The BasisCurves schema is designed to be
analagous to offline renderers'notion of batched curves (such as the
classical RIB definition via Basis and Curves statements), while the
NurbsCurve schema is designed to be analgous to the NURBS curves found
in packages like Maya and Houdini while retaining their consistency
with the RenderMan specification for NURBS Patches. HermiteCurves are
useful for the interchange of animation guides and paths.
It is safe to use the length of the curve vertex count to derive the
number of curves and the number and layout of curve vertices, but this
schema should NOT be used to derive the number of curve points. While
vertex indices are implicit in all shipped descendent types of this
schema, one should not assume that all internal or future shipped
schemas will follow this pattern. Be sure to key any indexing behavior
off the concrete type, not this abstract type.
"""
result["Curves"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomCurves on UsdPrim ``prim`` .
Equivalent to UsdGeomCurves::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomCurves on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomCurves (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Curves"].GetCurveVertexCountsAttr.func_doc = """GetCurveVertexCountsAttr() -> Attribute
Curves-derived primitives can represent multiple distinct, potentially
disconnected curves.
The length of'curveVertexCounts'gives the number of such curves, and
each element describes the number of vertices in the corresponding
curve
Declaration
``int[] curveVertexCounts``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["Curves"].CreateCurveVertexCountsAttr.func_doc = """CreateCurveVertexCountsAttr(defaultValue, writeSparsely) -> Attribute
See GetCurveVertexCountsAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Curves"].GetWidthsAttr.func_doc = """GetWidthsAttr() -> Attribute
Provides width specification for the curves, whose application will
depend on whether the curve is oriented (normals are defined for it),
in which case widths are"ribbon width", or unoriented, in which case
widths are cylinder width.
'widths'is not a generic Primvar, but the number of elements in this
attribute will be determined by its'interpolation'. See
SetWidthsInterpolation() . If'widths'and'primvars:widths'are both
specified, the latter has precedence.
Declaration
``float[] widths``
C++ Type
VtArray<float>
Usd Type
SdfValueTypeNames->FloatArray
"""
result["Curves"].CreateWidthsAttr.func_doc = """CreateWidthsAttr(defaultValue, writeSparsely) -> Attribute
See GetWidthsAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Curves"].GetWidthsInterpolation.func_doc = """GetWidthsInterpolation() -> str
Get the interpolation for the *widths* attribute.
Although'widths'is not classified as a generic UsdGeomPrimvar (and
will not be included in the results of
UsdGeomPrimvarsAPI::GetPrimvars() ) it does require an interpolation
specification. The fallback interpolation, if left unspecified, is
UsdGeomTokens->vertex, which means a width value is specified at the
end of each curve segment.
"""
result["Curves"].SetWidthsInterpolation.func_doc = """SetWidthsInterpolation(interpolation) -> bool
Set the interpolation for the *widths* attribute.
true upon success, false if ``interpolation`` is not a legal value as
defined by UsdPrimvar::IsValidInterpolation(), or if there was a
problem setting the value. No attempt is made to validate that the
widths attr's value contains the right number of elements to match its
interpolation to its prim's topology.
GetWidthsInterpolation()
Parameters
----------
interpolation : str
"""
result["Curves"].GetCurveCount.func_doc = """GetCurveCount(timeCode) -> int
Returns the number of curves as defined by the size of the
*curveVertexCounts* array at *timeCode*.
For most code, this check will be performant. When using file formats
where the cost of attribute reading is high and the time sampled array
will be read into memory later, it may be better to explicitly read
the value once and check the size of the array directly.
GetCurveVertexCountsAttr()
Parameters
----------
timeCode : TimeCode
"""
result["Curves"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Curves"].Get.func_doc = """**classmethod** Get(stage, path) -> Curves
Return a UsdGeomCurves holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomCurves(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Curves"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(points, widths, extent) -> bool
Compute the extent for the curves defined by points and widths.
true upon success, false if unable to calculate extent. On success,
extent will contain an approximate axis-aligned bounding box of the
curve defined by points with the given widths.
This function is to provide easy authoring of extent for usd authoring
tools, hence it is static and acts outside a specific prim (as in
attribute based methods).
Parameters
----------
points : Vec3fArray
widths : FloatArray
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtent(points, widths, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
points : Vec3fArray
widths : FloatArray
transform : Matrix4d
extent : Vec3fArray
"""
result["Curves"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Cylinder"].__doc__ = """
Defines a primitive cylinder with closed ends, centered at the origin,
whose spine is along the specified *axis*.
The fallback values for Cube, Sphere, Cone, and Cylinder are set so
that they all pack into the same volume/bounds.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["Cylinder"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomCylinder on UsdPrim ``prim`` .
Equivalent to UsdGeomCylinder::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomCylinder on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomCylinder (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Cylinder"].GetHeightAttr.func_doc = """GetHeightAttr() -> Attribute
The size of the cylinder's spine along the specified *axis*.
If you author *height* you must also author *extent*.
GetExtentAttr()
Declaration
``double height = 2``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Cylinder"].CreateHeightAttr.func_doc = """CreateHeightAttr(defaultValue, writeSparsely) -> Attribute
See GetHeightAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cylinder"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute
The radius of the cylinder.
If you author *radius* you must also author *extent*.
GetExtentAttr()
Declaration
``double radius = 1``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Cylinder"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute
See GetRadiusAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cylinder"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute
The axis along which the spine of the cylinder is aligned.
Declaration
``uniform token axis ="Z"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
X, Y, Z
"""
result["Cylinder"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute
See GetAxisAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cylinder"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute
Extent is re-defined on Cylinder only to provide a fallback value.
UsdGeomGprim::GetExtentAttr() .
Declaration
``float3[] extent = [(-1, -1, -1), (1, 1, 1)]``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Float3Array
"""
result["Cylinder"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute
See GetExtentAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Cylinder"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Cylinder"].Get.func_doc = """**classmethod** Get(stage, path) -> Cylinder
Return a UsdGeomCylinder holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomCylinder(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Cylinder"].Define.func_doc = """**classmethod** Define(stage, path) -> Cylinder
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Cylinder"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(height, radius, axis, extent) -> bool
Compute the extent for the cylinder defined by the height, radius, and
axis.
true upon success, false if unable to calculate extent. On success,
extent will contain an approximate axis-aligned bounding box of the
cylinder defined by the height, radius, and axis.
This function is to provide easy authoring of extent for usd authoring
tools, hence it is static and acts outside a specific prim (as in
attribute based methods).
Parameters
----------
height : float
radius : float
axis : str
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtent(height, radius, axis, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
height : float
radius : float
axis : str
transform : Matrix4d
extent : Vec3fArray
"""
result["Cylinder"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Gprim"].__doc__ = """
Base class for all geometric primitives.
Gprim encodes basic graphical properties such as *doubleSided* and
*orientation*, and provides primvars for"display
color"and"displayopacity"that travel with geometry to be used as
shader overrides.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["Gprim"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomGprim on UsdPrim ``prim`` .
Equivalent to UsdGeomGprim::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomGprim on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomGprim (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Gprim"].GetDisplayColorAttr.func_doc = """GetDisplayColorAttr() -> Attribute
It is useful to have an"official"colorSet that can be used as a
display or modeling color, even in the absence of any specified shader
for a gprim.
DisplayColor serves this role; because it is a UsdGeomPrimvar, it can
also be used as a gprim override for any shader that consumes a
*displayColor* parameter.
Declaration
``color3f[] primvars:displayColor``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Color3fArray
"""
result["Gprim"].CreateDisplayColorAttr.func_doc = """CreateDisplayColorAttr(defaultValue, writeSparsely) -> Attribute
See GetDisplayColorAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Gprim"].GetDisplayOpacityAttr.func_doc = """GetDisplayOpacityAttr() -> Attribute
Companion to *displayColor* that specifies opacity, broken out as an
independent attribute rather than an rgba color, both so that each can
be independently overridden, and because shaders rarely consume rgba
parameters.
Declaration
``float[] primvars:displayOpacity``
C++ Type
VtArray<float>
Usd Type
SdfValueTypeNames->FloatArray
"""
result["Gprim"].CreateDisplayOpacityAttr.func_doc = """CreateDisplayOpacityAttr(defaultValue, writeSparsely) -> Attribute
See GetDisplayOpacityAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Gprim"].GetDoubleSidedAttr.func_doc = """GetDoubleSidedAttr() -> Attribute
Although some renderers treat all parametric or polygonal surfaces as
if they were effectively laminae with outward-facing normals on both
sides, some renderers derive significant optimizations by considering
these surfaces to have only a single outward side, typically
determined by control-point winding order and/or *orientation*.
By doing so they can perform"backface culling"to avoid drawing the
many polygons of most closed surfaces that face away from the viewer.
However, it is often advantageous to model thin objects such as paper
and cloth as single, open surfaces that must be viewable from both
sides, always. Setting a gprim's *doubleSided* attribute to ``true``
instructs all renderers to disable optimizations such as backface
culling for the gprim, and attempt (not all renderers are able to do
so, but the USD reference GL renderer always will) to provide forward-
facing normals on each side of the surface for lighting calculations.
Declaration
``uniform bool doubleSided = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
Variability
SdfVariabilityUniform
"""
result["Gprim"].CreateDoubleSidedAttr.func_doc = """CreateDoubleSidedAttr(defaultValue, writeSparsely) -> Attribute
See GetDoubleSidedAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Gprim"].GetOrientationAttr.func_doc = """GetOrientationAttr() -> Attribute
Orientation specifies whether the gprim's surface normal should be
computed using the right hand rule, or the left hand rule.
Please see Coordinate System, Winding Order, Orientation, and Surface
Normals for a deeper explanation and generalization of orientation to
composed scenes with transformation hierarchies.
Declaration
``uniform token orientation ="rightHanded"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
rightHanded, leftHanded
"""
result["Gprim"].CreateOrientationAttr.func_doc = """CreateOrientationAttr(defaultValue, writeSparsely) -> Attribute
See GetOrientationAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Gprim"].GetDisplayColorPrimvar.func_doc = """GetDisplayColorPrimvar() -> Primvar
Convenience function to get the displayColor Attribute as a Primvar.
GetDisplayColorAttr() , CreateDisplayColorPrimvar()
"""
result["Gprim"].CreateDisplayColorPrimvar.func_doc = """CreateDisplayColorPrimvar(interpolation, elementSize) -> Primvar
Convenience function to create the displayColor primvar, optionally
specifying interpolation and elementSize.
CreateDisplayColorAttr() , GetDisplayColorPrimvar()
Parameters
----------
interpolation : str
elementSize : int
"""
result["Gprim"].GetDisplayOpacityPrimvar.func_doc = """GetDisplayOpacityPrimvar() -> Primvar
Convenience function to get the displayOpacity Attribute as a Primvar.
GetDisplayOpacityAttr() , CreateDisplayOpacityPrimvar()
"""
result["Gprim"].CreateDisplayOpacityPrimvar.func_doc = """CreateDisplayOpacityPrimvar(interpolation, elementSize) -> Primvar
Convenience function to create the displayOpacity primvar, optionally
specifying interpolation and elementSize.
CreateDisplayOpacityAttr() , GetDisplayOpacityPrimvar()
Parameters
----------
interpolation : str
elementSize : int
"""
result["Gprim"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Gprim"].Get.func_doc = """**classmethod** Get(stage, path) -> Gprim
Return a UsdGeomGprim holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomGprim(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Gprim"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["HermiteCurves"].__doc__ = """
This schema specifies a cubic hermite interpolated curve batch as
sometimes used for defining guides for animation. While hermite curves
can be useful because they interpolate through their control points,
they are not well supported by high-end renderers for imaging.
Therefore, while we include this schema for interchange, we strongly
recommend the use of UsdGeomBasisCurves as the representation of
curves intended to be rendered (ie. hair or grass). Hermite curves can
be converted to a Bezier representation (though not from Bezier back
to Hermite in general).
Point Interpolation
===================
The initial cubic curve segment is defined by the first two points and
first two tangents. Additional segments are defined by additional
point / tangent pairs. The number of segments for each non-batched
hermite curve would be len(curve.points) - 1. The total number of
segments for the batched UsdGeomHermiteCurves representation is
len(points) - len(curveVertexCounts).
Primvar, Width, and Normal Interpolation
========================================
Primvar interpolation is not well specified for this type as it is not
intended as a rendering representation. We suggest that per point
primvars would be linearly interpolated across each segment and should
be tagged as'varying'.
It is not immediately clear how to specify cubic
or'vertex'interpolation for this type, as we lack a specification for
primvar tangents. This also means that width and normal interpolation
should be restricted to varying (linear), uniform (per curve element),
or constant (per prim).
"""
result["HermiteCurves"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomHermiteCurves on UsdPrim ``prim`` .
Equivalent to UsdGeomHermiteCurves::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomHermiteCurves on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomHermiteCurves (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["HermiteCurves"].GetTangentsAttr.func_doc = """GetTangentsAttr() -> Attribute
Defines the outgoing trajectory tangent for each point.
Tangents should be the same size as the points attribute.
Declaration
``vector3f[] tangents = []``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Vector3fArray
"""
result["HermiteCurves"].CreateTangentsAttr.func_doc = """CreateTangentsAttr(defaultValue, writeSparsely) -> Attribute
See GetTangentsAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["HermiteCurves"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["HermiteCurves"].Get.func_doc = """**classmethod** Get(stage, path) -> HermiteCurves
Return a UsdGeomHermiteCurves holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomHermiteCurves(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["HermiteCurves"].Define.func_doc = """**classmethod** Define(stage, path) -> HermiteCurves
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["HermiteCurves"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Imageable"].__doc__ = """
Base class for all prims that may require rendering or visualization
of some sort. The primary attributes of Imageable are *visibility* and
*purpose*, which each provide instructions for what geometry should be
included for processing by rendering and other computations.
Deprecated
Imageable also provides API for accessing primvars, which has been
moved to the UsdGeomPrimvarsAPI schema, because primvars can now be
applied on non-Imageable prim types. This API is planned to be
removed, UsdGeomPrimvarsAPI should be used directly instead.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["Imageable"].MakeVisible.func_doc = """MakeVisible(time) -> None
Make the imageable visible if it is invisible at the given time.
Since visibility is pruning, this may need to override some ancestor's
visibility and all-but-one of the ancestor's children's visibility,
for all the ancestors of this prim up to the highest ancestor that is
explicitly invisible, to preserve the visibility state.
If MakeVisible() (or MakeInvisible() ) is going to be applied to all
the prims on a stage, ancestors must be processed prior to descendants
to get the correct behavior.
When visibility is animated, this only works when it is invoked
sequentially at increasing time samples. If visibility is already
authored and animated in the scene, calling MakeVisible() at an
arbitrary (in-between) frame isn't guaranteed to work.
This will only work properly if all ancestor prims of the imageable
are **defined**, as the imageable schema is only valid on defined
prims.
Be sure to set the edit target to the layer containing the strongest
visibility opinion or to a stronger layer.
MakeInvisible()
ComputeVisibility()
Parameters
----------
time : TimeCode
"""
result["Imageable"].MakeInvisible.func_doc = """MakeInvisible(time) -> None
Makes the imageable invisible if it is visible at the given time.
When visibility is animated, this only works when it is invoked
sequentially at increasing time samples. If visibility is already
authored and animated in the scene, calling MakeVisible() at an
arbitrary (in-between) frame isn't guaranteed to work.
Be sure to set the edit target to the layer containing the strongest
visibility opinion or to a stronger layer.
MakeVisible()
ComputeVisibility()
Parameters
----------
time : TimeCode
"""
result["Imageable"].ComputeVisibility.func_doc = """ComputeVisibility(time) -> str
Calculate the effective visibility of this prim, as defined by its
most ancestral authored"invisible"opinion, if any.
A prim is considered visible at the current ``time`` if none of its
Imageable ancestors express an authored"invisible"opinion, which is
what leads to the"simple pruning"behavior described in
GetVisibilityAttr() .
This function should be considered a reference implementation for
correctness. **If called on each prim in the context of a traversal we
will perform massive overcomputation, because sibling prims share sub-
problems in the query that can be efficiently cached, but are not
(cannot be) by this simple implementation.** If you have control of
your traversal, it will be far more efficient to manage visibility on
a stack as you traverse.
GetVisibilityAttr()
Parameters
----------
time : TimeCode
"""
result["Imageable"].GetPurposeVisibilityAttr.func_doc = """GetPurposeVisibilityAttr(purpose) -> Attribute
Return the attribute that is used for expressing visibility opinions
for the given ``purpose`` .
For"default"purpose, return the overall *visibility* attribute.
For"guide","proxy", or"render"purpose, return *guideVisibility*,
*proxyVisibility*, or *renderVisibility* if UsdGeomVisibilityAPI is
applied to the prim. If UsdGeomvVisibiltyAPI is not applied, an empty
attribute is returned for purposes other than default.
UsdGeomVisibilityAPI::Apply
UsdGeomVisibilityAPI::GetPurposeVisibilityAttr
Parameters
----------
purpose : str
"""
result["Imageable"].ComputeEffectiveVisibility.func_doc = """ComputeEffectiveVisibility(purpose, time) -> str
Calculate the effective purpose visibility of this prim for the given
``purpose`` , taking into account opinions for the corresponding
purpose attribute, along with overall visibility opinions.
If ComputeVisibility() returns"invisible", then
ComputeEffectiveVisibility() is"invisible"for all purpose values.
Otherwise, ComputeEffectiveVisibility() returns the value of the
nearest ancestral authored opinion for the corresponding purpose
visibility attribute, as retured by GetPurposeVisibilityAttr(purpose).
Note that the value returned here can be"invisible"(indicating the
prim is invisible for the given purpose),"visible"(indicating that
it's visible), or"inherited"(indicating that the purpose visibility is
context-dependent and the fallback behavior must be determined by the
caller.
This function should be considered a reference implementation for
correctness. **If called on each prim in the context of a traversal we
will perform massive overcomputation, because sibling prims share sub-
problems in the query that can be efficiently cached, but are not
(cannot be) by this simple implementation.** If you have control of
your traversal, it will be far more efficient to manage visibility on
a stack as you traverse.
UsdGeomVisibilityAPI
GetPurposeVisibilityAttr()
ComputeVisibility()
Parameters
----------
purpose : str
time : TimeCode
"""
result["Imageable"].ComputePurposeInfo.func_doc = """ComputePurposeInfo() -> PurposeInfo
Calculate the effective purpose information about this prim which
includes final computed purpose value of the prim as well as whether
the purpose value should be inherited by namespace children without
their own purpose opinions.
This function should be considered a reference implementation for
correctness. **If called on each prim in the context of a traversal we
will perform massive overcomputation, because sibling prims share sub-
problems in the query that can be efficiently cached, but are not
(cannot be) by this simple implementation.** If you have control of
your traversal, it will be far more efficient to manage purpose, along
with visibility, on a stack as you traverse.
GetPurposeAttr() , Imageable Purpose
----------------------------------------------------------------------
ComputePurposeInfo(parentPurposeInfo) -> PurposeInfo
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Calculates the effective purpose information about this prim, given
the computed purpose information of its parent prim.
This can be much more efficient than using CommputePurposeInfo() when
PurposeInfo values are properly computed and cached for a hierarchy of
prims using this function.
GetPurposeAttr() , Imageable Purpose
Parameters
----------
parentPurposeInfo : PurposeInfo
"""
result["Imageable"].ComputePurpose.func_doc = """ComputePurpose() -> str
Calculate the effective purpose information about this prim.
This is equivalent to extracting the purpose from the value returned
by ComputePurposeInfo() .
This function should be considered a reference implementation for
correctness. **If called on each prim in the context of a traversal we
will perform massive overcomputation, because sibling prims share sub-
problems in the query that can be efficiently cached, but are not
(cannot be) by this simple implementation.** If you have control of
your traversal, it will be far more efficient to manage purpose, along
with visibility, on a stack as you traverse.
GetPurposeAttr() , Imageable Purpose
"""
result["Imageable"].SetProxyPrim.func_doc = """SetProxyPrim(proxy) -> bool
Convenience function for authoring the *renderProxy* rel on this prim
to target the given ``proxy`` prim.
To facilitate authoring on sparse or unloaded stages, we do not
perform any validation of this prim's purpose or the type or purpose
of the specified prim.
ComputeProxyPrim() , GetProxyPrimRel()
Parameters
----------
proxy : Prim
----------------------------------------------------------------------
SetProxyPrim(proxy) -> bool
Parameters
----------
proxy : SchemaBase
"""
result["Imageable"].ComputeWorldBound.func_doc = """ComputeWorldBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d
Compute the bound of this prim in world space, at the specified
``time`` , and for the specified purposes.
The bound of the prim is computed, including the transform (if any)
authored on the node itself, and then transformed to world space.
It is an error to not specify any purposes, which will result in the
return of an empty box.
**If you need to compute bounds for multiple prims on a stage, it will
be much, much more efficient to instantiate a UsdGeomBBoxCache and
query it directly; doing so will reuse sub-computations shared by the
prims.**
Parameters
----------
time : TimeCode
purpose1 : str
purpose2 : str
purpose3 : str
purpose4 : str
"""
result["Imageable"].ComputeLocalBound.func_doc = """ComputeLocalBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d
Compute the bound of this prim in local space, at the specified
``time`` , and for the specified purposes.
The bound of the prim is computed, including the transform (if any)
authored on the node itself.
It is an error to not specify any purposes, which will result in the
return of an empty box.
**If you need to compute bounds for multiple prims on a stage, it will
be much, much more efficient to instantiate a UsdGeomBBoxCache and
query it directly; doing so will reuse sub-computations shared by the
prims.**
Parameters
----------
time : TimeCode
purpose1 : str
purpose2 : str
purpose3 : str
purpose4 : str
"""
result["Imageable"].ComputeUntransformedBound.func_doc = """ComputeUntransformedBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d
Compute the untransformed bound of this prim, at the specified
``time`` , and for the specified purposes.
The bound of the prim is computed in its object space, ignoring any
transforms authored on or above the prim.
It is an error to not specify any purposes, which will result in the
return of an empty box.
**If you need to compute bounds for multiple prims on a stage, it will
be much, much more efficient to instantiate a UsdGeomBBoxCache and
query it directly; doing so will reuse sub-computations shared by the
prims.**
Parameters
----------
time : TimeCode
purpose1 : str
purpose2 : str
purpose3 : str
purpose4 : str
"""
result["Imageable"].ComputeLocalToWorldTransform.func_doc = """ComputeLocalToWorldTransform(time) -> Matrix4d
Compute the transformation matrix for this prim at the given time,
including the transform authored on the Prim itself, if present.
**If you need to compute the transform for multiple prims on a stage,
it will be much, much more efficient to instantiate a
UsdGeomXformCache and query it directly; doing so will reuse sub-
computations shared by the prims.**
Parameters
----------
time : TimeCode
"""
result["Imageable"].ComputeParentToWorldTransform.func_doc = """ComputeParentToWorldTransform(time) -> Matrix4d
Compute the transformation matrix for this prim at the given time,
*NOT* including the transform authored on the prim itself.
**If you need to compute the transform for multiple prims on a stage,
it will be much, much more efficient to instantiate a
UsdGeomXformCache and query it directly; doing so will reuse sub-
computations shared by the prims.**
Parameters
----------
time : TimeCode
"""
result["Imageable"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomImageable on UsdPrim ``prim`` .
Equivalent to UsdGeomImageable::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomImageable on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomImageable (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Imageable"].GetVisibilityAttr.func_doc = """GetVisibilityAttr() -> Attribute
Visibility is meant to be the simplest form of"pruning"visibility that
is supported by most DCC apps.
Visibility is animatable, allowing a sub-tree of geometry to be
present for some segment of a shot, and absent from others; unlike the
action of deactivating geometry prims, invisible geometry is still
available for inspection, for positioning, for defining volumes, etc.
Declaration
``token visibility ="inherited"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Allowed Values
inherited, invisible
"""
result["Imageable"].CreateVisibilityAttr.func_doc = """CreateVisibilityAttr(defaultValue, writeSparsely) -> Attribute
See GetVisibilityAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Imageable"].GetPurposeAttr.func_doc = """GetPurposeAttr() -> Attribute
Purpose is a classification of geometry into categories that can each
be independently included or excluded from traversals of prims on a
stage, such as rendering or bounding-box computation traversals.
See Imageable Purpose for more detail about how *purpose* is computed
and used.
Declaration
``uniform token purpose ="default"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
default, render, proxy, guide
"""
result["Imageable"].CreatePurposeAttr.func_doc = """CreatePurposeAttr(defaultValue, writeSparsely) -> Attribute
See GetPurposeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Imageable"].GetProxyPrimRel.func_doc = """GetProxyPrimRel() -> Relationship
The *proxyPrim* relationship allows us to link a prim whose *purpose*
is"render"to its (single target) purpose="proxy"prim.
This is entirely optional, but can be useful in several scenarios:
- In a pipeline that does pruning (for complexity management) by
deactivating prims composed from asset references, when we deactivate
a purpose="render"prim, we will be able to discover and additionally
deactivate its associated purpose="proxy"prim, so that preview renders
reflect the pruning accurately.
- DCC importers may be able to make more aggressive optimizations
for interactive processing and display if they can discover the proxy
for a given render prim.
- With a little more work, a Hydra-based application will be able
to map a picked proxy prim back to its render geometry for selection.
It is only valid to author the proxyPrim relationship on prims whose
purpose is"render".
"""
result["Imageable"].CreateProxyPrimRel.func_doc = """CreateProxyPrimRel() -> Relationship
See GetProxyPrimRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["Imageable"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Imageable"].Get.func_doc = """**classmethod** Get(stage, path) -> Imageable
Return a UsdGeomImageable holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomImageable(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Imageable"].GetOrderedPurposeTokens.func_doc = """**classmethod** GetOrderedPurposeTokens() -> list[TfToken]
Returns an ordered list of allowed values of the purpose attribute.
The ordering is important because it defines the protocol between
UsdGeomModelAPI and UsdGeomBBoxCache for caching and retrieving
extents hints by purpose.
The order is: [default, render, proxy, guide]
See
UsdGeomModelAPI::GetExtentsHint() .
GetOrderedPurposeTokens()
"""
result["Imageable"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["LinearUnits"].__doc__ = """
Container class for static double-precision symbols representing
common units of measure expressed in meters.
Encoding Stage Linear Units
"""
result["Mesh"].__doc__ = """
Encodes a mesh with optional subdivision properties and features.
As a point-based primitive, meshes are defined in terms of points that
are connected into edges and faces. Many references to meshes use the
term'vertex'in place of or interchangeably with'points', while some
use'vertex'to refer to the'face-vertices'that define a face. To avoid
confusion, the term'vertex'is intentionally avoided in favor
of'points'or'face-vertices'.
The connectivity between points, edges and faces is encoded using a
common minimal topological description of the faces of the mesh. Each
face is defined by a set of face-vertices using indices into the
Mesh's *points* array (inherited from UsdGeomPointBased) and laid out
in a single linear *faceVertexIndices* array for efficiency. A
companion *faceVertexCounts* array provides, for each face, the number
of consecutive face-vertices in *faceVertexIndices* that define the
face. No additional connectivity information is required or
constructed, so no adjacency or neighborhood queries are available.
A key property of this mesh schema is that it encodes both subdivision
surfaces and simpler polygonal meshes. This is achieved by varying the
*subdivisionScheme* attribute, which is set to specify Catmull-Clark
subdivision by default, so polygonal meshes must always be explicitly
declared. The available subdivision schemes and additional subdivision
features encoded in optional attributes conform to the feature set of
OpenSubdiv (
https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html).
**A Note About Primvars**
The following list clarifies the number of elements for and the
interpolation behavior of the different primvar interpolation types
for meshes:
- **constant** : One element for the entire mesh; no interpolation.
- **uniform** : One element for each face of the mesh; elements are
typically not interpolated but are inherited by other faces derived
from a given face (via subdivision, tessellation, etc.).
- **varying** : One element for each point of the mesh;
interpolation of point data is always linear.
- **vertex** : One element for each point of the mesh;
interpolation of point data is applied according to the
*subdivisionScheme* attribute.
- **faceVarying** : One element for each of the face-vertices that
define the mesh topology; interpolation of face-vertex data may be
smooth or linear, according to the *subdivisionScheme* and
*faceVaryingLinearInterpolation* attributes.
Primvar interpolation types and related utilities are described more
generally in Interpolation of Geometric Primitive Variables.
**A Note About Normals**
Normals should not be authored on a subdivision mesh, since
subdivision algorithms define their own normals. They should only be
authored for polygonal meshes ( *subdivisionScheme* ="none").
The *normals* attribute inherited from UsdGeomPointBased is not a
generic primvar, but the number of elements in this attribute will be
determined by its *interpolation*. See
UsdGeomPointBased::GetNormalsInterpolation() . If *normals* and
*primvars:normals* are both specified, the latter has precedence. If a
polygonal mesh specifies **neither** *normals* nor *primvars:normals*,
then it should be treated and rendered as faceted, with no attempt to
compute smooth normals.
The normals generated for smooth subdivision schemes, e.g. Catmull-
Clark and Loop, will likewise be smooth, but others, e.g. Bilinear,
may be discontinuous between faces and/or within non-planar irregular
faces.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["Mesh"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomMesh on UsdPrim ``prim`` .
Equivalent to UsdGeomMesh::Get (prim.GetStage(), prim.GetPath()) for a
*valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomMesh on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomMesh (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Mesh"].GetFaceVertexIndicesAttr.func_doc = """GetFaceVertexIndicesAttr() -> Attribute
Flat list of the index (into the *points* attribute) of each vertex of
each face in the mesh.
If this attribute has more than one timeSample, the mesh is considered
to be topologically varying.
Declaration
``int[] faceVertexIndices``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["Mesh"].CreateFaceVertexIndicesAttr.func_doc = """CreateFaceVertexIndicesAttr(defaultValue, writeSparsely) -> Attribute
See GetFaceVertexIndicesAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetFaceVertexCountsAttr.func_doc = """GetFaceVertexCountsAttr() -> Attribute
Provides the number of vertices in each face of the mesh, which is
also the number of consecutive indices in *faceVertexIndices* that
define the face.
The length of this attribute is the number of faces in the mesh. If
this attribute has more than one timeSample, the mesh is considered to
be topologically varying.
Declaration
``int[] faceVertexCounts``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["Mesh"].CreateFaceVertexCountsAttr.func_doc = """CreateFaceVertexCountsAttr(defaultValue, writeSparsely) -> Attribute
See GetFaceVertexCountsAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetSubdivisionSchemeAttr.func_doc = """GetSubdivisionSchemeAttr() -> Attribute
The subdivision scheme to be applied to the surface.
Valid values are:
- **catmullClark** : The default, Catmull-Clark subdivision;
preferred for quad-dominant meshes (generalizes B-splines);
interpolation of point data is smooth (non-linear)
- **loop** : Loop subdivision; preferred for purely triangular
meshes; interpolation of point data is smooth (non-linear)
- **bilinear** : Subdivision reduces all faces to quads
(topologically similar to"catmullClark"); interpolation of point data
is bilinear
- **none** : No subdivision, i.e. a simple polygonal mesh;
interpolation of point data is linear
Polygonal meshes are typically lighter weight and faster to render,
depending on renderer and render mode. Use of"bilinear"will produce a
similar shape to a polygonal mesh and may offer additional guarantees
of watertightness and additional subdivision features (e.g. holes) but
may also not respect authored normals.
Declaration
``uniform token subdivisionScheme ="catmullClark"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
catmullClark, loop, bilinear, none
"""
result["Mesh"].CreateSubdivisionSchemeAttr.func_doc = """CreateSubdivisionSchemeAttr(defaultValue, writeSparsely) -> Attribute
See GetSubdivisionSchemeAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetInterpolateBoundaryAttr.func_doc = """GetInterpolateBoundaryAttr() -> Attribute
Specifies how subdivision is applied for faces adjacent to boundary
edges and boundary points.
Valid values correspond to choices available in OpenSubdiv:
- **none** : No boundary interpolation is applied and boundary
faces are effectively treated as holes
- **edgeOnly** : A sequence of boundary edges defines a smooth
curve to which the edges of subdivided boundary faces converge
- **edgeAndCorner** : The default, similar to"edgeOnly"but the
smooth boundary curve is made sharp at corner points
These are illustrated and described in more detail in the OpenSubdiv
documentation:
https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#boundary-
interpolation-rules
Declaration
``token interpolateBoundary ="edgeAndCorner"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Allowed Values
none, edgeOnly, edgeAndCorner
"""
result["Mesh"].CreateInterpolateBoundaryAttr.func_doc = """CreateInterpolateBoundaryAttr(defaultValue, writeSparsely) -> Attribute
See GetInterpolateBoundaryAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetFaceVaryingLinearInterpolationAttr.func_doc = """GetFaceVaryingLinearInterpolationAttr() -> Attribute
Specifies how elements of a primvar of interpolation
type"faceVarying"are interpolated for subdivision surfaces.
Interpolation can be as smooth as a"vertex"primvar or constrained to
be linear at features specified by several options. Valid values
correspond to choices available in OpenSubdiv:
- **none** : No linear constraints or sharpening, smooth everywhere
- **cornersOnly** : Sharpen corners of discontinuous boundaries
only, smooth everywhere else
- **cornersPlus1** : The default, same as"cornersOnly"plus
additional sharpening at points where three or more distinct face-
varying values occur
- **cornersPlus2** : Same as"cornersPlus1"plus additional
sharpening at points with at least one discontinuous boundary corner
or only one discontinuous boundary edge (a dart)
- **boundaries** : Piecewise linear along discontinuous boundaries,
smooth interior
- **all** : Piecewise linear everywhere
These are illustrated and described in more detail in the OpenSubdiv
documentation:
https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#face-
varying-interpolation-rules
Declaration
``token faceVaryingLinearInterpolation ="cornersPlus1"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Allowed Values
none, cornersOnly, cornersPlus1, cornersPlus2, boundaries, all
"""
result["Mesh"].CreateFaceVaryingLinearInterpolationAttr.func_doc = """CreateFaceVaryingLinearInterpolationAttr(defaultValue, writeSparsely) -> Attribute
See GetFaceVaryingLinearInterpolationAttr() , and also Create vs Get
Property Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetTriangleSubdivisionRuleAttr.func_doc = """GetTriangleSubdivisionRuleAttr() -> Attribute
Specifies an option to the subdivision rules for the Catmull-Clark
scheme to try and improve undesirable artifacts when subdividing
triangles.
Valid values are"catmullClark"for the standard rules (the default)
and"smooth"for the improvement.
See
https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#triangle-
subdivision-rule
Declaration
``token triangleSubdivisionRule ="catmullClark"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Allowed Values
catmullClark, smooth
"""
result["Mesh"].CreateTriangleSubdivisionRuleAttr.func_doc = """CreateTriangleSubdivisionRuleAttr(defaultValue, writeSparsely) -> Attribute
See GetTriangleSubdivisionRuleAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetHoleIndicesAttr.func_doc = """GetHoleIndicesAttr() -> Attribute
The indices of all faces that should be treated as holes, i.e.
made invisible. This is traditionally a feature of subdivision
surfaces and not generally applied to polygonal meshes.
Declaration
``int[] holeIndices = []``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["Mesh"].CreateHoleIndicesAttr.func_doc = """CreateHoleIndicesAttr(defaultValue, writeSparsely) -> Attribute
See GetHoleIndicesAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetCornerIndicesAttr.func_doc = """GetCornerIndicesAttr() -> Attribute
The indices of points for which a corresponding sharpness value is
specified in *cornerSharpnesses* (so the size of this array must match
that of *cornerSharpnesses*).
Declaration
``int[] cornerIndices = []``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["Mesh"].CreateCornerIndicesAttr.func_doc = """CreateCornerIndicesAttr(defaultValue, writeSparsely) -> Attribute
See GetCornerIndicesAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetCornerSharpnessesAttr.func_doc = """GetCornerSharpnessesAttr() -> Attribute
The sharpness values associated with a corresponding set of points
specified in *cornerIndices* (so the size of this array must match
that of *cornerIndices*).
Use the constant ``SHARPNESS_INFINITE`` for a perfectly sharp corner.
Declaration
``float[] cornerSharpnesses = []``
C++ Type
VtArray<float>
Usd Type
SdfValueTypeNames->FloatArray
"""
result["Mesh"].CreateCornerSharpnessesAttr.func_doc = """CreateCornerSharpnessesAttr(defaultValue, writeSparsely) -> Attribute
See GetCornerSharpnessesAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetCreaseIndicesAttr.func_doc = """GetCreaseIndicesAttr() -> Attribute
The indices of points grouped into sets of successive pairs that
identify edges to be creased.
The size of this array must be equal to the sum of all elements of the
*creaseLengths* attribute.
Declaration
``int[] creaseIndices = []``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["Mesh"].CreateCreaseIndicesAttr.func_doc = """CreateCreaseIndicesAttr(defaultValue, writeSparsely) -> Attribute
See GetCreaseIndicesAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetCreaseLengthsAttr.func_doc = """GetCreaseLengthsAttr() -> Attribute
The length of this array specifies the number of creases (sets of
adjacent sharpened edges) on the mesh.
Each element gives the number of points of each crease, whose indices
are successively laid out in the *creaseIndices* attribute. Since each
crease must be at least one edge long, each element of this array must
be at least two.
Declaration
``int[] creaseLengths = []``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["Mesh"].CreateCreaseLengthsAttr.func_doc = """CreateCreaseLengthsAttr(defaultValue, writeSparsely) -> Attribute
See GetCreaseLengthsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetCreaseSharpnessesAttr.func_doc = """GetCreaseSharpnessesAttr() -> Attribute
The per-crease or per-edge sharpness values for all creases.
Since *creaseLengths* encodes the number of points in each crease, the
number of elements in this array will be either len(creaseLengths) or
the sum over all X of (creaseLengths[X] - 1). Note that while the RI
spec allows each crease to have either a single sharpness or a value
per-edge, USD will encode either a single sharpness per crease on a
mesh, or sharpnesses for all edges making up the creases on a mesh.
Use the constant ``SHARPNESS_INFINITE`` for a perfectly sharp crease.
Declaration
``float[] creaseSharpnesses = []``
C++ Type
VtArray<float>
Usd Type
SdfValueTypeNames->FloatArray
"""
result["Mesh"].CreateCreaseSharpnessesAttr.func_doc = """CreateCreaseSharpnessesAttr(defaultValue, writeSparsely) -> Attribute
See GetCreaseSharpnessesAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Mesh"].GetFaceCount.func_doc = """GetFaceCount(timeCode) -> int
Returns the number of faces as defined by the size of the
*faceVertexCounts* array at *timeCode*.
For most code, this check will be performant. When using file formats
where the cost of attribute reading is high and the time sampled array
will be read into memory later, it may be better to explicitly read
the value once and check the size of the array directly.
GetFaceVertexCountsAttr()
Parameters
----------
timeCode : TimeCode
"""
result["Mesh"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Mesh"].Get.func_doc = """**classmethod** Get(stage, path) -> Mesh
Return a UsdGeomMesh holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomMesh(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Mesh"].Define.func_doc = """**classmethod** Define(stage, path) -> Mesh
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Mesh"].ValidateTopology.func_doc = """**classmethod** ValidateTopology(faceVertexIndices, faceVertexCounts, numPoints, reason) -> bool
Validate the topology of a mesh.
This validates that the sum of ``faceVertexCounts`` is equal to the
size of the ``faceVertexIndices`` array, and that all face vertex
indices in the ``faceVertexIndices`` array are in the range [0,
numPoints). Returns true if the topology is valid, or false otherwise.
If the topology is invalid and ``reason`` is non-null, an error
message describing the validation error will be set.
Parameters
----------
faceVertexIndices : IntArray
faceVertexCounts : IntArray
numPoints : int
reason : str
"""
result["Mesh"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["ModelAPI"].__doc__ = """
UsdGeomModelAPI extends the generic UsdModelAPI schema with geometry
specific concepts such as cached extents for the entire model,
constraint targets, and geometry-inspired extensions to the payload
lofting process.
As described in GetExtentsHint() below, it is useful to cache extents
at the model level. UsdGeomModelAPI provides schema for computing and
storing these cached extents, which can be consumed by
UsdGeomBBoxCache to provide fast access to precomputed extents that
will be used as the model's bounds ( see
UsdGeomBBoxCache::UsdGeomBBoxCache() ).
Draw Modes
==========
Draw modes provide optional alternate imaging behavior for USD
subtrees with kind model. *model:drawMode* (which is inheritable) and
*model:applyDrawMode* (which is not) are resolved into a decision to
stop traversing the scene graph at a certain point, and replace a USD
subtree with proxy geometry.
The value of *model:drawMode* determines the type of proxy geometry:
- *origin* - Draw the model-space basis vectors of the replaced
prim.
- *bounds* - Draw the model-space bounding box of the replaced
prim.
- *cards* - Draw textured quads as a placeholder for the replaced
prim.
- *default* - An explicit opinion to draw the USD subtree as
normal.
- *inherited* - Defer to the parent opinion.
*model:drawMode* falls back to *inherited* so that a whole scene, a
large group, or all prototypes of a model hierarchy PointInstancer can
be assigned a draw mode with a single attribute edit. If no draw mode
is explicitly set in a hierarchy, the resolved value is *default*.
*model:applyDrawMode* is meant to be written when an asset is
authored, and provides flexibility for different asset types. For
example, a character assembly (composed of character, clothes, etc)
might have *model:applyDrawMode* set at the top of the subtree so the
whole group can be drawn as a single card object. An effects subtree
might have *model:applyDrawMode* set at a lower level so each particle
group draws individually.
Models of kind component are treated as if *model:applyDrawMode* were
true. This means a prim is drawn with proxy geometry when: the prim
has kind component, and/or *model:applyDrawMode* is set; and the
prim's resolved value for *model:drawMode* is not *default*.
Cards Geometry
==============
The specific geometry used in cards mode is controlled by the
*model:cardGeometry* attribute:
- *cross* - Generate a quad normal to each basis direction and
negative. Locate each quad so that it bisects the model extents.
- *box* - Generate a quad normal to each basis direction and
negative. Locate each quad on a face of the model extents, facing out.
- *fromTexture* - Generate a quad for each supplied texture from
attributes stored in that texture's metadata.
For *cross* and *box* mode, the extents are calculated for purposes
*default*, *proxy*, and *render*, at their earliest authored time. If
the model has no textures, all six card faces are rendered using
*model:drawModeColor*. If one or more textures are present, only axes
with one or more textures assigned are drawn. For each axis, if both
textures (positive and negative) are specified, they'll be used on the
corresponding card faces; if only one texture is specified, it will be
mapped to the opposite card face after being flipped on the texture's
s-axis. Any card faces with invalid asset paths will be drawn with
*model:drawModeColor*.
Both *model:cardGeometry* and *model:drawModeColor* should be authored
on the prim where the draw mode takes effect, since these attributes
are not inherited.
For *fromTexture* mode, only card faces with valid textures assigned
are drawn. The geometry is generated by pulling the *worldtoscreen*
attribute out of texture metadata. This is expected to be a 4x4 matrix
mapping the model-space position of the card quad to the clip-space
quad with corners (-1,-1,0) and (1,1,0). The card vertices are
generated by transforming the clip-space corners by the inverse of
*worldtoscreen*. Textures are mapped so that (s) and (t) map to (+x)
and (+y) in clip space. If the metadata cannot be read in the right
format, or the matrix can't be inverted, the card face is not drawn.
All card faces are drawn and textured as single-sided.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["ModelAPI"].GetExtentsHint.func_doc = """GetExtentsHint(extents, time) -> bool
Retrieve the authored value (if any) of this model's"extentsHint".
Persistent caching of bounds in USD is a potentially perilous
endeavor, given that:
- It is very easy to add overrides in new super-layers that
invalidate the cached bounds, and no practical way to automatically
detect when this happens
- It is possible for references to be allowed to"float", so that
asset updates can flow directly into cached scenes. Such changes in
referenced scene description can also invalidate cached bounds in
referencing layers.
For these reasons, as a general rule, we only persistently cache leaf
gprim extents in object space. However, even with cached gprim
extents, computing bounds can be expensive. Since model-level bounds
are so useful to many graphics applications, we make an exception,
with some caveats. The"extentsHint"should be considered entirely
optional (whereas gprim extent is not); if authored, it should
contains the extents for various values of gprim purposes. The extents
for different values of purpose are stored in a linear Vec3f array as
pairs of GfVec3f values in the order specified by
UsdGeomImageable::GetOrderedPurposeTokens() . This list is trimmed to
only include non-empty extents. i.e., if a model has only default and
render geoms, then it will only have 4 GfVec3f values in its
extentsHint array. We do not skip over zero extents, so if a model has
only default and proxy geom, we will author six GfVec3f 's, the middle
two representing an zero extent for render geometry.
A UsdGeomBBoxCache can be configured to first consult the cached
extents when evaluating model roots, rather than descending into the
models for the full computation. This is not the default behavior, and
gives us a convenient way to validate that the cached extentsHint is
still valid.
``true`` if a value was fetched; ``false`` if no value was authored,
or on error. It is an error to make this query of a prim that is not a
model root.
UsdGeomImageable::GetPurposeAttr() ,
UsdGeomImageable::GetOrderedPurposeTokens()
Parameters
----------
extents : Vec3fArray
time : TimeCode
"""
result["ModelAPI"].SetExtentsHint.func_doc = """SetExtentsHint(extents, time) -> bool
Authors the extentsHint array for this model at the given time.
GetExtentsHint()
Parameters
----------
extents : Vec3fArray
time : TimeCode
"""
result["ModelAPI"].GetExtentsHintAttr.func_doc = """GetExtentsHintAttr() -> Attribute
Returns the custom'extentsHint'attribute if it exits.
"""
result["ModelAPI"].ComputeExtentsHint.func_doc = """ComputeExtentsHint(bboxCache) -> Vec3fArray
For the given model, compute the value for the extents hint with the
given ``bboxCache`` .
``bboxCache`` should be setup with the appropriate time. After calling
this function, the ``bboxCache`` may have it's included purposes
changed.
``bboxCache`` should not be in use by any other thread while this
method is using it in a thread.
Parameters
----------
bboxCache : BBoxCache
"""
result["ModelAPI"].GetConstraintTarget.func_doc = """GetConstraintTarget(constraintName) -> ConstraintTarget
Get the constraint target with the given name, ``constraintName`` .
If the requested constraint target does not exist, then an invalid
UsdConstraintTarget object is returned.
Parameters
----------
constraintName : str
"""
result["ModelAPI"].CreateConstraintTarget.func_doc = """CreateConstraintTarget(constraintName) -> ConstraintTarget
Creates a new constraint target with the given name,
``constraintName`` .
If the constraint target already exists, then the existing target is
returned. If it does not exist, a new one is created and returned.
Parameters
----------
constraintName : str
"""
result["ModelAPI"].GetConstraintTargets.func_doc = """GetConstraintTargets() -> list[ConstraintTarget]
Returns all the constraint targets belonging to the model.
Only valid constraint targets in the"constraintTargets"namespace are
returned by this method.
"""
result["ModelAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomModelAPI on UsdPrim ``prim`` .
Equivalent to UsdGeomModelAPI::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomModelAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomModelAPI (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["ModelAPI"].GetModelDrawModeAttr.func_doc = """GetModelDrawModeAttr() -> Attribute
Alternate imaging mode; applied to this prim or child prims where
*model:applyDrawMode* is true, or where the prim has kind *component*.
See Draw Modes for mode descriptions.
Declaration
``uniform token model:drawMode ="inherited"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
origin, bounds, cards, default, inherited
"""
result["ModelAPI"].CreateModelDrawModeAttr.func_doc = """CreateModelDrawModeAttr(defaultValue, writeSparsely) -> Attribute
See GetModelDrawModeAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].GetModelApplyDrawModeAttr.func_doc = """GetModelApplyDrawModeAttr() -> Attribute
If true, and the resolved value of *model:drawMode* is non-default,
apply an alternate imaging mode to this prim.
See Draw Modes.
Declaration
``uniform bool model:applyDrawMode = 0``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
Variability
SdfVariabilityUniform
"""
result["ModelAPI"].CreateModelApplyDrawModeAttr.func_doc = """CreateModelApplyDrawModeAttr(defaultValue, writeSparsely) -> Attribute
See GetModelApplyDrawModeAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].GetModelDrawModeColorAttr.func_doc = """GetModelDrawModeColorAttr() -> Attribute
The base color of imaging prims inserted for alternate imaging modes.
For *origin* and *bounds* modes, this controls line color; for *cards*
mode, this controls the fallback quad color.
Declaration
``uniform float3 model:drawModeColor = (0.18, 0.18, 0.18)``
C++ Type
GfVec3f
Usd Type
SdfValueTypeNames->Float3
Variability
SdfVariabilityUniform
"""
result["ModelAPI"].CreateModelDrawModeColorAttr.func_doc = """CreateModelDrawModeColorAttr(defaultValue, writeSparsely) -> Attribute
See GetModelDrawModeColorAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].GetModelCardGeometryAttr.func_doc = """GetModelCardGeometryAttr() -> Attribute
The geometry to generate for imaging prims inserted for *cards*
imaging mode.
See Cards Geometry for geometry descriptions.
Declaration
``uniform token model:cardGeometry ="cross"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
cross, box, fromTexture
"""
result["ModelAPI"].CreateModelCardGeometryAttr.func_doc = """CreateModelCardGeometryAttr(defaultValue, writeSparsely) -> Attribute
See GetModelCardGeometryAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].GetModelCardTextureXPosAttr.func_doc = """GetModelCardTextureXPosAttr() -> Attribute
In *cards* imaging mode, the texture applied to the X+ quad.
The texture axes (s,t) are mapped to model-space axes (-y, -z).
Declaration
``asset model:cardTextureXPos``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
"""
result["ModelAPI"].CreateModelCardTextureXPosAttr.func_doc = """CreateModelCardTextureXPosAttr(defaultValue, writeSparsely) -> Attribute
See GetModelCardTextureXPosAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].GetModelCardTextureYPosAttr.func_doc = """GetModelCardTextureYPosAttr() -> Attribute
In *cards* imaging mode, the texture applied to the Y+ quad.
The texture axes (s,t) are mapped to model-space axes (x, -z).
Declaration
``asset model:cardTextureYPos``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
"""
result["ModelAPI"].CreateModelCardTextureYPosAttr.func_doc = """CreateModelCardTextureYPosAttr(defaultValue, writeSparsely) -> Attribute
See GetModelCardTextureYPosAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].GetModelCardTextureZPosAttr.func_doc = """GetModelCardTextureZPosAttr() -> Attribute
In *cards* imaging mode, the texture applied to the Z+ quad.
The texture axes (s,t) are mapped to model-space axes (x, -y).
Declaration
``asset model:cardTextureZPos``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
"""
result["ModelAPI"].CreateModelCardTextureZPosAttr.func_doc = """CreateModelCardTextureZPosAttr(defaultValue, writeSparsely) -> Attribute
See GetModelCardTextureZPosAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].GetModelCardTextureXNegAttr.func_doc = """GetModelCardTextureXNegAttr() -> Attribute
In *cards* imaging mode, the texture applied to the X- quad.
The texture axes (s,t) are mapped to model-space axes (y, -z).
Declaration
``asset model:cardTextureXNeg``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
"""
result["ModelAPI"].CreateModelCardTextureXNegAttr.func_doc = """CreateModelCardTextureXNegAttr(defaultValue, writeSparsely) -> Attribute
See GetModelCardTextureXNegAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].GetModelCardTextureYNegAttr.func_doc = """GetModelCardTextureYNegAttr() -> Attribute
In *cards* imaging mode, the texture applied to the Y- quad.
The texture axes (s,t) are mapped to model-space axes (-x, -z).
Declaration
``asset model:cardTextureYNeg``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
"""
result["ModelAPI"].CreateModelCardTextureYNegAttr.func_doc = """CreateModelCardTextureYNegAttr(defaultValue, writeSparsely) -> Attribute
See GetModelCardTextureYNegAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].GetModelCardTextureZNegAttr.func_doc = """GetModelCardTextureZNegAttr() -> Attribute
In *cards* imaging mode, the texture applied to the Z- quad.
The texture axes (s,t) are mapped to model-space axes (-x, -y).
Declaration
``asset model:cardTextureZNeg``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
"""
result["ModelAPI"].CreateModelCardTextureZNegAttr.func_doc = """CreateModelCardTextureZNegAttr(defaultValue, writeSparsely) -> Attribute
See GetModelCardTextureZNegAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["ModelAPI"].ComputeModelDrawMode.func_doc = """ComputeModelDrawMode(parentDrawMode) -> str
Calculate the effective model:drawMode of this prim.
If the draw mode is authored on this prim, it's used. Otherwise, the
fallback value is"inherited", which defers to the parent opinion. The
first non-inherited opinion found walking from this prim towards the
root is used. If the attribute isn't set on any ancestors, we
return"default"(meaning, disable"drawMode"geometry).
If this function is being called in a traversal context to compute the
draw mode of an entire hierarchy of prims, it would be beneficial to
cache and pass in the computed parent draw-mode via the
``parentDrawMode`` parameter. This avoids repeated upward traversal to
look for ancestor opinions.
When ``parentDrawMode`` is empty (or unspecified), this function does
an upward traversal to find the closest ancestor with an authored
model:drawMode.
GetModelDrawModeAttr()
Parameters
----------
parentDrawMode : str
"""
result["ModelAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["ModelAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> ModelAPI
Return a UsdGeomModelAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomModelAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["ModelAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["ModelAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> ModelAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"GeomModelAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdGeomModelAPI object is returned upon success. An invalid
(or empty) UsdGeomModelAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["ModelAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["MotionAPI"].__doc__ = """
UsdGeomMotionAPI encodes data that can live on any prim that may
affect computations involving:
- computed motion for motion blur
- sampling for motion blur
The motion:blurScale attribute allows artists to scale the **amount**
of motion blur to be rendered for parts of the scene without changing
the recorded animation. See Effectively Applying motion:blurScale for
use and implementation details.
"""
result["MotionAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomMotionAPI on UsdPrim ``prim`` .
Equivalent to UsdGeomMotionAPI::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomMotionAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomMotionAPI (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["MotionAPI"].GetMotionBlurScaleAttr.func_doc = """GetMotionBlurScaleAttr() -> Attribute
BlurScale is an **inherited** float attribute that stipulates the
rendered motion blur (as typically specified via UsdGeomCamera 's
*shutter:open* and *shutter:close* properties) should be scaled for
**all objects** at and beneath the prim in namespace on which the
*motion:blurScale* value is specified.
Without changing any other data in the scene, *blurScale* allows
artists to"dial in"the amount of blur on a per-object basis. A
*blurScale* value of zero removes all blur, a value of 0.5 reduces
blur by half, and a value of 2.0 doubles the blur. The legal range for
*blurScale* is [0, inf), although very high values may result in
extremely expensive renders, and may exceed the capabilities of some
renderers.
Although renderers are free to implement this feature however they see
fit, see Effectively Applying motion:blurScale for our guidance on
implementing the feature universally and efficiently.
ComputeMotionBlurScale()
Declaration
``float motion:blurScale = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["MotionAPI"].CreateMotionBlurScaleAttr.func_doc = """CreateMotionBlurScaleAttr(defaultValue, writeSparsely) -> Attribute
See GetMotionBlurScaleAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MotionAPI"].GetVelocityScaleAttr.func_doc = """GetVelocityScaleAttr() -> Attribute
Deprecated
VelocityScale is an **inherited** float attribute that velocity-based
schemas (e.g. PointBased, PointInstancer) can consume to compute
interpolated positions and orientations by applying velocity and
angularVelocity, which is required for interpolating between samples
when topology is varying over time. Although these quantities are
generally physically computed by a simulator, sometimes we require
more or less motion-blur to achieve the desired look. VelocityScale
allows artists to dial-in, as a post-sim correction, a scale factor to
be applied to the velocity prior to computing interpolated positions
from it.
Declaration
``float motion:velocityScale = 1``
C++ Type
float
Usd Type
SdfValueTypeNames->Float
"""
result["MotionAPI"].CreateVelocityScaleAttr.func_doc = """CreateVelocityScaleAttr(defaultValue, writeSparsely) -> Attribute
See GetVelocityScaleAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MotionAPI"].GetNonlinearSampleCountAttr.func_doc = """GetNonlinearSampleCountAttr() -> Attribute
Determines the number of position or transformation samples created
when motion is described by attributes contributing non-linear terms.
To give an example, imagine an application (such as a renderer)
consuming'points'and the USD document also contains'accelerations'for
the same prim. Unless the application can consume
these'accelerations'itself, an intermediate layer has to compute
samples within the sampling interval for the point positions based on
the value of'points','velocities'and'accelerations'. The number of
these samples is given by'nonlinearSampleCount'. The samples are
equally spaced within the sampling interval.
Another example involves the PointInstancer
where'nonlinearSampleCount'is relevant
when'angularVelocities'or'accelerations'are authored.
'nonlinearSampleCount'is an **inherited** attribute, also see
ComputeNonlinearSampleCount()
Declaration
``int motion:nonlinearSampleCount = 3``
C++ Type
int
Usd Type
SdfValueTypeNames->Int
"""
result["MotionAPI"].CreateNonlinearSampleCountAttr.func_doc = """CreateNonlinearSampleCountAttr(defaultValue, writeSparsely) -> Attribute
See GetNonlinearSampleCountAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["MotionAPI"].ComputeVelocityScale.func_doc = """ComputeVelocityScale(time) -> float
Deprecated
Compute the inherited value of *velocityScale* at ``time`` , i.e. the
authored value on the prim closest to this prim in namespace, resolved
upwards through its ancestors in namespace.
the inherited value, or 1.0 if neither the prim nor any of its
ancestors possesses an authored value.
this is a reference implementation that is not particularly efficient
if evaluating over many prims, because it does not share inherited
results.
Parameters
----------
time : TimeCode
"""
result["MotionAPI"].ComputeNonlinearSampleCount.func_doc = """ComputeNonlinearSampleCount(time) -> int
Compute the inherited value of *nonlinearSampleCount* at ``time`` ,
i.e.
the authored value on the prim closest to this prim in namespace,
resolved upwards through its ancestors in namespace.
the inherited value, or 3 if neither the prim nor any of its ancestors
possesses an authored value.
this is a reference implementation that is not particularly efficient
if evaluating over many prims, because it does not share inherited
results.
Parameters
----------
time : TimeCode
"""
result["MotionAPI"].ComputeMotionBlurScale.func_doc = """ComputeMotionBlurScale(time) -> float
Compute the inherited value of *motion:blurScale* at ``time`` , i.e.
the authored value on the prim closest to this prim in namespace,
resolved upwards through its ancestors in namespace.
the inherited value, or 1.0 if neither the prim nor any of its
ancestors possesses an authored value.
this is a reference implementation that is not particularly efficient
if evaluating over many prims, because it does not share inherited
results.
Parameters
----------
time : TimeCode
"""
result["MotionAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["MotionAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> MotionAPI
Return a UsdGeomMotionAPI holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomMotionAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["MotionAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["MotionAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> MotionAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"MotionAPI"to the token-valued,
listOp metadata *apiSchemas* on the prim.
A valid UsdGeomMotionAPI object is returned upon success. An invalid
(or empty) UsdGeomMotionAPI object is returned upon failure. See
UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["MotionAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["NurbsCurves"].__doc__ = """
This schema is analagous to NURBS Curves in packages like Maya and
Houdini, often used for interchange of rigging and modeling curves.
Unlike Maya, this curve spec supports batching of multiple curves into
a single prim, widths, and normals in the schema. Additionally, we
require'numSegments + 2 \\* degree + 1'knots (2 more than maya does).
This is to be more consistent with RenderMan's NURBS patch
specification.
To express a periodic curve:
- knot[0] = knot[1] - (knots[-2] - knots[-3];
- knot[-1] = knot[-2] + (knot[2] - knots[1]);
To express a nonperiodic curve:
- knot[0] = knot[1];
- knot[-1] = knot[-2];
In spite of these slight differences in the spec, curves generated in
Maya should be preserved when roundtripping.
*order* and *range*, when representing a batched NurbsCurve should be
authored one value per curve. *knots* should be the concatentation of
all batched curves.
**NurbsCurve Form**
**Form** is provided as an aid to interchange between modeling and
animation applications so that they can robustly identify the intent
with which the surface was modelled, and take measures (if they are
able) to preserve the continuity/concidence constraints as the surface
may be rigged or deformed.
- An *open-form* NurbsCurve has no continuity constraints.
- A *closed-form* NurbsCurve expects the first and last control
points to overlap
- A *periodic-form* NurbsCurve expects the first and last *order* -
1 control points to overlap.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["NurbsCurves"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomNurbsCurves on UsdPrim ``prim`` .
Equivalent to UsdGeomNurbsCurves::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomNurbsCurves on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomNurbsCurves (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["NurbsCurves"].GetOrderAttr.func_doc = """GetOrderAttr() -> Attribute
Order of the curve.
Order must be positive and is equal to the degree of the polynomial
basis to be evaluated, plus 1. Its value for the'i'th curve must be
less than or equal to curveVertexCount[i]
Declaration
``int[] order = []``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["NurbsCurves"].CreateOrderAttr.func_doc = """CreateOrderAttr(defaultValue, writeSparsely) -> Attribute
See GetOrderAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsCurves"].GetKnotsAttr.func_doc = """GetKnotsAttr() -> Attribute
Knot vector providing curve parameterization.
The length of the slice of the array for the ith curve must be (
curveVertexCount[i] + order[i] ), and its entries must take on
monotonically increasing values.
Declaration
``double[] knots``
C++ Type
VtArray<double>
Usd Type
SdfValueTypeNames->DoubleArray
"""
result["NurbsCurves"].CreateKnotsAttr.func_doc = """CreateKnotsAttr(defaultValue, writeSparsely) -> Attribute
See GetKnotsAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsCurves"].GetRangesAttr.func_doc = """GetRangesAttr() -> Attribute
Provides the minimum and maximum parametric values (as defined by
knots) over which the curve is actually defined.
The minimum must be less than the maximum, and greater than or equal
to the value of the knots['i'th curve slice][order[i]-1]. The maxium
must be less than or equal to the last element's value in knots['i'th
curve slice]. Range maps to (vmin, vmax) in the RenderMan spec.
Declaration
``double2[] ranges``
C++ Type
VtArray<GfVec2d>
Usd Type
SdfValueTypeNames->Double2Array
"""
result["NurbsCurves"].CreateRangesAttr.func_doc = """CreateRangesAttr(defaultValue, writeSparsely) -> Attribute
See GetRangesAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsCurves"].GetPointWeightsAttr.func_doc = """GetPointWeightsAttr() -> Attribute
Optionally provides"w"components for each control point, thus must be
the same length as the points attribute.
If authored, the patch will be rational. If unauthored, the patch will
be polynomial, i.e. weight for all points is 1.0.
Some DCC's pre-weight the *points*, but in this schema, *points* are
not pre-weighted.
Declaration
``double[] pointWeights``
C++ Type
VtArray<double>
Usd Type
SdfValueTypeNames->DoubleArray
"""
result["NurbsCurves"].CreatePointWeightsAttr.func_doc = """CreatePointWeightsAttr(defaultValue, writeSparsely) -> Attribute
See GetPointWeightsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsCurves"].GetFormAttr.func_doc = """GetFormAttr() -> Attribute
Interpret the control grid and knot vectors as representing an open,
geometrically closed, or geometrically closed and C2 continuous curve.
NurbsCurve Form
Declaration
``uniform token form ="open"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
open, closed, periodic
"""
result["NurbsCurves"].CreateFormAttr.func_doc = """CreateFormAttr(defaultValue, writeSparsely) -> Attribute
See GetFormAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsCurves"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["NurbsCurves"].Get.func_doc = """**classmethod** Get(stage, path) -> NurbsCurves
Return a UsdGeomNurbsCurves holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomNurbsCurves(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["NurbsCurves"].Define.func_doc = """**classmethod** Define(stage, path) -> NurbsCurves
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["NurbsCurves"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["NurbsPatch"].__doc__ = """
Encodes a rational or polynomial non-uniform B-spline surface, with
optional trim curves.
The encoding mostly follows that of RiNuPatch and RiTrimCurve:
https://renderman.pixar.com/resources/current/RenderMan/geometricPrimitives.html#rinupatch,
with some minor renaming and coalescing for clarity.
The layout of control vertices in the *points* attribute inherited
from UsdGeomPointBased is row-major with U considered rows, and V
columns.
**NurbsPatch Form**
The authored points, orders, knots, weights, and ranges are all that
is required to render the nurbs patch. However, the only way to model
closed surfaces with nurbs is to ensure that the first and last
control points along the given axis are coincident. Similarly, to
ensure the surface is not only closed but also C2 continuous, the last
*order* - 1 control points must be (correspondingly) coincident with
the first *order* - 1 control points, and also the spacing of the last
corresponding knots must be the same as the first corresponding knots.
**Form** is provided as an aid to interchange between modeling and
animation applications so that they can robustly identify the intent
with which the surface was modelled, and take measures (if they are
able) to preserve the continuity/concidence constraints as the surface
may be rigged or deformed.
- An *open-form* NurbsPatch has no continuity constraints.
- A *closed-form* NurbsPatch expects the first and last control
points to overlap
- A *periodic-form* NurbsPatch expects the first and last *order* -
1 control points to overlap.
**Nurbs vs Subdivision Surfaces**
Nurbs are an important modeling primitive in CAD/CAM tools and early
computer graphics DCC's. Because they have a natural UV
parameterization they easily support"trim curves", which allow smooth
shapes to be carved out of the surface.
However, the topology of the patch is always rectangular, and joining
two nurbs patches together (especially when they have differing
numbers of spans) is difficult to do smoothly. Also, nurbs are not
supported by the Ptex texturing technology ( http://ptex.us).
Neither of these limitations are shared by subdivision surfaces;
therefore, although they do not subscribe to trim-curve-based shaping,
subdivs are often considered a more flexible modeling primitive.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["NurbsPatch"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomNurbsPatch on UsdPrim ``prim`` .
Equivalent to UsdGeomNurbsPatch::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomNurbsPatch on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomNurbsPatch (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["NurbsPatch"].GetUVertexCountAttr.func_doc = """GetUVertexCountAttr() -> Attribute
Number of vertices in the U direction.
Should be at least as large as uOrder.
Declaration
``int uVertexCount``
C++ Type
int
Usd Type
SdfValueTypeNames->Int
"""
result["NurbsPatch"].CreateUVertexCountAttr.func_doc = """CreateUVertexCountAttr(defaultValue, writeSparsely) -> Attribute
See GetUVertexCountAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetVVertexCountAttr.func_doc = """GetVVertexCountAttr() -> Attribute
Number of vertices in the V direction.
Should be at least as large as vOrder.
Declaration
``int vVertexCount``
C++ Type
int
Usd Type
SdfValueTypeNames->Int
"""
result["NurbsPatch"].CreateVVertexCountAttr.func_doc = """CreateVVertexCountAttr(defaultValue, writeSparsely) -> Attribute
See GetVVertexCountAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetUOrderAttr.func_doc = """GetUOrderAttr() -> Attribute
Order in the U direction.
Order must be positive and is equal to the degree of the polynomial
basis to be evaluated, plus 1.
Declaration
``int uOrder``
C++ Type
int
Usd Type
SdfValueTypeNames->Int
"""
result["NurbsPatch"].CreateUOrderAttr.func_doc = """CreateUOrderAttr(defaultValue, writeSparsely) -> Attribute
See GetUOrderAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetVOrderAttr.func_doc = """GetVOrderAttr() -> Attribute
Order in the V direction.
Order must be positive and is equal to the degree of the polynomial
basis to be evaluated, plus 1.
Declaration
``int vOrder``
C++ Type
int
Usd Type
SdfValueTypeNames->Int
"""
result["NurbsPatch"].CreateVOrderAttr.func_doc = """CreateVOrderAttr(defaultValue, writeSparsely) -> Attribute
See GetVOrderAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetUKnotsAttr.func_doc = """GetUKnotsAttr() -> Attribute
Knot vector for U direction providing U parameterization.
The length of this array must be ( uVertexCount + uOrder), and its
entries must take on monotonically increasing values.
Declaration
``double[] uKnots``
C++ Type
VtArray<double>
Usd Type
SdfValueTypeNames->DoubleArray
"""
result["NurbsPatch"].CreateUKnotsAttr.func_doc = """CreateUKnotsAttr(defaultValue, writeSparsely) -> Attribute
See GetUKnotsAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetVKnotsAttr.func_doc = """GetVKnotsAttr() -> Attribute
Knot vector for V direction providing U parameterization.
The length of this array must be ( vVertexCount + vOrder), and its
entries must take on monotonically increasing values.
Declaration
``double[] vKnots``
C++ Type
VtArray<double>
Usd Type
SdfValueTypeNames->DoubleArray
"""
result["NurbsPatch"].CreateVKnotsAttr.func_doc = """CreateVKnotsAttr(defaultValue, writeSparsely) -> Attribute
See GetVKnotsAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetUFormAttr.func_doc = """GetUFormAttr() -> Attribute
Interpret the control grid and knot vectors as representing an open,
geometrically closed, or geometrically closed and C2 continuous
surface along the U dimension.
NurbsPatch Form
Declaration
``uniform token uForm ="open"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
open, closed, periodic
"""
result["NurbsPatch"].CreateUFormAttr.func_doc = """CreateUFormAttr(defaultValue, writeSparsely) -> Attribute
See GetUFormAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetVFormAttr.func_doc = """GetVFormAttr() -> Attribute
Interpret the control grid and knot vectors as representing an open,
geometrically closed, or geometrically closed and C2 continuous
surface along the V dimension.
NurbsPatch Form
Declaration
``uniform token vForm ="open"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
open, closed, periodic
"""
result["NurbsPatch"].CreateVFormAttr.func_doc = """CreateVFormAttr(defaultValue, writeSparsely) -> Attribute
See GetVFormAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetURangeAttr.func_doc = """GetURangeAttr() -> Attribute
Provides the minimum and maximum parametric values (as defined by
uKnots) over which the surface is actually defined.
The minimum must be less than the maximum, and greater than or equal
to the value of uKnots[uOrder-1]. The maxium must be less than or
equal to the last element's value in uKnots.
Declaration
``double2 uRange``
C++ Type
GfVec2d
Usd Type
SdfValueTypeNames->Double2
"""
result["NurbsPatch"].CreateURangeAttr.func_doc = """CreateURangeAttr(defaultValue, writeSparsely) -> Attribute
See GetURangeAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetVRangeAttr.func_doc = """GetVRangeAttr() -> Attribute
Provides the minimum and maximum parametric values (as defined by
vKnots) over which the surface is actually defined.
The minimum must be less than the maximum, and greater than or equal
to the value of vKnots[vOrder-1]. The maxium must be less than or
equal to the last element's value in vKnots.
Declaration
``double2 vRange``
C++ Type
GfVec2d
Usd Type
SdfValueTypeNames->Double2
"""
result["NurbsPatch"].CreateVRangeAttr.func_doc = """CreateVRangeAttr(defaultValue, writeSparsely) -> Attribute
See GetVRangeAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetPointWeightsAttr.func_doc = """GetPointWeightsAttr() -> Attribute
Optionally provides"w"components for each control point, thus must be
the same length as the points attribute.
If authored, the patch will be rational. If unauthored, the patch will
be polynomial, i.e. weight for all points is 1.0.
Some DCC's pre-weight the *points*, but in this schema, *points* are
not pre-weighted.
Declaration
``double[] pointWeights``
C++ Type
VtArray<double>
Usd Type
SdfValueTypeNames->DoubleArray
"""
result["NurbsPatch"].CreatePointWeightsAttr.func_doc = """CreatePointWeightsAttr(defaultValue, writeSparsely) -> Attribute
See GetPointWeightsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetTrimCurveCountsAttr.func_doc = """GetTrimCurveCountsAttr() -> Attribute
Each element specifies how many curves are present in each"loop"of the
trimCurve, and the length of the array determines how many loops the
trimCurve contains.
The sum of all elements is the total nuber of curves in the trim, to
which we will refer as *nCurves* in describing the other trim
attributes.
Declaration
``int[] trimCurve:counts``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["NurbsPatch"].CreateTrimCurveCountsAttr.func_doc = """CreateTrimCurveCountsAttr(defaultValue, writeSparsely) -> Attribute
See GetTrimCurveCountsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetTrimCurveOrdersAttr.func_doc = """GetTrimCurveOrdersAttr() -> Attribute
Flat list of orders for each of the *nCurves* curves.
Declaration
``int[] trimCurve:orders``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["NurbsPatch"].CreateTrimCurveOrdersAttr.func_doc = """CreateTrimCurveOrdersAttr(defaultValue, writeSparsely) -> Attribute
See GetTrimCurveOrdersAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetTrimCurveVertexCountsAttr.func_doc = """GetTrimCurveVertexCountsAttr() -> Attribute
Flat list of number of vertices for each of the *nCurves* curves.
Declaration
``int[] trimCurve:vertexCounts``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["NurbsPatch"].CreateTrimCurveVertexCountsAttr.func_doc = """CreateTrimCurveVertexCountsAttr(defaultValue, writeSparsely) -> Attribute
See GetTrimCurveVertexCountsAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetTrimCurveKnotsAttr.func_doc = """GetTrimCurveKnotsAttr() -> Attribute
Flat list of parametric values for each of the *nCurves* curves.
There will be as many knots as the sum over all elements of
*vertexCounts* plus the sum over all elements of *orders*.
Declaration
``double[] trimCurve:knots``
C++ Type
VtArray<double>
Usd Type
SdfValueTypeNames->DoubleArray
"""
result["NurbsPatch"].CreateTrimCurveKnotsAttr.func_doc = """CreateTrimCurveKnotsAttr(defaultValue, writeSparsely) -> Attribute
See GetTrimCurveKnotsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetTrimCurveRangesAttr.func_doc = """GetTrimCurveRangesAttr() -> Attribute
Flat list of minimum and maximum parametric values (as defined by
*knots*) for each of the *nCurves* curves.
Declaration
``double2[] trimCurve:ranges``
C++ Type
VtArray<GfVec2d>
Usd Type
SdfValueTypeNames->Double2Array
"""
result["NurbsPatch"].CreateTrimCurveRangesAttr.func_doc = """CreateTrimCurveRangesAttr(defaultValue, writeSparsely) -> Attribute
See GetTrimCurveRangesAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetTrimCurvePointsAttr.func_doc = """GetTrimCurvePointsAttr() -> Attribute
Flat list of homogeneous 2D points (u, v, w) that comprise the
*nCurves* curves.
The number of points should be equal to the um over all elements of
*vertexCounts*.
Declaration
``double3[] trimCurve:points``
C++ Type
VtArray<GfVec3d>
Usd Type
SdfValueTypeNames->Double3Array
"""
result["NurbsPatch"].CreateTrimCurvePointsAttr.func_doc = """CreateTrimCurvePointsAttr(defaultValue, writeSparsely) -> Attribute
See GetTrimCurvePointsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["NurbsPatch"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["NurbsPatch"].Get.func_doc = """**classmethod** Get(stage, path) -> NurbsPatch
Return a UsdGeomNurbsPatch holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomNurbsPatch(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["NurbsPatch"].Define.func_doc = """**classmethod** Define(stage, path) -> NurbsPatch
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["NurbsPatch"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Plane"].__doc__ = """
Defines a primitive plane, centered at the origin, and is defined by a
cardinal axis, width, and length. The plane is double-sided by
default.
The axis of width and length are perpendicular to the plane's *axis*:
axis
width
length
X
z-axis
y-axis
Y
x-axis
z-axis
Z
x-axis
y-axis
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["Plane"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomPlane on UsdPrim ``prim`` .
Equivalent to UsdGeomPlane::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomPlane on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomPlane (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Plane"].GetDoubleSidedAttr.func_doc = """GetDoubleSidedAttr() -> Attribute
Planes are double-sided by default.
Clients may also support single-sided planes.
UsdGeomGprim::GetDoubleSidedAttr()
Declaration
``uniform bool doubleSided = 1``
C++ Type
bool
Usd Type
SdfValueTypeNames->Bool
Variability
SdfVariabilityUniform
"""
result["Plane"].CreateDoubleSidedAttr.func_doc = """CreateDoubleSidedAttr(defaultValue, writeSparsely) -> Attribute
See GetDoubleSidedAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Plane"].GetWidthAttr.func_doc = """GetWidthAttr() -> Attribute
The width of the plane, which aligns to the x-axis when *axis*
is'Z'or'Y', or to the z-axis when *axis* is'X'.
If you author *width* you must also author *extent*.
UsdGeomGprim::GetExtentAttr()
Declaration
``double width = 2``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Plane"].CreateWidthAttr.func_doc = """CreateWidthAttr(defaultValue, writeSparsely) -> Attribute
See GetWidthAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Plane"].GetLengthAttr.func_doc = """GetLengthAttr() -> Attribute
The length of the plane, which aligns to the y-axis when *axis*
is'Z'or'X', or to the z-axis when *axis* is'Y'.
If you author *length* you must also author *extent*.
UsdGeomGprim::GetExtentAttr()
Declaration
``double length = 2``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Plane"].CreateLengthAttr.func_doc = """CreateLengthAttr(defaultValue, writeSparsely) -> Attribute
See GetLengthAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Plane"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute
The axis along which the surface of the plane is aligned.
When set to'Z'the plane is in the xy-plane; when *axis* is'X'the plane
is in the yz-plane, and when *axis* is'Y'the plane is in the xz-plane.
UsdGeomGprim::GetAxisAttr().
Declaration
``uniform token axis ="Z"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
X, Y, Z
"""
result["Plane"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute
See GetAxisAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Plane"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute
Extent is re-defined on Plane only to provide a fallback value.
UsdGeomGprim::GetExtentAttr() .
Declaration
``float3[] extent = [(-1, -1, 0), (1, 1, 0)]``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Float3Array
"""
result["Plane"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute
See GetExtentAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Plane"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Plane"].Get.func_doc = """**classmethod** Get(stage, path) -> Plane
Return a UsdGeomPlane holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomPlane(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Plane"].Define.func_doc = """**classmethod** Define(stage, path) -> Plane
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Plane"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(width, length, axis, extent) -> bool
Compute the extent for the plane defined by the size of each
dimension.
true upon success, false if unable to calculate extent. On success,
extent will contain an approximate axis-aligned bounding box of the
plane defined by the size of each dimension.
This function is to provide easy authoring of extent for usd authoring
tools, hence it is static and acts outside a specific prim (as in
attribute based methods).
Parameters
----------
width : float
length : float
axis : str
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtent(width, length, axis, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
width : float
length : float
axis : str
transform : Matrix4d
extent : Vec3fArray
"""
result["Plane"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["PointBased"].__doc__ = """
Base class for all UsdGeomGprims that possess points, providing common
attributes such as normals and velocities.
"""
result["PointBased"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomPointBased on UsdPrim ``prim`` .
Equivalent to UsdGeomPointBased::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomPointBased on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomPointBased (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["PointBased"].GetPointsAttr.func_doc = """GetPointsAttr() -> Attribute
The primary geometry attribute for all PointBased primitives,
describes points in (local) space.
Declaration
``point3f[] points``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Point3fArray
"""
result["PointBased"].CreatePointsAttr.func_doc = """CreatePointsAttr(defaultValue, writeSparsely) -> Attribute
See GetPointsAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointBased"].GetVelocitiesAttr.func_doc = """GetVelocitiesAttr() -> Attribute
If provided,'velocities'should be used by renderers to.
compute positions between samples for the'points'attribute, rather
than interpolating between neighboring'points'samples. This is the
only reasonable means of computing motion blur for topologically
varying PointBased primitives. It follows that the length of
each'velocities'sample must match the length of the
corresponding'points'sample. Velocity is measured in position units
per second, as per most simulation software. To convert to position
units per UsdTimeCode, divide by UsdStage::GetTimeCodesPerSecond() .
See also Applying Timesampled Velocities to Geometry.
Declaration
``vector3f[] velocities``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Vector3fArray
"""
result["PointBased"].CreateVelocitiesAttr.func_doc = """CreateVelocitiesAttr(defaultValue, writeSparsely) -> Attribute
See GetVelocitiesAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointBased"].GetAccelerationsAttr.func_doc = """GetAccelerationsAttr() -> Attribute
If provided,'accelerations'should be used with velocities to compute
positions between samples for the'points'attribute rather than
interpolating between neighboring'points'samples.
Acceleration is measured in position units per second-squared. To
convert to position units per squared UsdTimeCode, divide by the
square of UsdStage::GetTimeCodesPerSecond() .
Declaration
``vector3f[] accelerations``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Vector3fArray
"""
result["PointBased"].CreateAccelerationsAttr.func_doc = """CreateAccelerationsAttr(defaultValue, writeSparsely) -> Attribute
See GetAccelerationsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointBased"].GetNormalsAttr.func_doc = """GetNormalsAttr() -> Attribute
Provide an object-space orientation for individual points, which,
depending on subclass, may define a surface, curve, or free points.
Note that'normals'should not be authored on any Mesh that is
subdivided, since the subdivision algorithm will define its own
normals.'normals'is not a generic primvar, but the number of elements
in this attribute will be determined by its'interpolation'. See
SetNormalsInterpolation() . If'normals'and'primvars:normals'are both
specified, the latter has precedence.
Declaration
``normal3f[] normals``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Normal3fArray
"""
result["PointBased"].CreateNormalsAttr.func_doc = """CreateNormalsAttr(defaultValue, writeSparsely) -> Attribute
See GetNormalsAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointBased"].GetNormalsInterpolation.func_doc = """GetNormalsInterpolation() -> str
Get the interpolation for the *normals* attribute.
Although'normals'is not classified as a generic UsdGeomPrimvar (and
will not be included in the results of
UsdGeomPrimvarsAPI::GetPrimvars() ) it does require an interpolation
specification. The fallback interpolation, if left unspecified, is
UsdGeomTokens->vertex, which will generally produce smooth shading on
a polygonal mesh. To achieve partial or fully faceted shading of a
polygonal mesh with normals, one should use UsdGeomTokens->faceVarying
or UsdGeomTokens->uniform interpolation.
"""
result["PointBased"].SetNormalsInterpolation.func_doc = """SetNormalsInterpolation(interpolation) -> bool
Set the interpolation for the *normals* attribute.
true upon success, false if ``interpolation`` is not a legal value as
defined by UsdGeomPrimvar::IsValidInterpolation() , or if there was a
problem setting the value. No attempt is made to validate that the
normals attr's value contains the right number of elements to match
its interpolation to its prim's topology.
GetNormalsInterpolation()
Parameters
----------
interpolation : str
"""
result["PointBased"].ComputePointsAtTime.func_doc = """**classmethod** ComputePointsAtTime(points, time, baseTime) -> bool
Compute points given the positions, velocities and accelerations at
``time`` .
This will return ``false`` and leave ``points`` untouched if:
- ``points`` is None
- one of ``time`` and ``baseTime`` is numeric and the other is
UsdTimeCode::Default() (they must either both be numeric or both be
default)
- there is no authored points attribute
If there is no error, we will return ``true`` and ``points`` will
contain the computed points.
points
\\- the out parameter for the new points. Its size will depend on the
authored data. time
\\- UsdTimeCode at which we want to evaluate the transforms baseTime
\\- required for correct interpolation between samples when *velocities*
or *accelerations* are present. If there are samples for *positions*
and *velocities* at t1 and t2, normal value resolution would attempt
to interpolate between the two samples, and if they could not be
interpolated because they differ in size (common in cases where
velocity is authored), will choose the sample at t1. When sampling for
the purposes of motion-blur, for example, it is common, when rendering
the frame at t2, to sample at [ t2-shutter/2, t2+shutter/2 ] for a
shutter interval of *shutter*. The first sample falls between t1 and
t2, but we must sample at t2 and apply velocity-based interpolation
based on those samples to get a correct result. In such scenarios, one
should provide a ``baseTime`` of t2 when querying *both* samples. If
your application does not care about off-sample interpolation, it can
supply the same value for ``baseTime`` that it does for ``time`` .
When ``baseTime`` is less than or equal to ``time`` , we will choose
the lower bracketing timeSample.
Parameters
----------
points : VtArray[Vec3f]
time : TimeCode
baseTime : TimeCode
----------------------------------------------------------------------
ComputePointsAtTime(points, stage, time, positions, velocities, velocitiesSampleTime, accelerations, velocityScale) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Perform the point computation.
This does the same computation as the non-static ComputePointsAtTime
method, but takes all data as parameters rather than accessing
authored data.
points
\\- the out parameter for the computed points. Its size will depend on
the given data. stage
\\- the UsdStage time
\\- time at which we want to evaluate the transforms positions
\\- array containing all current points. velocities
\\- array containing all velocities. This array must be either the same
size as ``positions`` or empty. If it is empty, points are computed as
if all velocities were zero in all dimensions. velocitiesSampleTime
\\- time at which the samples from ``velocities`` were taken.
accelerations
\\- array containing all accelerations. This array must be either the
same size as ``positions`` or empty. If it is empty, points are
computed as if all accelerations were zero in all dimensions.
velocityScale
\\- Deprecated
Parameters
----------
points : VtArray[Vec3f]
stage : UsdStageWeak
time : TimeCode
positions : Vec3fArray
velocities : Vec3fArray
velocitiesSampleTime : TimeCode
accelerations : Vec3fArray
velocityScale : float
"""
result["PointBased"].ComputePointsAtTimes.func_doc = """ComputePointsAtTimes(pointsArray, times, baseTime) -> bool
Compute points as in ComputePointsAtTime, but using multiple sample
times.
An array of vector arrays is returned where each vector array contains
the points for the corresponding time in ``times`` .
times
\\- A vector containing the UsdTimeCodes at which we want to sample.
Parameters
----------
pointsArray : list[VtArray[Vec3f]]
times : list[TimeCode]
baseTime : TimeCode
"""
result["PointBased"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["PointBased"].Get.func_doc = """**classmethod** Get(stage, path) -> PointBased
Return a UsdGeomPointBased holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomPointBased(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["PointBased"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(points, extent) -> bool
Compute the extent for the point cloud defined by points.
true on success, false if extents was unable to be calculated. On
success, extent will contain the axis-aligned bounding box of the
point cloud defined by points.
This function is to provide easy authoring of extent for usd authoring
tools, hence it is static and acts outside a specific prim (as in
attribute based methods).
Parameters
----------
points : Vec3fArray
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtent(points, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
points : Vec3fArray
transform : Matrix4d
extent : Vec3fArray
"""
result["PointBased"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["PointInstancer"].__doc__ = """
Encodes vectorized instancing of multiple, potentially animated,
prototypes (object/instance masters), which can be arbitrary
prims/subtrees on a UsdStage.
PointInstancer is a"multi instancer", as it allows multiple prototypes
to be scattered among its"points". We use a UsdRelationship
*prototypes* to identify and order all of the possible prototypes, by
targeting the root prim of each prototype. The ordering imparted by
relationships associates a zero-based integer with each prototype, and
it is these integers we use to identify the prototype of each
instance, compactly, and allowing prototypes to be swapped out without
needing to reauthor all of the per-instance data.
The PointInstancer schema is designed to scale to billions of
instances, which motivates the choice to split the per-instance
transformation into position, (quaternion) orientation, and scales,
rather than a 4x4 matrix per-instance. In addition to requiring fewer
bytes even if all elements are authored (32 bytes vs 64 for a single-
precision 4x4 matrix), we can also be selective about which attributes
need to animate over time, for substantial data reduction in many
cases.
Note that PointInstancer is *not* a Gprim, since it is not a graphical
primitive by any stretch of the imagination. It *is*, however,
Boundable, since we will sometimes want to treat the entire
PointInstancer similarly to a procedural, from the perspective of
inclusion or framing.
Varying Instance Identity over Time
===================================
PointInstancers originating from simulations often have the
characteristic that points/instances are"born", move around for some
time period, and then die (or leave the area of interest). In such
cases, billions of instances may be birthed over time, while at any
*specific* time, only a much smaller number are actually alive. To
encode this situation efficiently, the simulator may re-use indices in
the instance arrays, when a particle dies, its index will be taken
over by a new particle that may be birthed in a much different
location. This presents challenges both for identity-tracking, and for
motion-blur.
We facilitate identity tracking by providing an optional, animatable
*ids* attribute, that specifies the 64 bit integer ID of the particle
at each index, at each point in time. If the simulator keeps
monotonically increasing a particle-count each time a new particle is
birthed, it will serve perfectly as particle *ids*.
We facilitate motion blur for varying-topology particle streams by
optionally allowing per-instance *velocities* and *angularVelocities*
to be authored. If instance transforms are requested at a time between
samples and either of the velocity attributes is authored, then we
will not attempt to interpolate samples of *positions* or
*orientations*. If not authored, and the bracketing samples have the
same length, then we will interpolate.
Computing an Instance Transform
===============================
Each instance's transformation is a combination of the SRT affine
transform described by its scale, orientation, and position, applied
*after* (i.e. less locally) than the transformation computed at the
root of the prototype it is instancing. In other words, to put an
instance of a PointInstancer into the space of the PointInstancer's
parent prim:
- Apply (most locally) the authored transformation for
*prototypes[protoIndices[i]]*
- If *scales* is authored, next apply the scaling matrix from
*scales[i]*
- If *orientations* is authored: **if *angularVelocities* is
authored**, first multiply *orientations[i]* by the unit quaternion
derived by scaling *angularVelocities[i]* by the time differential
from the left-bracketing timeSample for *orientation* to the requested
evaluation time *t*, storing the result in *R*, **else** assign *R*
directly from *orientations[i]*. Apply the rotation matrix derived
from *R*.
- Apply the translation derived from *positions[i]*. If
*velocities* is authored, apply the translation deriving from
*velocities[i]* scaled by the time differential from the left-
bracketing timeSample for *positions* to the requested evaluation time
*t*.
- Least locally, apply the transformation authored on the
PointInstancer prim itself (or the
UsdGeomImageable::ComputeLocalToWorldTransform() of the PointInstancer
to put the instance directly into world space)
If neither *velocities* nor *angularVelocities* are authored, we
fallback to standard position and orientation computation logic (using
linear interpolation between timeSamples) as described by Applying
Timesampled Velocities to Geometry.
**Scaling Velocities for Interpolation**
When computing time-differentials by which to apply velocity or
angularVelocity to positions or orientations, we must scale by ( 1.0 /
UsdStage::GetTimeCodesPerSecond() ), because velocities are recorded
in units/second, while we are interpolating in UsdTimeCode ordinates.
We provide both high and low-level API's for dealing with the
transformation as a matrix, both will compute the instance matrices
using multiple threads; the low-level API allows the client to cache
unvarying inputs so that they need not be read duplicately when
computing over time.
See also Applying Timesampled Velocities to Geometry.
Primvars on PointInstancer
==========================
Primvars authored on a PointInstancer prim should always be applied to
each instance with *constant* interpolation at the root of the
instance. When you are authoring primvars on a PointInstancer, think
about it as if you were authoring them on a point-cloud (e.g. a
UsdGeomPoints gprim). The same interpolation rules for points apply
here, substituting"instance"for"point".
In other words, the (constant) value extracted for each instance from
the authored primvar value depends on the authored *interpolation* and
*elementSize* of the primvar, as follows:
- **constant** or **uniform** : the entire authored value of the
primvar should be applied exactly to each instance.
- **varying**, **vertex**, or **faceVarying** : the first
*elementSize* elements of the authored primvar array should be
assigned to instance zero, the second *elementSize* elements should be
assigned to instance one, and so forth.
Masking Instances:"Deactivating"and Invising
============================================
Often a PointInstancer is created"upstream"in a graphics pipeline, and
the needs of"downstream"clients necessitate eliminating some of the
instances from further consideration. Accomplishing this pruning by
re-authoring all of the per-instance attributes is not very
attractive, since it may mean destructively editing a large quantity
of data. We therefore provide means of"masking"instances by ID, such
that the instance data is unmolested, but per-instance transform and
primvar data can be retrieved with the no-longer-desired instances
eliminated from the (smaller) arrays. PointInstancer allows two
independent means of masking instances by ID, each with different
features that meet the needs of various clients in a pipeline. Both
pruning features'lists of ID's are combined to produce the mask
returned by ComputeMaskAtTime() .
If a PointInstancer has no authored *ids* attribute, the masking
features will still be available, with the integers specifying element
position in the *protoIndices* array rather than ID.
The first masking feature encodes a list of IDs in a list-editable
metadatum called *inactiveIds*, which, although it does not have any
similar impact to stage population as prim activation, it shares with
that feature that its application is uniform over all time. Because it
is list-editable, we can *sparsely* add and remove instances from it
in many layers.
This sparse application pattern makes *inactiveIds* a good choice when
further downstream clients may need to reverse masking decisions made
upstream, in a manner that is robust to many kinds of future changes
to the upstream data.
See ActivateId() , ActivateIds() , DeactivateId() , DeactivateIds() ,
ActivateAllIds()
The second masking feature encodes a list of IDs in a time-varying
Int64Array-valued UsdAttribute called *invisibleIds*, since it shares
with Imageable visibility the ability to animate object visibility.
Unlike *inactiveIds*, overriding a set of opinions for *invisibleIds*
is not at all straightforward, because one will, in general need to
reauthor (in the overriding layer) **all** timeSamples for the
attribute just to change one Id's visibility state, so it cannot be
authored sparsely. But it can be a very useful tool for situations
like encoding pre-computed camera-frustum culling of geometry when
either or both of the instances or the camera is animated.
See VisId() , VisIds() , InvisId() , InvisIds() , VisAllIds()
Processing and Not Processing Prototypes
========================================
Any prim in the scenegraph can be targeted as a prototype by the
*prototypes* relationship. We do not, however, provide a specific
mechanism for identifying prototypes as geometry that should not be
drawn (or processed) in their own, local spaces in the scenegraph. We
encourage organizing all prototypes as children of the PointInstancer
prim that consumes them, and pruning"raw"processing and drawing
traversals when they encounter a PointInstancer prim; this is what the
UsdGeomBBoxCache and UsdImaging engines do.
There *is* a pattern one can deploy for organizing the prototypes such
that they will automatically be skipped by basic
UsdPrim::GetChildren() or UsdPrimRange traversals. Usd prims each have
a specifier of"def","over", or"class". The default traversals skip
over prims that are"pure overs"or classes. So to protect prototypes
from all generic traversals and processing, place them under a prim
that is just an"over". For example,
.. code-block:: text
01 def PointInstancer "Crowd_Mid"
02 {
03 rel prototypes = [ </Crowd_Mid/Prototypes/MaleThin_Business>, </Crowd_Mid/Prototypes/MaleThin_Casual> ]
04
05 over "Prototypes"
06 {
07 def "MaleThin_Business" (
08 references = [@MaleGroupA/usd/MaleGroupA.usd@</MaleGroupA>]
09 variants = {
10 string modelingVariant = "Thin"
11 string costumeVariant = "BusinessAttire"
12 }
13 )
14 { \\.\\.\\. }
15
16 def "MaleThin_Casual"
17 \\.\\.\\.
18 }
19 }
"""
result["PointInstancer"].ActivateId.func_doc = """ActivateId(id) -> bool
Ensure that the instance identified by ``id`` is active over all time.
This activation is encoded sparsely, affecting no other instances.
This does not guarantee that the instance will be rendered, because it
may still be"invisible"due to ``id`` being present in the
*invisibleIds* attribute (see VisId() , InvisId() )
Parameters
----------
id : int
"""
result["PointInstancer"].ActivateIds.func_doc = """ActivateIds(ids) -> bool
Ensure that the instances identified by ``ids`` are active over all
time.
This activation is encoded sparsely, affecting no other instances.
This does not guarantee that the instances will be rendered, because
each may still be"invisible"due to its presence in the *invisibleIds*
attribute (see VisId() , InvisId() )
Parameters
----------
ids : Int64Array
"""
result["PointInstancer"].ActivateAllIds.func_doc = """ActivateAllIds() -> bool
Ensure that all instances are active over all time.
This does not guarantee that the instances will be rendered, because
each may still be"invisible"due to its presence in the *invisibleIds*
attribute (see VisId() , InvisId() )
"""
result["PointInstancer"].DeactivateId.func_doc = """DeactivateId(id) -> bool
Ensure that the instance identified by ``id`` is inactive over all
time.
This deactivation is encoded sparsely, affecting no other instances.
A deactivated instance is guaranteed not to render if the renderer
honors masking.
Parameters
----------
id : int
"""
result["PointInstancer"].DeactivateIds.func_doc = """DeactivateIds(ids) -> bool
Ensure that the instances identified by ``ids`` are inactive over all
time.
This deactivation is encoded sparsely, affecting no other instances.
A deactivated instance is guaranteed not to render if the renderer
honors masking.
Parameters
----------
ids : Int64Array
"""
result["PointInstancer"].VisId.func_doc = """VisId(id, time) -> bool
Ensure that the instance identified by ``id`` is visible at ``time`` .
This will cause *invisibleIds* to first be broken down (keyed) at
``time`` , causing all animation in weaker layers that the current
UsdEditTarget to be overridden. Has no effect on any timeSamples other
than the one at ``time`` . If the *invisibleIds* attribute is not
authored or is blocked, this operation is a no-op.
This does not guarantee that the instance will be rendered, because it
may still be"inactive"due to ``id`` being present in the
*inactivevIds* metadata (see ActivateId() , DeactivateId() )
Parameters
----------
id : int
time : TimeCode
"""
result["PointInstancer"].VisIds.func_doc = """VisIds(ids, time) -> bool
Ensure that the instances identified by ``ids`` are visible at
``time`` .
This will cause *invisibleIds* to first be broken down (keyed) at
``time`` , causing all animation in weaker layers that the current
UsdEditTarget to be overridden. Has no effect on any timeSamples other
than the one at ``time`` . If the *invisibleIds* attribute is not
authored or is blocked, this operation is a no-op.
This does not guarantee that the instances will be rendered, because
each may still be"inactive"due to ``id`` being present in the
*inactivevIds* metadata (see ActivateId() , DeactivateId() )
Parameters
----------
ids : Int64Array
time : TimeCode
"""
result["PointInstancer"].VisAllIds.func_doc = """VisAllIds(time) -> bool
Ensure that all instances are visible at ``time`` .
Operates by authoring an empty array at ``time`` .
This does not guarantee that the instances will be rendered, because
each may still be"inactive"due to its id being present in the
*inactivevIds* metadata (see ActivateId() , DeactivateId() )
Parameters
----------
time : TimeCode
"""
result["PointInstancer"].InvisId.func_doc = """InvisId(id, time) -> bool
Ensure that the instance identified by ``id`` is invisible at ``time``
.
This will cause *invisibleIds* to first be broken down (keyed) at
``time`` , causing all animation in weaker layers that the current
UsdEditTarget to be overridden. Has no effect on any timeSamples other
than the one at ``time`` .
An invised instance is guaranteed not to render if the renderer honors
masking.
Parameters
----------
id : int
time : TimeCode
"""
result["PointInstancer"].InvisIds.func_doc = """InvisIds(ids, time) -> bool
Ensure that the instances identified by ``ids`` are invisible at
``time`` .
This will cause *invisibleIds* to first be broken down (keyed) at
``time`` , causing all animation in weaker layers that the current
UsdEditTarget to be overridden. Has no effect on any timeSamples other
than the one at ``time`` .
An invised instance is guaranteed not to render if the renderer honors
masking.
Parameters
----------
ids : Int64Array
time : TimeCode
"""
result["PointInstancer"].ComputeMaskAtTime.func_doc = """ComputeMaskAtTime(time, ids) -> list[bool]
Computes a presence mask to be applied to per-instance data arrays
based on authored *inactiveIds*, *invisibleIds*, and *ids*.
If no *ids* attribute has been authored, then the values in
*inactiveIds* and *invisibleIds* will be interpreted directly as
indices of *protoIndices*.
If ``ids`` is non-None, it is assumed to be the id-mapping to apply,
and must match the length of *protoIndices* at ``time`` . If None, we
will call GetIdsAttr() .Get(time)
If all"live"instances at UsdTimeCode ``time`` pass the mask, we will
return an **empty** mask so that clients can trivially recognize the
common"no masking"case. The returned mask can be used with
ApplyMaskToArray() , and will contain a ``true`` value for every
element that should survive.
Parameters
----------
time : TimeCode
ids : Int64Array
"""
result["PointInstancer"].ProtoXformInclusion.__doc__ = """
Encodes whether to include each prototype's root prim's transformation
as the most-local component of computed instance transforms.
"""
result["PointInstancer"].MaskApplication.__doc__ = """
Encodes whether to evaluate and apply the PointInstancer's mask to
computed results.
ComputeMaskAtTime()
"""
result["PointInstancer"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomPointInstancer on UsdPrim ``prim`` .
Equivalent to UsdGeomPointInstancer::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomPointInstancer on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomPointInstancer (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["PointInstancer"].GetProtoIndicesAttr.func_doc = """GetProtoIndicesAttr() -> Attribute
**Required property**.
Per-instance index into *prototypes* relationship that identifies what
geometry should be drawn for each instance. **Topology attribute** -
can be animated, but at a potential performance impact for streaming.
Declaration
``int[] protoIndices``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["PointInstancer"].CreateProtoIndicesAttr.func_doc = """CreateProtoIndicesAttr(defaultValue, writeSparsely) -> Attribute
See GetProtoIndicesAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointInstancer"].GetIdsAttr.func_doc = """GetIdsAttr() -> Attribute
Ids are optional; if authored, the ids array should be the same length
as the *protoIndices* array, specifying (at each timeSample if
instance identities are changing) the id of each instance.
The type is signed intentionally, so that clients can encode some
binary state on Id'd instances without adding a separate primvar. See
also Varying Instance Identity over Time
Declaration
``int64[] ids``
C++ Type
VtArray<int64_t>
Usd Type
SdfValueTypeNames->Int64Array
"""
result["PointInstancer"].CreateIdsAttr.func_doc = """CreateIdsAttr(defaultValue, writeSparsely) -> Attribute
See GetIdsAttr() , and also Create vs Get Property Methods for when to
use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointInstancer"].GetPositionsAttr.func_doc = """GetPositionsAttr() -> Attribute
**Required property**.
Per-instance position. See also Computing an Instance Transform.
Declaration
``point3f[] positions``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Point3fArray
"""
result["PointInstancer"].CreatePositionsAttr.func_doc = """CreatePositionsAttr(defaultValue, writeSparsely) -> Attribute
See GetPositionsAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointInstancer"].GetOrientationsAttr.func_doc = """GetOrientationsAttr() -> Attribute
If authored, per-instance orientation of each instance about its
prototype's origin, represented as a unit length quaternion, which
allows us to encode it with sufficient precision in a compact GfQuath.
It is client's responsibility to ensure that authored quaternions are
unit length; the convenience API below for authoring orientations from
rotation matrices will ensure that quaternions are unit length, though
it will not make any attempt to select the"better (for
interpolationwith respect to neighboring samples)"of the two possible
quaternions that encode the rotation.
See also Computing an Instance Transform.
Declaration
``quath[] orientations``
C++ Type
VtArray<GfQuath>
Usd Type
SdfValueTypeNames->QuathArray
"""
result["PointInstancer"].CreateOrientationsAttr.func_doc = """CreateOrientationsAttr(defaultValue, writeSparsely) -> Attribute
See GetOrientationsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointInstancer"].GetScalesAttr.func_doc = """GetScalesAttr() -> Attribute
If authored, per-instance scale to be applied to each instance, before
any rotation is applied.
See also Computing an Instance Transform.
Declaration
``float3[] scales``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Float3Array
"""
result["PointInstancer"].CreateScalesAttr.func_doc = """CreateScalesAttr(defaultValue, writeSparsely) -> Attribute
See GetScalesAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointInstancer"].GetVelocitiesAttr.func_doc = """GetVelocitiesAttr() -> Attribute
If provided, per-instance'velocities'will be used to compute positions
between samples for the'positions'attribute, rather than interpolating
between neighboring'positions'samples.
Velocities should be considered mandatory if both *protoIndices* and
*positions* are animated. Velocity is measured in position units per
second, as per most simulation software. To convert to position units
per UsdTimeCode, divide by UsdStage::GetTimeCodesPerSecond() .
See also Computing an Instance Transform, Applying Timesampled
Velocities to Geometry.
Declaration
``vector3f[] velocities``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Vector3fArray
"""
result["PointInstancer"].CreateVelocitiesAttr.func_doc = """CreateVelocitiesAttr(defaultValue, writeSparsely) -> Attribute
See GetVelocitiesAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointInstancer"].GetAccelerationsAttr.func_doc = """GetAccelerationsAttr() -> Attribute
If authored, per-instance'accelerations'will be used with velocities
to compute positions between samples for the'positions'attribute
rather than interpolating between neighboring'positions'samples.
Acceleration is measured in position units per second-squared. To
convert to position units per squared UsdTimeCode, divide by the
square of UsdStage::GetTimeCodesPerSecond() .
Declaration
``vector3f[] accelerations``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Vector3fArray
"""
result["PointInstancer"].CreateAccelerationsAttr.func_doc = """CreateAccelerationsAttr(defaultValue, writeSparsely) -> Attribute
See GetAccelerationsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointInstancer"].GetAngularVelocitiesAttr.func_doc = """GetAngularVelocitiesAttr() -> Attribute
If authored, per-instance angular velocity vector to be used for
interoplating orientations.
Angular velocities should be considered mandatory if both
*protoIndices* and *orientations* are animated. Angular velocity is
measured in **degrees** per second. To convert to degrees per
UsdTimeCode, divide by UsdStage::GetTimeCodesPerSecond() .
See also Computing an Instance Transform.
Declaration
``vector3f[] angularVelocities``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Vector3fArray
"""
result["PointInstancer"].CreateAngularVelocitiesAttr.func_doc = """CreateAngularVelocitiesAttr(defaultValue, writeSparsely) -> Attribute
See GetAngularVelocitiesAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointInstancer"].GetInvisibleIdsAttr.func_doc = """GetInvisibleIdsAttr() -> Attribute
A list of id's to make invisible at the evaluation time.
See invisibleIds: Animatable Masking.
Declaration
``int64[] invisibleIds = []``
C++ Type
VtArray<int64_t>
Usd Type
SdfValueTypeNames->Int64Array
"""
result["PointInstancer"].CreateInvisibleIdsAttr.func_doc = """CreateInvisibleIdsAttr(defaultValue, writeSparsely) -> Attribute
See GetInvisibleIdsAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["PointInstancer"].GetPrototypesRel.func_doc = """GetPrototypesRel() -> Relationship
**Required property**.
Orders and targets the prototype root prims, which can be located
anywhere in the scenegraph that is convenient, although we promote
organizing prototypes as children of the PointInstancer. The position
of a prototype in this relationship defines the value an instance
would specify in the *protoIndices* attribute to instance that
prototype. Since relationships are uniform, this property cannot be
animated.
"""
result["PointInstancer"].CreatePrototypesRel.func_doc = """CreatePrototypesRel() -> Relationship
See GetPrototypesRel() , and also Create vs Get Property Methods for
when to use Get vs Create.
"""
result["PointInstancer"].ComputeInstanceTransformsAtTime.func_doc = """**classmethod** ComputeInstanceTransformsAtTime(xforms, time, baseTime, doProtoXforms, applyMask) -> bool
Compute the per-instance,"PointInstancer relative"transforms given the
positions, scales, orientations, velocities and angularVelocities at
``time`` , as described in Computing an Instance Transform.
This will return ``false`` and leave ``xforms`` untouched if:
- ``xforms`` is None
- one of ``time`` and ``baseTime`` is numeric and the other is
UsdTimeCode::Default() (they must either both be numeric or both be
default)
- there is no authored *protoIndices* attribute or *positions*
attribute
- the size of any of the per-instance attributes does not match the
size of *protoIndices*
- ``doProtoXforms`` is ``IncludeProtoXform`` but an index value in
*protoIndices* is outside the range [0, prototypes.size())
- ``applyMask`` is ``ApplyMask`` and a mask is set but the size of
the mask does not match the size of *protoIndices*.
If there is no error, we will return ``true`` and ``xforms`` will
contain the computed transformations.
xforms
\\- the out parameter for the transformations. Its size will depend on
the authored data and ``applyMask`` time
\\- UsdTimeCode at which we want to evaluate the transforms baseTime
\\- required for correct interpolation between samples when *velocities*
or *angularVelocities* are present. If there are samples for
*positions* and *velocities* at t1 and t2, normal value resolution
would attempt to interpolate between the two samples, and if they
could not be interpolated because they differ in size (common in cases
where velocity is authored), will choose the sample at t1. When
sampling for the purposes of motion-blur, for example, it is common,
when rendering the frame at t2, to sample at [ t2-shutter/2,
t2+shutter/2 ] for a shutter interval of *shutter*. The first sample
falls between t1 and t2, but we must sample at t2 and apply velocity-
based interpolation based on those samples to get a correct result. In
such scenarios, one should provide a ``baseTime`` of t2 when querying
*both* samples. If your application does not care about off-sample
interpolation, it can supply the same value for ``baseTime`` that it
does for ``time`` . When ``baseTime`` is less than or equal to
``time`` , we will choose the lower bracketing timeSample. Selecting
sample times with respect to baseTime will be performed independently
for positions and orientations. doProtoXforms
\\- specifies whether to include the root transformation of each
instance's prototype in the instance's transform. Default is to
include it, but some clients may want to apply the proto transform as
part of the prototype itself, so they can specify
``ExcludeProtoXform`` instead. applyMask
\\- specifies whether to apply ApplyMaskToArray() to the computed
result. The default is ``ApplyMask`` .
Parameters
----------
xforms : VtArray[Matrix4d]
time : TimeCode
baseTime : TimeCode
doProtoXforms : ProtoXformInclusion
applyMask : MaskApplication
----------------------------------------------------------------------
ComputeInstanceTransformsAtTime(xforms, stage, time, protoIndices, positions, velocities, velocitiesSampleTime, accelerations, scales, orientations, angularVelocities, angularVelocitiesSampleTime, protoPaths, mask, velocityScale) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Perform the per-instance transform computation as described in
Computing an Instance Transform.
This does the same computation as the non-static
ComputeInstanceTransformsAtTime method, but takes all data as
parameters rather than accessing authored data.
xforms
\\- the out parameter for the transformations. Its size will depend on
the given data and ``applyMask`` stage
\\- the UsdStage time
\\- time at which we want to evaluate the transforms protoIndices
\\- array containing all instance prototype indices. positions
\\- array containing all instance positions. This array must be the same
size as ``protoIndices`` . velocities
\\- array containing all instance velocities. This array must be either
the same size as ``protoIndices`` or empty. If it is empty, transforms
are computed as if all velocities were zero in all dimensions.
velocitiesSampleTime
\\- time at which the samples from ``velocities`` were taken.
accelerations
\\- array containing all instance accelerations. This array must be
either the same size as ``protoIndicesor`` empty. If it is empty,
transforms are computed as if all accelerations were zero in all
dimensions. scales
\\- array containing all instance scales. This array must be either the
same size as ``protoIndices`` or empty. If it is empty, transforms are
computed with no change in scale. orientations
\\- array containing all instance orientations. This array must be
either the same size as ``protoIndices`` or empty. If it is empty,
transforms are computed with no change in orientation
angularVelocities
\\- array containing all instance angular velocities. This array must be
either the same size as ``protoIndices`` or empty. If it is empty,
transforms are computed as if all angular velocities were zero in all
dimensions. angularVelocitiesSampleTime
\\- time at which the samples from ``angularVelocities`` were taken.
protoPaths
\\- array containing the paths for all instance prototypes. If this
array is not empty, prototype transforms are applied to the instance
transforms. mask
\\- vector containing a mask to apply to the computed result. This
vector must be either the same size as ``protoIndices`` or empty. If
it is empty, no mask is applied. velocityScale
\\- Deprecated
Parameters
----------
xforms : VtArray[Matrix4d]
stage : UsdStageWeak
time : TimeCode
protoIndices : IntArray
positions : Vec3fArray
velocities : Vec3fArray
velocitiesSampleTime : TimeCode
accelerations : Vec3fArray
scales : Vec3fArray
orientations : QuathArray
angularVelocities : Vec3fArray
angularVelocitiesSampleTime : TimeCode
protoPaths : list[SdfPath]
mask : list[bool]
velocityScale : float
"""
result["PointInstancer"].ComputeInstanceTransformsAtTimes.func_doc = """ComputeInstanceTransformsAtTimes(xformsArray, times, baseTime, doProtoXforms, applyMask) -> bool
Compute the per-instance transforms as in
ComputeInstanceTransformsAtTime, but using multiple sample times.
An array of matrix arrays is returned where each matrix array contains
the instance transforms for the corresponding time in ``times`` .
times
\\- A vector containing the UsdTimeCodes at which we want to sample.
Parameters
----------
xformsArray : list[VtArray[Matrix4d]]
times : list[TimeCode]
baseTime : TimeCode
doProtoXforms : ProtoXformInclusion
applyMask : MaskApplication
"""
result["PointInstancer"].ComputeExtentAtTime.func_doc = """ComputeExtentAtTime(extent, time, baseTime) -> bool
Compute the extent of the point instancer based on the per-
instance,"PointInstancer relative"transforms at ``time`` , as
described in Computing an Instance Transform.
If there is no error, we return ``true`` and ``extent`` will be the
tightest bounds we can compute efficiently. If an error occurs,
``false`` will be returned and ``extent`` will be left untouched.
For now, this uses a UsdGeomBBoxCache with the"default","proxy",
and"render"purposes.
extent
\\- the out parameter for the extent. On success, it will contain two
elements representing the min and max. time
\\- UsdTimeCode at which we want to evaluate the extent baseTime
\\- required for correct interpolation between samples when *velocities*
or *angularVelocities* are present. If there are samples for
*positions* and *velocities* at t1 and t2, normal value resolution
would attempt to interpolate between the two samples, and if they
could not be interpolated because they differ in size (common in cases
where velocity is authored), will choose the sample at t1. When
sampling for the purposes of motion-blur, for example, it is common,
when rendering the frame at t2, to sample at [ t2-shutter/2,
t2+shutter/2 ] for a shutter interval of *shutter*. The first sample
falls between t1 and t2, but we must sample at t2 and apply velocity-
based interpolation based on those samples to get a correct result. In
such scenarios, one should provide a ``baseTime`` of t2 when querying
*both* samples. If your application does not care about off-sample
interpolation, it can supply the same value for ``baseTime`` that it
does for ``time`` . When ``baseTime`` is less than or equal to
``time`` , we will choose the lower bracketing timeSample.
Parameters
----------
extent : Vec3fArray
time : TimeCode
baseTime : TimeCode
----------------------------------------------------------------------
ComputeExtentAtTime(extent, time, baseTime, transform) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
extent : Vec3fArray
time : TimeCode
baseTime : TimeCode
transform : Matrix4d
"""
result["PointInstancer"].ComputeExtentAtTimes.func_doc = """ComputeExtentAtTimes(extents, times, baseTime) -> bool
Compute the extent of the point instancer as in ComputeExtentAtTime,
but across multiple ``times`` .
This is equivalent to, but more efficient than, calling
ComputeExtentAtTime several times. Each element in ``extents`` is the
computed extent at the corresponding time in ``times`` .
As in ComputeExtentAtTime, if there is no error, we return ``true``
and ``extents`` will be the tightest bounds we can compute
efficiently. If an error occurs computing the extent at any time,
``false`` will be returned and ``extents`` will be left untouched.
times
\\- A vector containing the UsdTimeCodes at which we want to sample.
Parameters
----------
extents : list[Vec3fArray]
times : list[TimeCode]
baseTime : TimeCode
----------------------------------------------------------------------
ComputeExtentAtTimes(extents, times, baseTime, transform) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied
at each time.
Parameters
----------
extents : list[Vec3fArray]
times : list[TimeCode]
baseTime : TimeCode
transform : Matrix4d
"""
result["PointInstancer"].GetInstanceCount.func_doc = """GetInstanceCount(timeCode) -> int
Returns the number of instances as defined by the size of the
*protoIndices* array at *timeCode*.
For most code, this check will be performant. When using file formats
where the cost of attribute reading is high and the time sampled array
will be read into memory later, it may be better to explicitly read
the value once and check the size of the array directly.
GetProtoIndicesAttr()
Parameters
----------
timeCode : TimeCode
"""
result["PointInstancer"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["PointInstancer"].Get.func_doc = """**classmethod** Get(stage, path) -> PointInstancer
Return a UsdGeomPointInstancer holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomPointInstancer(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["PointInstancer"].Define.func_doc = """**classmethod** Define(stage, path) -> PointInstancer
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["PointInstancer"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Points"].__doc__ = """
Points are analogous to the RiPoints spec.
Points can be an efficient means of storing and rendering particle
effects comprised of thousands or millions of small particles. Points
generally receive a single shading sample each, which should take
*normals* into account, if present.
While not technically UsdGeomPrimvars, the widths and normals also
have interpolation metadata. It's common for authored widths and
normals to have constant or varying interpolation.
"""
result["Points"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomPoints on UsdPrim ``prim`` .
Equivalent to UsdGeomPoints::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomPoints on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomPoints (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Points"].GetWidthsAttr.func_doc = """GetWidthsAttr() -> Attribute
Widths are defined as the *diameter* of the points, in object space.
'widths'is not a generic Primvar, but the number of elements in this
attribute will be determined by its'interpolation'. See
SetWidthsInterpolation() . If'widths'and'primvars:widths'are both
specified, the latter has precedence.
Declaration
``float[] widths``
C++ Type
VtArray<float>
Usd Type
SdfValueTypeNames->FloatArray
"""
result["Points"].CreateWidthsAttr.func_doc = """CreateWidthsAttr(defaultValue, writeSparsely) -> Attribute
See GetWidthsAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Points"].GetIdsAttr.func_doc = """GetIdsAttr() -> Attribute
Ids are optional; if authored, the ids array should be the same length
as the points array, specifying (at each timesample if point
identities are changing) the id of each point.
The type is signed intentionally, so that clients can encode some
binary state on Id'd points without adding a separate primvar.
Declaration
``int64[] ids``
C++ Type
VtArray<int64_t>
Usd Type
SdfValueTypeNames->Int64Array
"""
result["Points"].CreateIdsAttr.func_doc = """CreateIdsAttr(defaultValue, writeSparsely) -> Attribute
See GetIdsAttr() , and also Create vs Get Property Methods for when to
use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Points"].GetWidthsInterpolation.func_doc = """GetWidthsInterpolation() -> str
Get the interpolation for the *widths* attribute.
Although'widths'is not classified as a generic UsdGeomPrimvar (and
will not be included in the results of
UsdGeomPrimvarsAPI::GetPrimvars() ) it does require an interpolation
specification. The fallback interpolation, if left unspecified, is
UsdGeomTokens->vertex, which means a width value is specified for each
point.
"""
result["Points"].SetWidthsInterpolation.func_doc = """SetWidthsInterpolation(interpolation) -> bool
Set the interpolation for the *widths* attribute.
true upon success, false if ``interpolation`` is not a legal value as
defined by UsdPrimvar::IsValidInterpolation(), or if there was a
problem setting the value. No attempt is made to validate that the
widths attr's value contains the right number of elements to match its
interpolation to its prim's topology.
GetWidthsInterpolation()
Parameters
----------
interpolation : str
"""
result["Points"].GetPointCount.func_doc = """GetPointCount(timeCode) -> int
Returns the number of points as defined by the size of the *points*
array at *timeCode*.
For most code, this check will be performant. When using file formats
where the cost of attribute reading is high and the time sampled array
will be read into memory later, it may be better to explicitly read
the value once and check the size of the array directly.
GetPointsAttr()
Parameters
----------
timeCode : TimeCode
"""
result["Points"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Points"].Get.func_doc = """**classmethod** Get(stage, path) -> Points
Return a UsdGeomPoints holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomPoints(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Points"].Define.func_doc = """**classmethod** Define(stage, path) -> Points
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Points"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(points, widths, extent) -> bool
Compute the extent for the point cloud defined by points and widths.
true upon success, false if widths and points are different sized
arrays. On success, extent will contain the axis-aligned bounding box
of the point cloud defined by points with the given widths.
This function is to provide easy authoring of extent for usd authoring
tools, hence it is static and acts outside a specific prim (as in
attribute based methods).
Parameters
----------
points : Vec3fArray
widths : FloatArray
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtent(points, widths, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
points : Vec3fArray
widths : FloatArray
transform : Matrix4d
extent : Vec3fArray
"""
result["Points"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Primvar"].__doc__ = """
Schema wrapper for UsdAttribute for authoring and introspecting
attributes that are primvars.
UsdGeomPrimvar provides API for authoring and retrieving the
additional data required to encode an attribute as a"Primvar", which
is a convenient contraction of RenderMan's"Primitive Variable"concept,
which is represented in Alembic as"arbitrary geometry
parameters"(arbGeomParams).
This includes the attribute's interpolation across the primitive
(which RenderMan refers to as its class specifier and Alembic as its
"geometry scope" ); it also includes the attribute's elementSize,
which states how many values in the value array must be aggregated for
each element on the primitive. An attribute's TypeName also factors
into the encoding of Primvar.
What is the Purpose of a Primvar?
=================================
There are three key aspects of Primvar identity:
- Primvars define a value that can vary across the primitive on
which they are defined, via prescribed interpolation rules
- Taken collectively on a prim, its Primvars describe the"per-
primitiveoverrides"to the material to which the prim is bound.
Different renderers may communicate the variables to the shaders using
different mechanisms over which Usd has no control; Primvars simply
provide the classification that any renderer should use to locate
potential overrides. Do please note that primvars override parameters
on UsdShadeShader objects, *not* Interface Attributes on
UsdShadeMaterial prims.
- *Primvars inherit down scene namespace.* Regular USD attributes
only apply to the prim on which they are specified, but primvars
implicitly also apply to any child prims, unless those child prims
have their own opinions about those primvars. This capability
necessarily entails added cost to check for inherited values, but the
benefit is that it allows concise encoding of certain opinions that
broadly affect large amounts of geometry. See
UsdGeomImageable::FindInheritedPrimvars().
Creating and Accessing Primvars
===============================
The UsdGeomPrimvarsAPI schema provides a complete interface for
creating and querying prims for primvars.
The **only** way to create a new Primvar in scene description is by
calling UsdGeomPrimvarsAPI::CreatePrimvar() . One
cannot"enhance"or"promote"an already existing attribute into a
Primvar, because doing so may require a namespace edit to rename the
attribute, which cannot, in general, be done within a single
UsdEditContext. Instead, create a new UsdGeomPrimvar of the desired
name using UsdGeomPrimvarsAPI::CreatePrimvar() , and then copy the
existing attribute onto the new UsdGeomPrimvar.
Primvar names can contain arbitrary sub-namespaces. The behavior of
UsdGeomImageable::GetPrimvar(TfToken const & name) is to
prepend"primvars:"onto'name'if it is not already a prefix, and return
the result, which means we do not have any ambiguity between the
primvars"primvars:nsA:foo"and"primvars:nsB:foo". **There are reserved
keywords that may not be used as the base names of primvars,** and
attempting to create Primvars of these names will result in a coding
error. The reserved keywords are tokens the Primvar uses internally to
encode various features, such as the"indices"keyword used by Indexed
Primvars.
If a client wishes to access an already-extant attribute as a Primvar,
(which may or may not actually be valid Primvar), they can use the
speculative constructor; typically, a primvar is only"interesting"if
it additionally provides a value. This might look like:
.. code-block:: text
UsdGeomPrimvar primvar = UsdGeomPrimvar(usdAttr);
if (primvar.HasValue()) {
VtValue values;
primvar.Get(&values, timeCode);
TfToken interpolation = primvar.GetInterpolation();
int elementSize = primvar.GetElementSize();
\\.\\.\\.
}
or, because Get() returns ``true`` if and only if it found a value:
.. code-block:: text
UsdGeomPrimvar primvar = UsdGeomPrimvar(usdAttr);
VtValue values;
if (primvar.Get(&values, timeCode)) {
TfToken interpolation = primvar.GetInterpolation();
int elementSize = primvar.GetElementSize();
\\.\\.\\.
}
As discussed in greater detail in Indexed Primvars, primvars can
optionally contain a (possibly time-varying) indexing attribute that
establishes a sharing topology for elements of the primvar. Consumers
can always chose to ignore the possibility of indexed data by
exclusively using the ComputeFlattened() API. If a client wishes to
preserve indexing in their processing of a primvar, we suggest a
pattern like the following, which accounts for the fact that a
stronger layer can block a primvar's indexing from a weaker layer, via
UsdGeomPrimvar::BlockIndices() :
.. code-block:: text
VtValue values;
VtIntArray indices;
if (primvar.Get(&values, timeCode)){
if (primvar.GetIndices(&indices, timeCode)){
// primvar is indexed: validate/process values and indices together
}
else {
// primvar is not indexed: validate/process values as flat array
}
}
UsdGeomPrimvar presents a small slice of the UsdAttribute API - enough
to extract the data that comprises the"Declaration info", and get/set
of the attribute value. A UsdGeomPrimvar also auto-converts to
UsdAttribute, so you can pass a UsdGeomPrimvar to any function that
accepts a UsdAttribute or const-ref thereto.
Primvar Allowed Scene Description Types and Plurality
=====================================================
There are no limitations imposed on the allowable scene description
types for Primvars; it is the responsibility of each consuming client
to perform renderer-specific conversions, if need be (the USD
distribution will include reference RenderMan conversion utilities).
A note about type plurality of Primvars: It is legitimate for a
Primvar to be of scalar or array type, and again, consuming clients
must be prepared to accommodate both. However, while it is not
possible, in all cases, for USD to *prevent* one from *changing* the
type of an attribute in different layers or variants of an asset, it
is never a good idea to do so. This is relevant because, except in a
few special cases, it is not possible to encode an *interpolation* of
any value greater than *constant* without providing multiple (i.e.
array) data values. Therefore, if there is any possibility that
downstream clients might need to change a Primvar's interpolation, the
Primvar-creator should encode it as an array rather than a scalar.
Why allow scalar values at all, then? First, sometimes it brings
clarity to (use of) a shader's API to acknowledge that some parameters
are meant to be single-valued over a shaded primitive. Second, many
DCC's provide far richer affordances for editing scalars than they do
array values, and we feel it is safer to let the content creator make
the decision/tradeoff of which kind of flexibility is more relevant,
rather than leaving it to an importer/exporter pair to interpret.
Also, like all attributes, Primvars can be time-sampled, and values
can be authored and consumed just as any other attribute. There is
currently no validation that the length of value arrays matches to the
size required by a gprim's topology, interpolation, and elementSize.
For consumer convenience, we provide GetDeclarationInfo() , which
returns all the type information (other than topology) needed to
compute the required array size, which is also all the information
required to prepare the Primvar's value for consumption by a renderer.
Lifetime Management and Primvar Validity
========================================
UsdGeomPrimvar has an explicit bool operator that validates that the
attribute IsDefined() and thus valid for querying and authoring values
and metadata. This is a fairly expensive query that we do **not**
cache, so if client code retains UsdGeomPrimvar objects, it should
manage its object validity closely, for performance. An ideal pattern
is to listen for UsdNotice::StageContentsChanged notifications, and
revalidate/refetch its retained UsdGeomPrimvar s only then, and
otherwise use them without validity checking.
Interpolation of Geometric Primitive Variables
==============================================
In the following explanation of the meaning of the various
kinds/levels of Primvar interpolation, each bolded bullet gives the
name of the token in UsdGeomTokens that provides the value. So to set
a Primvar's interpolation to"varying", one would:
.. code-block:: text
primvar.SetInterpolation(UsdGeomTokens->varying);
Reprinted and adapted from the RPS documentation, which contains
further details, *interpolation* describes how the Primvar will be
interpolated over the uv parameter space of a surface primitive (or
curve or pointcloud). The possible values are:
- **constant** One value remains constant over the entire surface
primitive.
- **uniform** One value remains constant for each uv patch segment
of the surface primitive (which is a *face* for meshes).
- **varying** Four values are interpolated over each uv patch
segment of the surface. Bilinear interpolation is used for
interpolation between the four values.
- **vertex** Values are interpolated between each vertex in the
surface primitive. The basis function of the surface is used for
interpolation between vertices.
- **faceVarying** For polygons and subdivision surfaces, four
values are interpolated over each face of the mesh. Bilinear
interpolation is used for interpolation between the four values.
UsdGeomPrimvar As Example of Attribute Schema
=============================================
Just as UsdSchemaBase and its subclasses provide the pattern for how
to layer schema onto the generic UsdPrim object, UsdGeomPrimvar
provides an example of how to layer schema onto a generic UsdAttribute
object. In both cases, the schema object wraps and contains the
UsdObject.
Primvar Namespace Inheritance
=============================
Constant interpolation primvar values can be inherited down namespace.
That is, a primvar value set on a prim will also apply to any child
prims, unless those children have their own opinions about those named
primvars. For complete details on how primvars inherit, see
usdGeom_PrimvarInheritance.
UsdGeomImageable::FindInheritablePrimvars().
"""
result["Primvar"].GetAttr.func_doc = """GetAttr() -> Attribute
Explicit UsdAttribute extractor.
"""
result["Primvar"].IsDefined.func_doc = """IsDefined() -> bool
Return true if the underlying UsdAttribute::IsDefined() , and in
addition the attribute is identified as a Primvar.
Does not imply that the primvar provides a value
"""
result["Primvar"].HasValue.func_doc = """HasValue() -> bool
Return true if the underlying attribute has a value, either from
authored scene description or a fallback.
"""
result["Primvar"].HasAuthoredValue.func_doc = """HasAuthoredValue() -> bool
Return true if the underlying attribute has an unblocked, authored
value.
"""
result["Primvar"].GetName.func_doc = """GetName() -> str
UsdAttribute::GetName()
"""
result["Primvar"].GetPrimvarName.func_doc = """GetPrimvarName() -> str
Returns the primvar's name, devoid of the"primvars:"namespace.
This is the name by which clients should refer to the primvar, if not
by its full attribute name - i.e. they should **not**, in general, use
GetBaseName() . In the error condition in which this Primvar object is
not backed by a properly namespaced UsdAttribute, return an empty
TfToken.
"""
result["Primvar"].NameContainsNamespaces.func_doc = """NameContainsNamespaces() -> bool
Does this primvar contain any namespaces other than
the"primvars:"namespace?
Some clients may only wish to consume primvars that have no extra
namespaces in their names, for ease of translating to other systems
that do not allow namespaces.
"""
result["Primvar"].GetBaseName.func_doc = """GetBaseName() -> str
UsdAttribute::GetBaseName()
"""
result["Primvar"].GetNamespace.func_doc = """GetNamespace() -> str
UsdAttribute::GetNamespace()
"""
result["Primvar"].SplitName.func_doc = """SplitName() -> list[str]
UsdAttribute::SplitName()
"""
result["Primvar"].GetTypeName.func_doc = """GetTypeName() -> ValueTypeName
UsdAttribute::GetTypeName()
"""
result["Primvar"].Get.func_doc = """Get(value, time) -> bool
Get the attribute value of the Primvar at ``time`` .
Usd_Handling_Indexed_Primvars for proper handling of indexed primvars
Parameters
----------
value : T
time : TimeCode
----------------------------------------------------------------------
Get(value, time) -> bool
Parameters
----------
value : str
time : TimeCode
----------------------------------------------------------------------
Get(value, time) -> bool
Parameters
----------
value : StringArray
time : TimeCode
----------------------------------------------------------------------
Get(value, time) -> bool
Parameters
----------
value : VtValue
time : TimeCode
"""
result["Primvar"].Set.func_doc = """Set(value, time) -> bool
Set the attribute value of the Primvar at ``time`` .
Parameters
----------
value : T
time : TimeCode
"""
result["Primvar"].GetTimeSamples.func_doc = """GetTimeSamples(times) -> bool
Populates a vector with authored sample times for this primvar.
Returns false on error.
This considers any timeSamples authored on the
associated"indices"attribute if the primvar is indexed.
UsdAttribute::GetTimeSamples
Parameters
----------
times : list[float]
"""
result["Primvar"].GetTimeSamplesInInterval.func_doc = """GetTimeSamplesInInterval(interval, times) -> bool
Populates a vector with authored sample times in ``interval`` .
This considers any timeSamples authored on the
associated"indices"attribute if the primvar is indexed.
UsdAttribute::GetTimeSamplesInInterval
Parameters
----------
interval : Interval
times : list[float]
"""
result["Primvar"].ValueMightBeTimeVarying.func_doc = """ValueMightBeTimeVarying() -> bool
Return true if it is possible, but not certain, that this primvar's
value changes over time, false otherwise.
This considers time-varyingness of the associated"indices"attribute if
the primvar is indexed.
UsdAttribute::ValueMightBeTimeVarying
"""
result["Primvar"].SetIndices.func_doc = """SetIndices(indices, time) -> bool
Sets the indices value of the indexed primvar at ``time`` .
The values in the indices array must be valid indices into the
authored array returned by Get() . The element numerality of the
primvar's'interpolation'metadata applies to the"indices"array, not the
attribute value array (returned by Get() ).
Parameters
----------
indices : IntArray
time : TimeCode
"""
result["Primvar"].GetIndices.func_doc = """GetIndices(indices, time) -> bool
Returns the value of the indices array associated with the indexed
primvar at ``time`` .
SetIndices() , Proper Client Handling of"Indexed"Primvars
Parameters
----------
indices : IntArray
time : TimeCode
"""
result["Primvar"].BlockIndices.func_doc = """BlockIndices() -> None
Block the indices that were previously set.
This effectively makes an indexed primvar no longer indexed. This is
useful when overriding an existing primvar.
"""
result["Primvar"].IsIndexed.func_doc = """IsIndexed() -> bool
Returns true if the primvar is indexed, i.e., if it has an
associated"indices"attribute.
If you are going to query the indices anyways, prefer to simply
consult the return-value of GetIndices() , which will be more
efficient.
"""
result["Primvar"].GetIndicesAttr.func_doc = """GetIndicesAttr() -> Attribute
Returns a valid indices attribute if the primvar is indexed.
Returns an invalid attribute otherwise.
"""
result["Primvar"].CreateIndicesAttr.func_doc = """CreateIndicesAttr() -> Attribute
Returns the existing indices attribute if the primvar is indexed or
creates a new one.
"""
result["Primvar"].SetUnauthoredValuesIndex.func_doc = """SetUnauthoredValuesIndex(unauthoredValuesIndex) -> bool
Set the index that represents unauthored values in the indices array.
Some apps (like Maya) allow you to author primvars sparsely over a
surface. Since most apps can't handle sparse primvars, Maya needs to
provide a value even for the elements it didn't author. This metadatum
provides a way to recover the information in apps that do support
sparse authoring / representation of primvars.
The fallback value of unauthoredValuesIndex is -1, which indicates
that there are no unauthored values.
GetUnauthoredValuesIndex()
Parameters
----------
unauthoredValuesIndex : int
"""
result["Primvar"].GetUnauthoredValuesIndex.func_doc = """GetUnauthoredValuesIndex() -> int
Returns the index that represents unauthored values in the indices
array.
SetUnauthoredValuesIndex()
"""
result["Primvar"].ComputeFlattened.func_doc = """**classmethod** ComputeFlattened(value, time) -> bool
Computes the flattened value of the primvar at ``time`` .
If the primvar is not indexed or if the value type of this primvar is
a scalar, this returns the authored value, which is the same as Get()
. Hence, it's safe to call ComputeFlattened() on non-indexed primvars.
Parameters
----------
value : VtArray[ScalarType]
time : TimeCode
----------------------------------------------------------------------
ComputeFlattened(value, time) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the flattened value of the primvar at ``time`` as a VtValue.
If the primvar is not indexed or if the value type of this primvar is
a scalar, this returns the authored value, which is the same as Get()
. Hence, it's safe to call ComputeFlattened() on non-indexed primvars.
Parameters
----------
value : VtValue
time : TimeCode
----------------------------------------------------------------------
ComputeFlattened(value, attrVal, indices, errString) -> bool
Computes the flattened value of ``attrValue`` given ``indices`` .
This method is a static convenience function that performs the main
work of ComputeFlattened above without needing an instance of a
UsdGeomPrimvar.
Returns ``false`` if the value contained in ``attrVal`` is not a
supported type for flattening. Otherwise returns ``true`` . The output
``errString`` variable may be populated with an error string if an
error is encountered during flattening.
Parameters
----------
value : VtValue
attrVal : VtValue
indices : IntArray
errString : str
"""
result["Primvar"].IsIdTarget.func_doc = """IsIdTarget() -> bool
Returns true if the primvar is an Id primvar.
UsdGeomPrimvar_Id_primvars
"""
result["Primvar"].SetIdTarget.func_doc = """SetIdTarget(path) -> bool
This primvar must be of String or StringArray type for this method to
succeed.
If not, a coding error is raised.
UsdGeomPrimvar_Id_primvars
Parameters
----------
path : Path
"""
result["Primvar"].__init__.func_doc = """__init__()
----------------------------------------------------------------------
__init__(other)
Copy construct.
Parameters
----------
other : Primvar
----------------------------------------------------------------------
__init__(attr)
Speculative constructor that will produce a valid UsdGeomPrimvar when
``attr`` already represents an attribute that is Primvar, and produces
an *invalid* Primvar otherwise (i.e.
operator bool() will return false).
Calling ``UsdGeomPrimvar::IsPrimvar(attr)`` will return the same truth
value as this constructor, but if you plan to subsequently use the
Primvar anyways, just use this constructor, as demonstrated in the
class documentation.
Parameters
----------
attr : Attribute
----------------------------------------------------------------------
__init__(prim, attrName, typeName)
Factory for UsdGeomImageable 's use, so that we can encapsulate the
logic of what discriminates Primvar in this class, while preserving
the pattern that attributes can only be created via their container
objects.
The name of the created attribute may or may not be the specified
``attrName`` , due to the possible need to apply property namespacing
for Primvar.
The behavior with respect to the provided ``typeName`` is the same as
for UsdAttributes::Create().
an invalid UsdGeomPrimvar if we failed to create a valid attribute, a
valid UsdGeomPrimvar otherwise. It is not an error to create over an
existing, compatible attribute. It is a failed verification for
``prim`` to be invalid/expired
UsdPrim::CreateAttribute()
Parameters
----------
prim : Prim
attrName : str
typeName : ValueTypeName
"""
result["Primvar"].GetInterpolation.func_doc = """GetInterpolation() -> str
Return the Primvar's interpolation, which is UsdGeomTokens->constant
if unauthored.
Interpolation determines how the Primvar interpolates over a geometric
primitive. See Interpolation of Geometric Primitive Variables
"""
result["Primvar"].SetInterpolation.func_doc = """SetInterpolation(interpolation) -> bool
Set the Primvar's interpolation.
Errors and returns false if ``interpolation`` is out of range as
defined by IsValidInterpolation() . No attempt is made to validate
that the Primvar's value contains the right number of elements to
match its interpolation to its topology.
GetInterpolation() , Interpolation of Geometric Primitive Variables
Parameters
----------
interpolation : str
"""
result["Primvar"].HasAuthoredInterpolation.func_doc = """HasAuthoredInterpolation() -> bool
Has interpolation been explicitly authored on this Primvar?
GetInterpolationSize()
"""
result["Primvar"].GetElementSize.func_doc = """GetElementSize() -> int
Return the"element size"for this Primvar, which is 1 if unauthored.
If this Primvar's type is *not* an array type, (e.g."Vec3f[]"), then
elementSize is irrelevant.
ElementSize does *not* generally encode the length of an array-type
primvar, and rarely needs to be authored. ElementSize can be thought
of as a way to create an"aggregate interpolatable type", by dictating
how many consecutive elements in the value array should be taken as an
atomic element to be interpolated over a gprim.
For example, spherical harmonics are often represented as a collection
of nine floating-point coefficients, and the coefficients need to be
sampled across a gprim's surface: a perfect case for primvars.
However, USD has no ``float9`` datatype. But we can communicate the
aggregation of nine floats successfully to renderers by declaring a
simple float-array valued primvar, and setting its *elementSize* to 9.
To author a *uniform* spherical harmonic primvar on a Mesh of 42
faces, the primvar's array value would contain 9\\*42 = 378 float
elements.
"""
result["Primvar"].SetElementSize.func_doc = """SetElementSize(eltSize) -> bool
Set the elementSize for this Primvar.
Errors and returns false if ``eltSize`` less than 1.
GetElementSize()
Parameters
----------
eltSize : int
"""
result["Primvar"].HasAuthoredElementSize.func_doc = """HasAuthoredElementSize() -> bool
Has elementSize been explicitly authored on this Primvar?
GetElementSize()
"""
result["Primvar"].GetDeclarationInfo.func_doc = """GetDeclarationInfo(name, typeName, interpolation, elementSize) -> None
Convenience function for fetching all information required to properly
declare this Primvar.
The ``name`` returned is the"client name", stripped of
the"primvars"namespace, i.e. equivalent to GetPrimvarName()
May also be more efficient than querying key individually.
Parameters
----------
name : str
typeName : ValueTypeName
interpolation : str
elementSize : int
"""
result["Primvar"].IsPrimvar.func_doc = """**classmethod** IsPrimvar(attr) -> bool
Test whether a given UsdAttribute represents valid Primvar, which
implies that creating a UsdGeomPrimvar from the attribute will
succeed.
Success implies that ``attr.IsDefined()`` is true.
Parameters
----------
attr : Attribute
"""
result["Primvar"].IsValidPrimvarName.func_doc = """**classmethod** IsValidPrimvarName(name) -> bool
Test whether a given ``name`` represents a valid name of a primvar,
which implies that creating a UsdGeomPrimvar with the given name will
succeed.
Parameters
----------
name : str
"""
result["Primvar"].StripPrimvarsName.func_doc = """**classmethod** StripPrimvarsName(name) -> str
Returns the ``name`` , devoid of the"primvars:"token if present,
otherwise returns the ``name`` unchanged.
Parameters
----------
name : str
"""
result["Primvar"].IsValidInterpolation.func_doc = """**classmethod** IsValidInterpolation(interpolation) -> bool
Validate that the provided ``interpolation`` is a valid setting for
interpolation as defined by Interpolation of Geometric Primitive
Variables.
Parameters
----------
interpolation : str
"""
result["PrimvarsAPI"].__doc__ = """
UsdGeomPrimvarsAPI encodes geometric"primitive variables", as
UsdGeomPrimvar, which interpolate across a primitive's topology, can
override shader inputs, and inherit down namespace.
Which Method to Use to Retrieve Primvars
========================================
While creating primvars is unambiguous ( CreatePrimvar() ), there are
quite a few methods available for retrieving primvars, making it
potentially confusing knowing which one to use. Here are some
guidelines:
- If you are populating a GUI with the primvars already available
for authoring values on a prim, use GetPrimvars() .
- If you want all of the"useful"(e.g. to a renderer) primvars
available at a prim, including those inherited from ancestor prims,
use FindPrimvarsWithInheritance() . Note that doing so individually
for many prims will be inefficient.
- To find a particular primvar defined directly on a prim, which
may or may not provide a value, use GetPrimvar() .
- To find a particular primvar defined on a prim or inherited from
ancestors, which may or may not provide a value, use
FindPrimvarWithInheritance() .
- To *efficiently* query for primvars using the overloads of
FindPrimvarWithInheritance() and FindPrimvarsWithInheritance() , one
must first cache the results of FindIncrementallyInheritablePrimvars()
for each non-leaf prim on the stage.
"""
result["PrimvarsAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomPrimvarsAPI on UsdPrim ``prim`` .
Equivalent to UsdGeomPrimvarsAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomPrimvarsAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomPrimvarsAPI (schemaObj.GetPrim()), as
it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["PrimvarsAPI"].CreatePrimvar.func_doc = """CreatePrimvar(name, typeName, interpolation, elementSize) -> Primvar
Author scene description to create an attribute on this prim that will
be recognized as Primvar (i.e.
will present as a valid UsdGeomPrimvar).
The name of the created attribute may or may not be the specified
``name`` , due to the possible need to apply property namespacing for
primvars. See Creating and Accessing Primvars for more information.
Creation may fail and return an invalid Primvar if ``name`` contains a
reserved keyword, such as the"indices"suffix we use for indexed
primvars.
The behavior with respect to the provided ``typeName`` is the same as
for UsdAttributes::Create(), and ``interpolation`` and ``elementSize``
are as described in UsdGeomPrimvar::GetInterpolation() and
UsdGeomPrimvar::GetElementSize() .
If ``interpolation`` and/or ``elementSize`` are left unspecified, we
will author no opinions for them, which means any (strongest) opinion
already authored in any contributing layer for these fields will
become the Primvar's values, or the fallbacks if no opinions have been
authored.
an invalid UsdGeomPrimvar if we failed to create a valid attribute, a
valid UsdGeomPrimvar otherwise. It is not an error to create over an
existing, compatible attribute.
UsdPrim::CreateAttribute() , UsdGeomPrimvar::IsPrimvar()
Parameters
----------
name : str
typeName : ValueTypeName
interpolation : str
elementSize : int
"""
result["PrimvarsAPI"].CreateNonIndexedPrimvar.func_doc = """CreateNonIndexedPrimvar(name, typeName, value, interpolation, elementSize, time) -> Primvar
Author scene description to create an attribute and authoring a
``value`` on this prim that will be recognized as a Primvar (i.e.
will present as a valid UsdGeomPrimvar). Note that unlike
CreatePrimvar using this API explicitly authors a block for the
indices attr associated with the primvar, thereby blocking any indices
set in any weaker layers.
an invalid UsdGeomPrimvar on error, a valid UsdGeomPrimvar otherwise.
It is fine to call this method multiple times, and in different
UsdEditTargets, even if there is an existing primvar of the same name,
indexed or not.
CreatePrimvar() , CreateIndexedPrimvar() , UsdPrim::CreateAttribute()
, UsdGeomPrimvar::IsPrimvar()
Parameters
----------
name : str
typeName : ValueTypeName
value : T
interpolation : str
elementSize : int
time : TimeCode
"""
result["PrimvarsAPI"].CreateIndexedPrimvar.func_doc = """CreateIndexedPrimvar(name, typeName, value, indices, interpolation, elementSize, time) -> Primvar
Author scene description to create an attribute and authoring a
``value`` on this prim that will be recognized as an indexed Primvar
with ``indices`` appropriately set (i.e.
will present as a valid UsdGeomPrimvar).
an invalid UsdGeomPrimvar on error, a valid UsdGeomPrimvar otherwise.
It is fine to call this method multiple times, and in different
UsdEditTargets, even if there is an existing primvar of the same name,
indexed or not.
CreatePrimvar() , CreateNonIndexedPrimvar() ,
UsdPrim::CreateAttribute() , UsdGeomPrimvar::IsPrimvar()
Parameters
----------
name : str
typeName : ValueTypeName
value : T
indices : IntArray
interpolation : str
elementSize : int
time : TimeCode
"""
result["PrimvarsAPI"].RemovePrimvar.func_doc = """RemovePrimvar(name) -> bool
Author scene description to delete an attribute on this prim that was
recognized as Primvar (i.e.
will present as a valid UsdGeomPrimvar), *in the current
UsdEditTarget*.
Because this method can only remove opinions about the primvar from
the current EditTarget, you may generally find it more useful to use
BlockPrimvar() which will ensure that all values from the EditTarget
and weaker layers for the primvar and its indices will be ignored.
Removal may fail and return false if ``name`` contains a reserved
keyword, such as the"indices"suffix we use for indexed primvars.
Note this will also remove the indices attribute associated with an
indiced primvar.
true if UsdGeomPrimvar and indices attribute was successfully removed,
false otherwise.
UsdPrim::RemoveProperty() )
Parameters
----------
name : str
"""
result["PrimvarsAPI"].BlockPrimvar.func_doc = """BlockPrimvar(name) -> None
Remove all time samples on the primvar and its associated indices
attr, and author a *block* ``default`` value.
This will cause authored opinions in weaker layers to be ignored.
UsdAttribute::Block() , UsdGeomPrimvar::BlockIndices
Parameters
----------
name : str
"""
result["PrimvarsAPI"].GetPrimvar.func_doc = """GetPrimvar(name) -> Primvar
Return the Primvar object named by ``name`` , which will be valid if a
Primvar attribute definition already exists.
Name lookup will account for Primvar namespacing, which means that
this method will succeed in some cases where
.. code-block:: text
UsdGeomPrimvar(prim->GetAttribute(name))
will not, unless ``name`` is properly namespace prefixed.
Just because a Primvar is valid and defined, and *even if* its
underlying UsdAttribute (GetAttr()) answers HasValue() affirmatively,
one must still check the return value of Get() , due to the potential
of time-varying value blocks (see Attribute Value Blocking).
HasPrimvar() , Which Method to Use to Retrieve Primvars
Parameters
----------
name : str
"""
result["PrimvarsAPI"].GetPrimvars.func_doc = """GetPrimvars() -> list[Primvar]
Return valid UsdGeomPrimvar objects for all defined Primvars on this
prim, similarly to UsdPrim::GetAttributes() .
The returned primvars may not possess any values, and therefore not be
useful to some clients. For the primvars useful for inheritance
computations, see GetPrimvarsWithAuthoredValues() , and for primvars
useful for direct consumption, see GetPrimvarsWithValues() .
Which Method to Use to Retrieve Primvars
"""
result["PrimvarsAPI"].GetAuthoredPrimvars.func_doc = """GetAuthoredPrimvars() -> list[Primvar]
Like GetPrimvars() , but include only primvars that have some authored
scene description (though not necessarily a value).
Which Method to Use to Retrieve Primvars
"""
result["PrimvarsAPI"].GetPrimvarsWithValues.func_doc = """GetPrimvarsWithValues() -> list[Primvar]
Like GetPrimvars() , but include only primvars that have some value,
whether it comes from authored scene description or a schema fallback.
For most purposes, this method is more useful than GetPrimvars() .
Which Method to Use to Retrieve Primvars
"""
result["PrimvarsAPI"].GetPrimvarsWithAuthoredValues.func_doc = """GetPrimvarsWithAuthoredValues() -> list[Primvar]
Like GetPrimvars() , but include only primvars that have an
**authored** value.
This is the query used when computing inheritable primvars, and is
generally more useful than GetAuthoredPrimvars() .
Which Method to Use to Retrieve Primvars
"""
result["PrimvarsAPI"].FindInheritablePrimvars.func_doc = """FindInheritablePrimvars() -> list[Primvar]
Compute the primvars that can be inherited from this prim by its child
prims, including the primvars that **this** prim inherits from
ancestor prims.
Inherited primvars will be bound to attributes on the corresponding
ancestor prims.
Only primvars with **authored**, **non-blocked**, **constant
interpolation** values are inheritable; fallback values are not
inherited. The order of the returned primvars is undefined.
It is not generally useful to call this method on UsdGeomGprim leaf
prims, and furthermore likely to be expensive since *most* primvars
are defined on Gprims.
Which Method to Use to Retrieve Primvars
"""
result["PrimvarsAPI"].FindIncrementallyInheritablePrimvars.func_doc = """FindIncrementallyInheritablePrimvars(inheritedFromAncestors) -> list[Primvar]
Compute the primvars that can be inherited from this prim by its child
prims, starting from the set of primvars inherited from this prim's
ancestors.
If this method returns an empty vector, then this prim's children
should inherit the same set of primvars available to this prim, i.e.
the input ``inheritedFromAncestors`` .
As opposed to FindInheritablePrimvars() , which always recurses up
through all of the prim's ancestors, this method allows more efficient
computation of inheritable primvars by starting with the list of
primvars inherited from this prim's ancestors, and returning a newly
allocated vector only when this prim makes a change to the set of
inherited primvars. This enables O(n) inherited primvar computation
for all prims on a Stage, with potential to share computed results
that are identical (i.e. when this method returns an empty vector, its
parent's result can (and must!) be reused for all of the prim's
children.
Which Method to Use to Retrieve Primvars
Parameters
----------
inheritedFromAncestors : list[Primvar]
"""
result["PrimvarsAPI"].FindPrimvarWithInheritance.func_doc = """FindPrimvarWithInheritance(name) -> Primvar
Like GetPrimvar() , but if the named primvar does not exist or has no
authored value on this prim, search for the named, value-producing
primvar on ancestor prims.
The returned primvar will be bound to the attribute on the
corresponding ancestor prim on which it was found (if any). If neither
this prim nor any ancestor contains a value-producing primvar, then
the returned primvar will be the same as that returned by GetPrimvar()
.
This is probably the method you want to call when needing to consume a
primvar of a particular name.
Which Method to Use to Retrieve Primvars
Parameters
----------
name : str
----------------------------------------------------------------------
FindPrimvarWithInheritance(name, inheritedFromAncestors) -> Primvar
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
This version of FindPrimvarWithInheritance() takes the pre-computed
set of primvars inherited from this prim's ancestors, as computed by
FindInheritablePrimvars() or FindIncrementallyInheritablePrimvars() on
the prim's parent.
Which Method to Use to Retrieve Primvars
Parameters
----------
name : str
inheritedFromAncestors : list[Primvar]
"""
result["PrimvarsAPI"].FindPrimvarsWithInheritance.func_doc = """FindPrimvarsWithInheritance() -> list[Primvar]
Find all of the value-producing primvars either defined on this prim,
or inherited from ancestor prims.
Which Method to Use to Retrieve Primvars
----------------------------------------------------------------------
FindPrimvarsWithInheritance(inheritedFromAncestors) -> list[Primvar]
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
This version of FindPrimvarsWithInheritance() takes the pre-computed
set of primvars inherited from this prim's ancestors, as computed by
FindInheritablePrimvars() or FindIncrementallyInheritablePrimvars() on
the prim's parent.
Which Method to Use to Retrieve Primvars
Parameters
----------
inheritedFromAncestors : list[Primvar]
"""
result["PrimvarsAPI"].HasPrimvar.func_doc = """HasPrimvar(name) -> bool
Is there a defined Primvar ``name`` on this prim?
Name lookup will account for Primvar namespacing.
Like GetPrimvar() , a return value of ``true`` for HasPrimvar() does
not guarantee the primvar will produce a value.
Parameters
----------
name : str
"""
result["PrimvarsAPI"].HasPossiblyInheritedPrimvar.func_doc = """HasPossiblyInheritedPrimvar(name) -> bool
Is there a Primvar named ``name`` with an authored value on this prim
or any of its ancestors?
This is probably the method you want to call when wanting to know
whether or not the prim"has"a primvar of a particular name.
FindPrimvarWithInheritance()
Parameters
----------
name : str
"""
result["PrimvarsAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["PrimvarsAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> PrimvarsAPI
Return a UsdGeomPrimvarsAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomPrimvarsAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["PrimvarsAPI"].CanContainPropertyName.func_doc = """**classmethod** CanContainPropertyName(name) -> bool
Test whether a given ``name`` contains the"primvars:"prefix.
Parameters
----------
name : str
"""
result["PrimvarsAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Scope"].__doc__ = """
Scope is the simplest grouping primitive, and does not carry the
baggage of transformability. Note that transforms should inherit down
through a Scope successfully - it is just a guaranteed no-op from a
transformability perspective.
"""
result["Scope"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomScope on UsdPrim ``prim`` .
Equivalent to UsdGeomScope::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomScope on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomScope (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Scope"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Scope"].Get.func_doc = """**classmethod** Get(stage, path) -> Scope
Return a UsdGeomScope holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomScope(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Scope"].Define.func_doc = """**classmethod** Define(stage, path) -> Scope
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Scope"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Sphere"].__doc__ = """
Defines a primitive sphere centered at the origin.
The fallback values for Cube, Sphere, Cone, and Cylinder are set so
that they all pack into the same volume/bounds.
"""
result["Sphere"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomSphere on UsdPrim ``prim`` .
Equivalent to UsdGeomSphere::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomSphere on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomSphere (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Sphere"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute
Indicates the sphere's radius.
If you author *radius* you must also author *extent*.
GetExtentAttr()
Declaration
``double radius = 1``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["Sphere"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute
See GetRadiusAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Sphere"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute
Extent is re-defined on Sphere only to provide a fallback value.
UsdGeomGprim::GetExtentAttr() .
Declaration
``float3[] extent = [(-1, -1, -1), (1, 1, 1)]``
C++ Type
VtArray<GfVec3f>
Usd Type
SdfValueTypeNames->Float3Array
"""
result["Sphere"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute
See GetExtentAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Sphere"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Sphere"].Get.func_doc = """**classmethod** Get(stage, path) -> Sphere
Return a UsdGeomSphere holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomSphere(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Sphere"].Define.func_doc = """**classmethod** Define(stage, path) -> Sphere
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Sphere"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(radius, extent) -> bool
Compute the extent for the sphere defined by the radius.
true upon success, false if unable to calculate extent. On success,
extent will contain an approximate axis-aligned bounding box of the
sphere defined by the radius.
This function is to provide easy authoring of extent for usd authoring
tools, hence it is static and acts outside a specific prim (as in
attribute based methods).
Parameters
----------
radius : float
extent : Vec3fArray
----------------------------------------------------------------------
ComputeExtent(radius, transform, extent) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Computes the extent as if the matrix ``transform`` was first applied.
Parameters
----------
radius : float
transform : Matrix4d
extent : Vec3fArray
"""
result["Sphere"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Subset"].__doc__ = """
Encodes a subset of a piece of geometry (i.e. a UsdGeomImageable) as a
set of indices. Currently only supports encoding of face-subsets, but
could be extended in the future to support subsets representing edges,
segments, points etc.
To apply to a geometric prim, a GeomSubset prim must be the prim's
direct child in namespace, and possess a concrete defining specifier
(i.e. def). This restriction makes it easy and efficient to discover
subsets of a prim. We might want to relax this restriction if it's
common to have multiple **families** of subsets on a gprim and if it's
useful to be able to organize subsets belonging to a family under a
common scope. See'familyName'attribute for more info on defining a
family of subsets.
Note that a GeomSubset isn't an imageable (i.e. doesn't derive from
UsdGeomImageable). So, you can't author **visibility** for it or
override its **purpose**.
Materials are bound to GeomSubsets just as they are for regular
geometry using API available in UsdShade (UsdShadeMaterial::Bind).
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["Subset"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomSubset on UsdPrim ``prim`` .
Equivalent to UsdGeomSubset::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomSubset on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomSubset (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Subset"].GetElementTypeAttr.func_doc = """GetElementTypeAttr() -> Attribute
The type of element that the indices target.
Currently only allows"face"and defaults to it.
Declaration
``uniform token elementType ="face"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
face
"""
result["Subset"].CreateElementTypeAttr.func_doc = """CreateElementTypeAttr(defaultValue, writeSparsely) -> Attribute
See GetElementTypeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Subset"].GetIndicesAttr.func_doc = """GetIndicesAttr() -> Attribute
The set of indices included in this subset.
The indices need not be sorted, but the same index should not appear
more than once.
Declaration
``int[] indices = []``
C++ Type
VtArray<int>
Usd Type
SdfValueTypeNames->IntArray
"""
result["Subset"].CreateIndicesAttr.func_doc = """CreateIndicesAttr(defaultValue, writeSparsely) -> Attribute
See GetIndicesAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Subset"].GetFamilyNameAttr.func_doc = """GetFamilyNameAttr() -> Attribute
The name of the family of subsets that this subset belongs to.
This is optional and is primarily useful when there are multiple
families of subsets under a geometric prim. In some cases, this could
also be used for achieving proper roundtripping of subset data between
DCC apps. When multiple subsets belonging to a prim have the same
familyName, they are said to belong to the family. A *familyType*
value can be encoded on the owner of a family of subsets as a token
using the static method UsdGeomSubset::SetFamilyType()
."familyType"can have one of the following values:
- **UsdGeomTokens->partition** : implies that every element of the
whole geometry appears exactly once in only one of the subsets
belonging to the family.
- **UsdGeomTokens->nonOverlapping** : an element that appears in
one subset may not appear in any other subset belonging to the family.
- **UsdGeomTokens->unrestricted** : implies that there are no
restrictions w.r.t. the membership of elements in the subsets. They
could be overlapping and the union of all subsets in the family may
not represent the whole.
The validity of subset data is not enforced by the authoring APIs,
however they can be checked using UsdGeomSubset::ValidateFamily() .
Declaration
``uniform token familyName =""``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
"""
result["Subset"].CreateFamilyNameAttr.func_doc = """CreateFamilyNameAttr(defaultValue, writeSparsely) -> Attribute
See GetFamilyNameAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Subset"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Subset"].Get.func_doc = """**classmethod** Get(stage, path) -> Subset
Return a UsdGeomSubset holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomSubset(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Subset"].Define.func_doc = """**classmethod** Define(stage, path) -> Subset
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Subset"].CreateGeomSubset.func_doc = """**classmethod** CreateGeomSubset(geom, subsetName, elementType, indices, familyName, familyType) -> Subset
Creates a new GeomSubset below the given ``geom`` with the given name,
``subsetName`` , element type, ``elementType`` and ``indices`` .
If a subset named ``subsetName`` already exists below ``geom`` , then
this updates its attributes with the values of the provided arguments
(indices value at time'default'will be updated) and returns it.
The family type is set / updated on ``geom`` only if a non-empty value
is passed in for ``familyType`` and ``familyName`` .
Parameters
----------
geom : Imageable
subsetName : str
elementType : str
indices : IntArray
familyName : str
familyType : str
"""
result["Subset"].CreateUniqueGeomSubset.func_doc = """**classmethod** CreateUniqueGeomSubset(geom, subsetName, elementType, indices, familyName, familyType) -> Subset
Creates a new GeomSubset below the given imageable, ``geom`` with the
given name, ``subsetName`` , element type, ``elementType`` and
``indices`` .
If a subset named ``subsetName`` already exists below ``geom`` , then
this creates a new subset by appending a suitable index as suffix to
``subsetName`` (eg, subsetName_1) to avoid name collisions.
The family type is set / updated on ``geom`` only if a non-empty value
is passed in for ``familyType`` and ``familyName`` .
Parameters
----------
geom : Imageable
subsetName : str
elementType : str
indices : IntArray
familyName : str
familyType : str
"""
result["Subset"].GetAllGeomSubsets.func_doc = """**classmethod** GetAllGeomSubsets(geom) -> list[Subset]
Returns all the GeomSubsets defined on the given imageable, ``geom`` .
Parameters
----------
geom : Imageable
"""
result["Subset"].GetGeomSubsets.func_doc = """**classmethod** GetGeomSubsets(geom, elementType, familyName) -> list[Subset]
Returns all the GeomSubsets of the given ``elementType`` belonging to
the specified family, ``familyName`` on the given imageable, ``geom``
.
If ``elementType`` is empty, then subsets containing all element types
are returned. If ``familyName`` is left empty, then all subsets of the
specified ``elementType`` will be returned.
Parameters
----------
geom : Imageable
elementType : str
familyName : str
"""
result["Subset"].GetAllGeomSubsetFamilyNames.func_doc = """**classmethod** GetAllGeomSubsetFamilyNames(geom) -> str.Set
Returns the names of all the families of GeomSubsets defined on the
given imageable, ``geom`` .
Parameters
----------
geom : Imageable
"""
result["Subset"].SetFamilyType.func_doc = """**classmethod** SetFamilyType(geom, familyName, familyType) -> bool
This method is used to encode the type of family that the GeomSubsets
on the given geometric prim ``geom`` , with the given family name,
``familyName`` belong to.
See UsdGeomSubset::GetFamilyNameAttr for the possible values for
``familyType`` .
When a family of GeomSubsets is tagged as a UsdGeomTokens->partition
or UsdGeomTokens->nonOverlapping, the validity of the data (i.e.
mutual exclusivity and/or wholeness) is not enforced by the authoring
APIs. Use ValidateFamily() to validate the data in a family of
GeomSubsets.
Returns false upon failure to create or set the appropriate attribute
on ``geom`` .
Parameters
----------
geom : Imageable
familyName : str
familyType : str
"""
result["Subset"].GetFamilyType.func_doc = """**classmethod** GetFamilyType(geom, familyName) -> str
Returns the type of family that the GeomSubsets on the given geometric
prim ``geom`` , with the given family name, ``familyName`` belong to.
This only returns the token that's encoded on ``geom`` and does not
perform any actual validation on the family of GeomSubsets. Please use
ValidateFamily() for such validation.
When familyType is not set on ``geom`` , the fallback value
UsdTokens->unrestricted is returned.
Parameters
----------
geom : Imageable
familyName : str
"""
result["Subset"].GetUnassignedIndices.func_doc = """**classmethod** GetUnassignedIndices(subsets, elementCount, time) -> IntArray
Utility for getting the list of indices that are not assigned to any
of the GeomSubsets in ``subsets`` at the timeCode, ``time`` , given
the element count (total number of indices in the array being
subdivided), ``elementCount`` .
Parameters
----------
subsets : list[Subset]
elementCount : int
time : TimeCode
"""
result["Subset"].ValidateSubsets.func_doc = """**classmethod** ValidateSubsets(subsets, elementCount, familyType, reason) -> bool
Validates the data in the given set of GeomSubsets, ``subsets`` ,
given the total number of elements in the array being subdivided,
``elementCount`` and the ``familyType`` that the subsets belong to.
For proper validation of indices in ``subsets`` , all of the
GeomSubsets must have the same'elementType'.
If one or more subsets contain invalid data, then false is returned
and ``reason`` is populated with a string explaining the reason why it
is invalid.
The python version of this method returns a tuple containing a (bool,
string), where the bool has the validity of the subsets and the string
contains the reason (if they're invalid).
Parameters
----------
subsets : list[Subset]
elementCount : int
familyType : str
reason : str
"""
result["Subset"].ValidateFamily.func_doc = """**classmethod** ValidateFamily(geom, elementType, familyName, reason) -> bool
Validates whether the family of subsets identified by the given
``familyName`` and ``elementType`` on the given imageable, ``geom``
contain valid data.
If the family is designated as a partition or as non-overlapping using
SetFamilyType() , then the validity of the data is checked. If the
familyType is"unrestricted", then this performs only bounds checking
of the values in the"indices"arrays.
If ``reason`` is not None, then it is populated with a string
explaining why the family is invalid, if it is invalid.
The python version of this method returns a tuple containing a (bool,
string), where the bool has the validity of the family and the string
contains the reason (if it's invalid).
Parameters
----------
geom : Imageable
elementType : str
familyName : str
reason : str
"""
result["Subset"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["VisibilityAPI"].__doc__ = """
UsdGeomVisibilityAPI introduces properties that can be used to author
visibility opinions.
Currently, this schema only introduces the attributes that are used to
control purpose visibility. Later, this schema will define *all*
visibility-related properties and UsdGeomImageable will no longer
define those properties. The purpose visibility attributes added by
this schema, *guideVisibility*, *proxyVisibility*, and
*renderVisibility* can each be used to control visibility for geometry
of the corresponding purpose values, with the overall *visibility*
attribute acting as an override. I.e., if *visibility* evaluates
to"invisible", purpose visibility is invisible; otherwise, purpose
visibility is determined by the corresponding purpose visibility
attribute.
Note that the behavior of *guideVisibility* is subtly different from
the *proxyVisibility* and *renderVisibility* attributes, in
that"guide"purpose visibility always evaluates to
either"invisible"or"visible", whereas the other attributes may yield
computed values of"inherited"if there is no authored opinion on the
attribute or inherited from an ancestor. This is motivated by the fact
that, in Pixar"s user workflows, we have never found a need to have
all guides visible in a scene by default, whereas we do find that
flexibility useful for"proxy"and"render"geometry.
This schema can only be applied to UsdGeomImageable prims. The
UseGeomImageable schema provides API for computing the purpose
visibility values that result from the attributes introduced by this
schema.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdGeomTokens. So to set an attribute to the value"rightHanded",
use UsdGeomTokens->rightHanded as the value.
"""
result["VisibilityAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomVisibilityAPI on UsdPrim ``prim`` .
Equivalent to UsdGeomVisibilityAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomVisibilityAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomVisibilityAPI (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["VisibilityAPI"].GetGuideVisibilityAttr.func_doc = """GetGuideVisibilityAttr() -> Attribute
This attribute controls visibility for geometry with purpose"guide".
Unlike overall *visibility*, *guideVisibility* is uniform, and
therefore cannot be animated.
Also unlike overall *visibility*, *guideVisibility* is tri-state, in
that a descendant with an opinion of"visible"overrides an ancestor
opinion of"invisible".
The *guideVisibility* attribute works in concert with the overall
*visibility* attribute: The visibility of a prim with purpose"guide"is
determined by the inherited values it receives for the *visibility*
and *guideVisibility* attributes. If *visibility* evaluates
to"invisible", the prim is invisible. If *visibility* evaluates
to"inherited"and *guideVisibility* evaluates to"visible", then the
prim is visible. **Otherwise, it is invisible.**
Declaration
``uniform token guideVisibility ="invisible"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
inherited, invisible, visible
"""
result["VisibilityAPI"].CreateGuideVisibilityAttr.func_doc = """CreateGuideVisibilityAttr(defaultValue, writeSparsely) -> Attribute
See GetGuideVisibilityAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["VisibilityAPI"].GetProxyVisibilityAttr.func_doc = """GetProxyVisibilityAttr() -> Attribute
This attribute controls visibility for geometry with purpose"proxy".
Unlike overall *visibility*, *proxyVisibility* is uniform, and
therefore cannot be animated.
Also unlike overall *visibility*, *proxyVisibility* is tri-state, in
that a descendant with an opinion of"visible"overrides an ancestor
opinion of"invisible".
The *proxyVisibility* attribute works in concert with the overall
*visibility* attribute: The visibility of a prim with purpose"proxy"is
determined by the inherited values it receives for the *visibility*
and *proxyVisibility* attributes. If *visibility* evaluates
to"invisible", the prim is invisible. If *visibility* evaluates
to"inherited"then: If *proxyVisibility* evaluates to"visible", then
the prim is visible; if *proxyVisibility* evaluates to"invisible",
then the prim is invisible; if *proxyVisibility* evaluates
to"inherited", then the prim may either be visible or invisible,
depending on a fallback value determined by the calling context.
Declaration
``uniform token proxyVisibility ="inherited"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
inherited, invisible, visible
"""
result["VisibilityAPI"].CreateProxyVisibilityAttr.func_doc = """CreateProxyVisibilityAttr(defaultValue, writeSparsely) -> Attribute
See GetProxyVisibilityAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["VisibilityAPI"].GetRenderVisibilityAttr.func_doc = """GetRenderVisibilityAttr() -> Attribute
This attribute controls visibility for geometry with purpose"render".
Unlike overall *visibility*, *renderVisibility* is uniform, and
therefore cannot be animated.
Also unlike overall *visibility*, *renderVisibility* is tri-state, in
that a descendant with an opinion of"visible"overrides an ancestor
opinion of"invisible".
The *renderVisibility* attribute works in concert with the overall
*visibility* attribute: The visibility of a prim with
purpose"render"is determined by the inherited values it receives for
the *visibility* and *renderVisibility* attributes. If *visibility*
evaluates to"invisible", the prim is invisible. If *visibility*
evaluates to"inherited"then: If *renderVisibility* evaluates
to"visible", then the prim is visible; if *renderVisibility* evaluates
to"invisible", then the prim is invisible; if *renderVisibility*
evaluates to"inherited", then the prim may either be visible or
invisible, depending on a fallback value determined by the calling
context.
Declaration
``uniform token renderVisibility ="inherited"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
inherited, invisible, visible
"""
result["VisibilityAPI"].CreateRenderVisibilityAttr.func_doc = """CreateRenderVisibilityAttr(defaultValue, writeSparsely) -> Attribute
See GetRenderVisibilityAttr() , and also Create vs Get Property
Methods for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["VisibilityAPI"].GetPurposeVisibilityAttr.func_doc = """GetPurposeVisibilityAttr(purpose) -> Attribute
Return the attribute that is used for expressing visibility opinions
for the given ``purpose`` .
The valid purpose tokens are"guide","proxy", and"render"which return
the attributes *guideVisibility*, *proxyVisibility*, and
*renderVisibility* respectively.
Note that while"default"is a valid purpose token for
UsdGeomImageable::GetPurposeVisibilityAttr, it is not a valid purpose
for this function, as UsdGeomVisibilityAPI itself does not have a
default visibility attribute. Calling this function with "default will
result in a coding error.
Parameters
----------
purpose : str
"""
result["VisibilityAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["VisibilityAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> VisibilityAPI
Return a UsdGeomVisibilityAPI holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomVisibilityAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["VisibilityAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool
Returns true if this **single-apply** API schema can be applied to the
given ``prim`` .
If this schema can not be a applied to the prim, this returns false
and, if provided, populates ``whyNot`` with the reason it can not be
applied.
Note that if CanApply returns false, that does not necessarily imply
that calling Apply will fail. Callers are expected to call CanApply
before calling Apply if they want to ensure that it is valid to apply
a schema.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
whyNot : str
"""
result["VisibilityAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> VisibilityAPI
Applies this **single-apply** API schema to the given ``prim`` .
This information is stored by adding"VisibilityAPI"to the token-
valued, listOp metadata *apiSchemas* on the prim.
A valid UsdGeomVisibilityAPI object is returned upon success. An
invalid (or empty) UsdGeomVisibilityAPI object is returned upon
failure. See UsdPrim::ApplyAPI() for conditions resulting in failure.
UsdPrim::GetAppliedSchemas()
UsdPrim::HasAPI()
UsdPrim::CanApplyAPI()
UsdPrim::ApplyAPI()
UsdPrim::RemoveAPI()
Parameters
----------
prim : Prim
"""
result["VisibilityAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Xform"].__doc__ = """
Concrete prim schema for a transform, which implements Xformable
"""
result["Xform"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomXform on UsdPrim ``prim`` .
Equivalent to UsdGeomXform::Get (prim.GetStage(), prim.GetPath()) for
a *valid* ``prim`` , but will not immediately throw an error for an
invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomXform on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomXform (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Xform"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Xform"].Get.func_doc = """**classmethod** Get(stage, path) -> Xform
Return a UsdGeomXform holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomXform(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Xform"].Define.func_doc = """**classmethod** Define(stage, path) -> Xform
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["Xform"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["Xformable"].__doc__ = """
Base class for all transformable prims, which allows arbitrary
sequences of component affine transformations to be encoded.
You may find it useful to review Linear Algebra in UsdGeom while
reading this class description. **Supported Component Transformation
Operations**
UsdGeomXformable currently supports arbitrary sequences of the
following operations, each of which can be encoded in an attribute of
the proper shape in any supported precision:
- translate - 3D
- scale - 3D
- rotateX - 1D angle in degrees
- rotateY - 1D angle in degrees
- rotateZ - 1D angle in degrees
- rotateABC - 3D where ABC can be any combination of the six
principle Euler Angle sets: XYZ, XZY, YXZ, YZX, ZXY, ZYX. See note on
rotation packing order
- orient - 4D (quaternion)
- transform - 4x4D
**Creating a Component Transformation**
To add components to a UsdGeomXformable prim, simply call AddXformOp()
with the desired op type, as enumerated in UsdGeomXformOp::Type, and
the desired precision, which is one of UsdGeomXformOp::Precision.
Optionally, you can also provide an"op suffix"for the operator that
disambiguates it from other components of the same type on the same
prim. Application-specific transform schemas can use the suffixes to
fill a role similar to that played by AbcGeom::XformOp's"Hint"enums
for their own round-tripping logic.
We also provide specific"Add"API for each type, for clarity and
conciseness, e.g. AddTranslateOp() , AddRotateXYZOp() etc.
AddXformOp() will return a UsdGeomXformOp object, which is a schema on
a newly created UsdAttribute that provides convenience API for
authoring and computing the component transformations. The
UsdGeomXformOp can then be used to author any number of timesamples
and default for the op.
Each successive call to AddXformOp() adds an operator that will be
applied"more locally"than the preceding operator, just as if we were
pushing transforms onto a transformation stack - which is precisely
what should happen when the operators are consumed by a reader.
If you can, please try to use the UsdGeomXformCommonAPI, which wraps
the UsdGeomXformable with an interface in which Op creation is taken
care of for you, and there is a much higher chance that the data you
author will be importable without flattening into other DCC's, as it
conforms to a fixed set of Scale-Rotate-Translate Ops.
Using the Authoring API **Data Encoding and Op Ordering**
Because there is no"fixed schema"of operations, all of the attributes
that encode transform operations are dynamic, and are scoped in the
namespace"xformOp". The second component of an attribute's name
provides the *type* of operation, as listed above.
An"xformOp"attribute can have additional namespace components derived
from the *opSuffix* argument to the AddXformOp() suite of methods,
which provides a preferred way of naming the ops such that we can have
multiple"translate"ops with unique attribute names. For example, in
the attribute named"xformOp:translate:maya:pivot","translate"is the
type of operation and"maya:pivot"is the suffix.
The following ordered list of attribute declarations in usda define a
basic Scale-Rotate-Translate with XYZ Euler angles, wherein the
translation is double-precision, and the remainder of the ops are
single, in which we will:
- Scale by 2.0 in each dimension
- Rotate about the X, Y, and Z axes by 30, 60, and 90 degrees,
respectively
- Translate by 100 units in the Y direction
.. code-block:: text
float3 xformOp:rotateXYZ = (30, 60, 90)
float3 xformOp:scale = (2, 2, 2)
double3 xformOp:translate = (0, 100, 0)
uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale" ]
The attributes appear in the dictionary order in which USD, by
default, sorts them. To ensure the ops are recovered and evaluated in
the correct order, the schema introduces the **xformOpOrder**
attribute, which contains the names of the op attributes, in the
precise sequence in which they should be pushed onto a transform
stack. **Note** that the order is opposite to what you might expect,
given the matrix algebra described in Linear Algebra in UsdGeom. This
also dictates order of op creation, since each call to AddXformOp()
adds a new op to the end of the **xformOpOrder** array, as a new"most-
local"operation. See Example 2 below for C++ code that could have
produced this USD.
If it were important for the prim's rotations to be independently
overridable, we could equivalently (at some performance cost) encode
the transformation also like so:
.. code-block:: text
float xformOp:rotateX = 30
float xformOp:rotateY = 60
float xformOp:rotateZ = 90
float3 xformOp:scale = (2, 2, 2)
double3 xformOp:translate = (0, 100, 0)
uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateZ", "xformOp:rotateY", "xformOp:rotateX", "xformOp:scale" ]
Again, note that although we are encoding an XYZ rotation, the three
rotations appear in the **xformOpOrder** in the opposite order, with
Z, followed, by Y, followed by X.
Were we to add a Maya-style scalePivot to the above example, it might
look like the following:
.. code-block:: text
float3 xformOp:rotateXYZ = (30, 60, 90)
float3 xformOp:scale = (2, 2, 2)
double3 xformOp:translate = (0, 100, 0)
double3 xformOp:translate:scalePivot
uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateXYZ", "xformOp:translate:scalePivot", "xformOp:scale" ]
**Paired"Inverted"Ops**
We have been claiming that the ordered list of ops serves as a set of
instructions to a transform stack, but you may have noticed in the
last example that there is a missing operation - the pivot for the
scale op needs to be applied in its inverse-form as a final (most
local) op! In the AbcGeom::Xform schema, we would have encoded an
actual"final"translation op whose value was authored by the exporter
as the negation of the pivot's value. However, doing so would be
brittle in USD, given that each op can be independently overridden,
and the constraint that one attribute must be maintained as the
negation of the other in order for successful re-importation of the
schema cannot be expressed in USD.
Our solution leverages the **xformOpOrder** member of the schema,
which, in addition to ordering the ops, may also contain one of two
special tokens that address the paired op and"stack
resetting"behavior.
The"paired op"behavior is encoded as an"!invert!"prefix in
**xformOpOrder**, as the result of an AddXformOp(isInverseOp=True)
call. The **xformOpOrder** for the last example would look like:
.. code-block:: text
uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateXYZ", "xformOp:translate:scalePivot", "xformOp:scale", "!invert!xformOp:translate:scalePivot" ]
When asked for its value via UsdGeomXformOp::GetOpTransform() ,
an"inverted"Op (i.e. the"inverted"half of a set of paired Ops) will
fetch the value of its paired attribute and return its negation. This
works for all op types - an error will be issued if a"transform"type
op is singular and cannot be inverted. When getting the authored value
of an inverted op via UsdGeomXformOp::Get() , the raw, uninverted
value of the associated attribute is returned.
For the sake of robustness, **setting a value on an inverted op is
disallowed.** Attempting to set a value on an inverted op will result
in a coding error and no value being set.
**Resetting the Transform Stack**
The other special op/token that can appear in *xformOpOrder* is
*"!resetXformStack!"*, which, appearing as the first element of
*xformOpOrder*, indicates this prim should not inherit the
transformation of its namespace parent. See SetResetXformStack()
**Expected Behavior for"Missing"Ops**
If an importer expects Scale-Rotate-Translate operations, but a prim
has only translate and rotate ops authored, the importer should assume
an identity scale. This allows us to optimize the data a bit, if only
a few components of a very rich schema (like Maya's) are authored in
the app.
**Using the C++ API**
#1. Creating a simple transform matrix encoding
.. code-block:: text
#2. Creating the simple SRT from the example above
.. code-block:: text
#3. Creating a parameterized SRT with pivot using
UsdGeomXformCommonAPI
.. code-block:: text
#4. Creating a rotate-only pivot transform with animated rotation and
translation
.. code-block:: text
"""
result["Xformable"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomXformable on UsdPrim ``prim`` .
Equivalent to UsdGeomXformable::Get (prim.GetStage(), prim.GetPath())
for a *valid* ``prim`` , but will not immediately throw an error for
an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomXformable on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomXformable (schemaObj.GetPrim()), as it
preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["Xformable"].GetXformOpOrderAttr.func_doc = """GetXformOpOrderAttr() -> Attribute
Encodes the sequence of transformation operations in the order in
which they should be pushed onto a transform stack while visiting a
UsdStage 's prims in a graph traversal that will effect the desired
positioning for this prim and its descendant prims.
You should rarely, if ever, need to manipulate this attribute
directly. It is managed by the AddXformOp() , SetResetXformStack() ,
and SetXformOpOrder() , and consulted by GetOrderedXformOps() and
GetLocalTransformation() .
Declaration
``uniform token[] xformOpOrder``
C++ Type
VtArray<TfToken>
Usd Type
SdfValueTypeNames->TokenArray
Variability
SdfVariabilityUniform
"""
result["Xformable"].CreateXformOpOrderAttr.func_doc = """CreateXformOpOrderAttr(defaultValue, writeSparsely) -> Attribute
See GetXformOpOrderAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["Xformable"].AddXformOp.func_doc = """AddXformOp(opType, precision, opSuffix, isInverseOp) -> XformOp
Add an affine transformation to the local stack represented by this
Xformable.
This will fail if there is already a transform operation of the same
name in the ordered ops on this prim (i.e. as returned by
GetOrderedXformOps() ), or if an op of the same name exists at all on
the prim with a different precision than that specified.
The newly created operation will become the most-locally applied
transformation on the prim, and will appear last in the list returned
by GetOrderedXformOps() . It is OK to begin authoring values to the
returned UsdGeomXformOp immediately, interspersed with subsequent
calls to AddXformOp() - just note the order of application, which
*can* be changed at any time (and in stronger layers) via
SetXformOpOrder() .
opType
is the type of transform operation, one of UsdGeomXformOp::Type.
precision
allows you to specify the precision with which you desire to encode
the data. This should be one of the values in the enum
UsdGeomXformOp::Precision. opSuffix
allows you to specify the purpose/meaning of the op in the stack. When
opSuffix is specified, the associated attribute's name is set
to"xformOp:<opType>:<opSuffix>". isInverseOp
is used to indicate an inverse transformation operation.
a UsdGeomXformOp that can be used to author to the operation. An error
is issued and the returned object will be invalid (evaluate to false)
if the op being added already exists in xformOpOrder or if the
arguments supplied are invalid.
If the attribute associated with the op already exists, but isn't of
the requested precision, a coding error is issued, but a valid xformOp
is returned with the existing attribute.
Parameters
----------
opType : XformOp.Type
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddTranslateOp.func_doc = """AddTranslateOp(precision, opSuffix, isInverseOp) -> XformOp
Add a translate operation to the local stack represented by this
xformable.
AddXformOp()
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddScaleOp.func_doc = """AddScaleOp(precision, opSuffix, isInverseOp) -> XformOp
Add a scale operation to the local stack represented by this
xformable.
AddXformOp()
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddRotateXOp.func_doc = """AddRotateXOp(precision, opSuffix, isInverseOp) -> XformOp
Add a rotation about the X-axis to the local stack represented by this
xformable.
Set the angle value of the resulting UsdGeomXformOp **in degrees**
AddXformOp()
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddRotateYOp.func_doc = """AddRotateYOp(precision, opSuffix, isInverseOp) -> XformOp
Add a rotation about the YX-axis to the local stack represented by
this xformable.
Set the angle value of the resulting UsdGeomXformOp **in degrees**
AddXformOp()
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddRotateZOp.func_doc = """AddRotateZOp(precision, opSuffix, isInverseOp) -> XformOp
Add a rotation about the Z-axis to the local stack represented by this
xformable.
AddXformOp()
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddRotateXYZOp.func_doc = """AddRotateXYZOp(precision, opSuffix, isInverseOp) -> XformOp
Add a rotation op with XYZ rotation order to the local stack
represented by this xformable.
Set the angle value of the resulting UsdGeomXformOp **in degrees**
AddXformOp() , note on angle packing order
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddRotateXZYOp.func_doc = """AddRotateXZYOp(precision, opSuffix, isInverseOp) -> XformOp
Add a rotation op with XZY rotation order to the local stack
represented by this xformable.
Set the angle values of the resulting UsdGeomXformOp **in degrees**
AddXformOp() , note on angle packing order
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddRotateYXZOp.func_doc = """AddRotateYXZOp(precision, opSuffix, isInverseOp) -> XformOp
Add a rotation op with YXZ rotation order to the local stack
represented by this xformable.
Set the angle values of the resulting UsdGeomXformOp **in degrees**
AddXformOp() , note on angle packing order
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddRotateYZXOp.func_doc = """AddRotateYZXOp(precision, opSuffix, isInverseOp) -> XformOp
Add a rotation op with YZX rotation order to the local stack
represented by this xformable.
Set the angle values of the resulting UsdGeomXformOp **in degrees**
AddXformOp() , note on angle packing order
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddRotateZXYOp.func_doc = """AddRotateZXYOp(precision, opSuffix, isInverseOp) -> XformOp
Add a rotation op with ZXY rotation order to the local stack
represented by this xformable.
Set the angle values of the resulting UsdGeomXformOp **in degrees**
AddXformOp() , note on angle packing order
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddRotateZYXOp.func_doc = """AddRotateZYXOp(precision, opSuffix, isInverseOp) -> XformOp
Add a rotation op with ZYX rotation order to the local stack
represented by this xformable.
Set the angle values of the resulting UsdGeomXformOp **in degrees**
AddXformOp() , note on angle packing order
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddOrientOp.func_doc = """AddOrientOp(precision, opSuffix, isInverseOp) -> XformOp
Add a orient op (arbitrary axis/angle rotation) to the local stack
represented by this xformable.
AddXformOp()
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].AddTransformOp.func_doc = """AddTransformOp(precision, opSuffix, isInverseOp) -> XformOp
Add a tranform op (4x4 matrix transformation) to the local stack
represented by this xformable.
AddXformOp() Note: This method takes a precision argument only to be
consistent with the other types of xformOps. The only valid precision
here is double since matrix values cannot be encoded in floating-pt
precision in Sdf.
Parameters
----------
precision : XformOp.Precision
opSuffix : str
isInverseOp : bool
"""
result["Xformable"].SetResetXformStack.func_doc = """SetResetXformStack(resetXform) -> bool
Specify whether this prim's transform should reset the transformation
stack inherited from its parent prim.
By default, parent transforms are inherited. SetResetXformStack() can
be called at any time during authoring, but will always add
a'!resetXformStack!'op as the *first* op in the ordered list, if one
does not exist already. If one already exists, and ``resetXform`` is
false, it will remove all ops upto and including the
last"!resetXformStack!"op.
Parameters
----------
resetXform : bool
"""
result["Xformable"].GetResetXformStack.func_doc = """GetResetXformStack() -> bool
Does this prim reset its parent's inherited transformation?
Returns true if"!resetXformStack!"appears *anywhere* in xformOpOrder.
When this returns true, all ops upto the last"!resetXformStack!"in
xformOpOrder are ignored when computing the local transformation.
"""
result["Xformable"].SetXformOpOrder.func_doc = """SetXformOpOrder(orderedXformOps, resetXformStack) -> bool
Reorder the already-existing transform ops on this prim.
All elements in ``orderedXformOps`` must be valid and represent
attributes on this prim. Note that it is *not* required that all the
existing operations be present in ``orderedXformOps`` , so this method
can be used to completely change the transformation structure applied
to the prim.
If ``resetXformStack`` is set to true, then "!resetXformOp! will be
set as the first op in xformOpOrder, to indicate that the prim does
not inherit its parent's transformation.
If you wish to re-specify a prim's transformation completely in a
stronger layer, you should first call this method with an *empty*
``orderedXformOps`` vector. From there you can call AddXformOp() just
as if you were authoring to the prim from scratch.
false if any of the elements of ``orderedXformOps`` are not extant on
this prim, or if an error occurred while authoring the ordering
metadata. Under either condition, no scene description is authored.
GetOrderedXformOps()
Parameters
----------
orderedXformOps : list[XformOp]
resetXformStack : bool
"""
result["Xformable"].ClearXformOpOrder.func_doc = """ClearXformOpOrder() -> bool
Clears the local transform stack.
"""
result["Xformable"].MakeMatrixXform.func_doc = """MakeMatrixXform() -> XformOp
Clears the existing local transform stack and creates a new xform op
of type'transform'.
This API is provided for convenience since this is the most common
xform authoring operation.
ClearXformOpOrder()
AddTransformOp()
"""
result["Xformable"].TransformMightBeTimeVarying.func_doc = """TransformMightBeTimeVarying() -> bool
Determine whether there is any possibility that this prim's *local*
transformation may vary over time.
The determination is based on a snapshot of the authored state of the
op attributes on the prim, and may become invalid in the face of
further authoring.
----------------------------------------------------------------------
TransformMightBeTimeVarying(ops) -> bool
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
Determine whether there is any possibility that this prim's *local*
transformation may vary over time, using a pre-fetched (cached) list
of ordered xform ops supplied by the client.
The determination is based on a snapshot of the authored state of the
op attributes on the prim, and may become invalid in the face of
further authoring.
Parameters
----------
ops : list[XformOp]
"""
result["Xformable"].GetTimeSamples.func_doc = """**classmethod** GetTimeSamples(times) -> bool
Sets ``times`` to the union of all the timesamples at which xformOps
that are included in the xformOpOrder attribute are authored.
This clears the ``times`` vector before accumulating sample times from
all the xformOps.
UsdAttribute::GetTimeSamples
Parameters
----------
times : list[float]
----------------------------------------------------------------------
GetTimeSamples(orderedXformOps, times) -> bool
Returns the union of all the timesamples at which the attributes
belonging to the given ``orderedXformOps`` are authored.
This clears the ``times`` vector before accumulating sample times from
``orderedXformOps`` .
UsdGeomXformable::GetTimeSamples
Parameters
----------
orderedXformOps : list[XformOp]
times : list[float]
"""
result["Xformable"].GetTimeSamplesInInterval.func_doc = """**classmethod** GetTimeSamplesInInterval(interval, times) -> bool
Sets ``times`` to the union of all the timesamples in the interval,
``interval`` , at which xformOps that are included in the xformOpOrder
attribute are authored.
This clears the ``times`` vector before accumulating sample times from
all the xformOps.
UsdAttribute::GetTimeSamples
Parameters
----------
interval : Interval
times : list[float]
----------------------------------------------------------------------
GetTimeSamplesInInterval(orderedXformOps, interval, times) -> bool
Returns the union of all the timesamples in the ``interval`` at which
the attributes belonging to the given ``orderedXformOps`` are
authored.
This clears the ``times`` vector before accumulating sample times from
``orderedXformOps`` .
UsdGeomXformable::GetTimeSamplesInInterval
Parameters
----------
orderedXformOps : list[XformOp]
interval : Interval
times : list[float]
"""
result["Xformable"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["Xformable"].Get.func_doc = """**classmethod** Get(stage, path) -> Xformable
Return a UsdGeomXformable holding the prim adhering to this schema at
``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomXformable(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["Xformable"].IsTransformationAffectedByAttrNamed.func_doc = """**classmethod** IsTransformationAffectedByAttrNamed(attrName) -> bool
Returns true if the attribute named ``attrName`` could affect the
local transformation of an xformable prim.
Parameters
----------
attrName : str
"""
result["Xformable"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["XformCache"].__doc__ = """
A caching mechanism for transform matrices. For best performance, this
object should be reused for multiple CTM queries.
Instances of this type can be copied, though using Swap() may result
in better performance.
It is valid to cache prims from multiple stages in a single
XformCache.
WARNING: this class does not automatically invalidate cached values
based on changes to the stage from which values were cached.
Additionally, a separate instance of this class should be used per-
thread, calling the Get\\* methods from multiple threads is not safe,
as they mutate internal state.
"""
result["XformCache"].__init__.func_doc = """__init__(time)
Construct a new XformCache for the specified ``time`` .
Parameters
----------
time : TimeCode
----------------------------------------------------------------------
__init__()
Construct a new XformCache for UsdTimeCode::Default() .
"""
result["XformCache"].GetLocalToWorldTransform.func_doc = """GetLocalToWorldTransform(prim) -> Matrix4d
Compute the transformation matrix for the given ``prim`` , including
the transform authored on the Prim itself, if present.
This method may mutate internal cache state and is not thread safe.
Parameters
----------
prim : Prim
"""
result["XformCache"].GetParentToWorldTransform.func_doc = """GetParentToWorldTransform(prim) -> Matrix4d
Compute the transformation matrix for the given ``prim`` , but do NOT
include the transform authored on the prim itself.
This method may mutate internal cache state and is not thread safe.
Parameters
----------
prim : Prim
"""
result["XformCache"].GetLocalTransformation.func_doc = """GetLocalTransformation(prim, resetsXformStack) -> Matrix4d
Returns the local transformation of the prim.
Uses the cached XformQuery to compute the result quickly. The
``resetsXformStack`` pointer must be valid. It will be set to true if
``prim`` resets the transform stack. The result of this call is
cached.
Parameters
----------
prim : Prim
resetsXformStack : bool
"""
result["XformCache"].ComputeRelativeTransform.func_doc = """ComputeRelativeTransform(prim, ancestor, resetXformStack) -> Matrix4d
Returns the result of concatenating all transforms beneath
``ancestor`` that affect ``prim`` .
This includes the local transform of ``prim`` itself, but not the
local transform of ``ancestor`` . If ``ancestor`` is not an ancestor
of ``prim`` , the resulting transform is the local-to-world
transformation of ``prim`` . The ``resetXformTsack`` pointer must be
valid. If any intermediate prims reset the transform stack,
``resetXformStack`` will be set to true. Intermediate transforms are
cached, but the result of this call itself is not cached.
Parameters
----------
prim : Prim
ancestor : Prim
resetXformStack : bool
"""
result["XformCache"].Clear.func_doc = """Clear() -> None
Clears all pre-cached values.
"""
result["XformCache"].SetTime.func_doc = """SetTime(time) -> None
Use the new ``time`` when computing values and may clear any existing
values cached for the previous time.
Setting ``time`` to the current time is a no-op.
Parameters
----------
time : TimeCode
"""
result["XformCache"].GetTime.func_doc = """GetTime() -> TimeCode
Get the current time from which this cache is reading values.
"""
result["XformCache"].Swap.func_doc = """Swap(other) -> None
Swap the contents of this XformCache with ``other`` .
Parameters
----------
other : XformCache
"""
result["XformCommonAPI"].__doc__ = """
This class provides API for authoring and retrieving a standard set of
component transformations which include a scale, a rotation, a scale-
rotate pivot and a translation. The goal of the API is to enhance
component-wise interchange. It achieves this by limiting the set of
allowed basic ops and by specifying the order in which they are
applied. In addition to the basic set of ops, the'resetXformStack'bit
can also be set to indicate whether the underlying xformable resets
the parent transformation (i.e. does not inherit it's parent's
transformation).
UsdGeomXformCommonAPI::GetResetXformStack()
UsdGeomXformCommonAPI::SetResetXformStack() The operator-bool for the
class will inform you whether an existing xformable is compatible with
this API.
The scale-rotate pivot is represented by a pair of (translate,
inverse-translate) xformOps around the scale and rotate operations.
The rotation operation can be any of the six allowed Euler angle sets.
UsdGeomXformOp::Type. The xformOpOrder of an xformable that has all of
the supported basic ops is as follows:
["xformOp:translate","xformOp:translate:pivot","xformOp:rotateXYZ","xformOp:scale","!invert!xformOp:translate:pivot"].
It is worth noting that all of the ops are optional. For example, an
xformable may have only a translate or a rotate. It would still be
considered as compatible with this API. Individual SetTranslate() ,
SetRotate() , SetScale() and SetPivot() methods are provided by this
API to allow such sparse authoring.
"""
result["XformCommonAPI"].SetTranslate.func_doc = """SetTranslate(translation, time) -> bool
Set translation at ``time`` to ``translation`` .
Parameters
----------
translation : Vec3d
time : TimeCode
"""
result["XformCommonAPI"].SetPivot.func_doc = """SetPivot(pivot, time) -> bool
Set pivot position at ``time`` to ``pivot`` .
Parameters
----------
pivot : Vec3f
time : TimeCode
"""
result["XformCommonAPI"].SetRotate.func_doc = """SetRotate(rotation, rotOrder, time) -> bool
Set rotation at ``time`` to ``rotation`` .
Parameters
----------
rotation : Vec3f
rotOrder : XformCommonAPI.RotationOrder
time : TimeCode
"""
result["XformCommonAPI"].SetScale.func_doc = """SetScale(scale, time) -> bool
Set scale at ``time`` to ``scale`` .
Parameters
----------
scale : Vec3f
time : TimeCode
"""
result["XformCommonAPI"].SetResetXformStack.func_doc = """SetResetXformStack(resetXformStack) -> bool
Set whether the xformable resets the transform stack.
i.e., does not inherit the parent transformation.
Parameters
----------
resetXformStack : bool
"""
result["XformCommonAPI"].CreateXformOps.func_doc = """CreateXformOps(rotOrder, op1, op2, op3, op4) -> Ops
Creates the specified XformCommonAPI-compatible xform ops, or returns
the existing ops if they already exist.
If successful, returns an Ops object with all the ops on this prim,
identified by type. If the requested xform ops couldn't be created or
the prim is not XformCommonAPI-compatible, returns an Ops object with
all invalid ops.
The ``rotOrder`` is only used if OpRotate is specified. Otherwise, it
is ignored. (If you don't need to create a rotate op, you might find
it helpful to use the other overload that takes no rotation order.)
Parameters
----------
rotOrder : RotationOrder
op1 : OpFlags
op2 : OpFlags
op3 : OpFlags
op4 : OpFlags
----------------------------------------------------------------------
CreateXformOps(op1, op2, op3, op4) -> Ops
This is an overloaded member function, provided for convenience. It
differs from the above function only in what argument(s) it accepts.
This overload does not take a rotation order.
If you specify OpRotate, then this overload assumes RotationOrderXYZ
or the previously-authored rotation order. (If you do need to create a
rotate op, you might find it helpful to use the other overload that
explicitly takes a rotation order.)
Parameters
----------
op1 : OpFlags
op2 : OpFlags
op3 : OpFlags
op4 : OpFlags
"""
result["XformCommonAPI"].GetRotationTransform.func_doc = """**classmethod** GetRotationTransform(rotation, rotationOrder) -> Matrix4d
Return the 4x4 matrix that applies the rotation encoded by rotation
vector ``rotation`` using the rotation order ``rotationOrder`` .
Deprecated
Please use the result of ConvertRotationOrderToOpType() along with
UsdGeomXformOp::GetOpTransform() instead.
Parameters
----------
rotation : Vec3f
rotationOrder : XformCommonAPI.RotationOrder
"""
result["XformCommonAPI"].RotationOrder.__doc__ = """
Enumerates the rotation order of the 3-angle Euler rotation.
"""
result["XformCommonAPI"].OpFlags.__doc__ = """
Enumerates the categories of ops that can be handled by
XformCommonAPI.
For use with CreateXformOps() .
"""
result["XformCommonAPI"].__init__.func_doc = """__init__(prim)
Construct a UsdGeomXformCommonAPI on UsdPrim ``prim`` .
Equivalent to UsdGeomXformCommonAPI::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdGeomXformCommonAPI on the prim held by ``schemaObj`` .
Should be preferred over UsdGeomXformCommonAPI (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["XformCommonAPI"].SetXformVectors.func_doc = """SetXformVectors(translation, rotation, scale, pivot, rotOrder, time) -> bool
Set values for the various component xformOps at a given ``time`` .
Calling this method will call all of the supported ops to be created,
even if they only contain default (identity) values.
To author individual operations selectively, use the Set[OpType]()
API.
Once the rotation order has been established for a given xformable
(either because of an already defined (and compatible) rotate op or
from calling SetXformVectors() or SetRotate() ), it cannot be changed.
Parameters
----------
translation : Vec3d
rotation : Vec3f
scale : Vec3f
pivot : Vec3f
rotOrder : RotationOrder
time : TimeCode
"""
result["XformCommonAPI"].GetXformVectors.func_doc = """GetXformVectors(translation, rotation, scale, pivot, rotOrder, time) -> bool
Retrieve values of the various component xformOps at a given ``time``
.
Identity values are filled in for the component xformOps that don't
exist or don't have an authored value.
This method works even on prims with an incompatible xform schema,
i.e. when the bool operator returns false. When the underlying
xformable has an incompatible xform schema, it performs a full-on
matrix decomposition to XYZ rotation order.
Parameters
----------
translation : Vec3d
rotation : Vec3f
scale : Vec3f
pivot : Vec3f
rotOrder : RotationOrder
time : TimeCode
"""
result["XformCommonAPI"].GetXformVectorsByAccumulation.func_doc = """GetXformVectorsByAccumulation(translation, rotation, scale, pivot, rotOrder, time) -> bool
Retrieve values of the various component xformOps at a given ``time``
.
Identity values are filled in for the component xformOps that don't
exist or don't have an authored value.
This method allows some additional flexibility for xform schemas that
do not strictly adhere to the xformCommonAPI. For incompatible
schemas, this method will attempt to reduce the schema into one from
which component vectors can be extracted by accumulating xformOp
transforms of the common types.
When the underlying xformable has a compatible xform schema, the usual
component value extraction method is used instead. When the xform
schema is incompatible and it cannot be reduced by accumulating
transforms, it performs a full-on matrix decomposition to XYZ rotation
order.
Parameters
----------
translation : Vec3d
rotation : Vec3f
scale : Vec3f
pivot : Vec3f
rotOrder : XformCommonAPI.RotationOrder
time : TimeCode
"""
result["XformCommonAPI"].GetResetXformStack.func_doc = """GetResetXformStack() -> bool
Returns whether the xformable resets the transform stack.
i.e., does not inherit the parent transformation.
"""
result["XformCommonAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["XformCommonAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> XformCommonAPI
Return a UsdGeomXformCommonAPI holding the prim adhering to this
schema at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdGeomXformCommonAPI(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["XformCommonAPI"].ConvertRotationOrderToOpType.func_doc = """**classmethod** ConvertRotationOrderToOpType(rotOrder) -> XformOp.Type
Converts the given ``rotOrder`` to the corresponding value in the
UsdGeomXformOp::Type enum.
For example, RotationOrderYZX corresponds to TypeRotateYZX. Raises a
coding error if ``rotOrder`` is not one of the named enumerators of
RotationOrder.
Parameters
----------
rotOrder : RotationOrder
"""
result["XformCommonAPI"].ConvertOpTypeToRotationOrder.func_doc = """**classmethod** ConvertOpTypeToRotationOrder(opType) -> RotationOrder
Converts the given ``opType`` to the corresponding value in the
UsdGeomXformCommonAPI::RotationOrder enum.
For example, TypeRotateYZX corresponds to RotationOrderYZX. Raises a
coding error if ``opType`` is not convertible to RotationOrder (i.e.,
if it isn't a three-axis rotation) and returns the default
RotationOrderXYZ instead.
Parameters
----------
opType : XformOp.Type
"""
result["XformCommonAPI"].CanConvertOpTypeToRotationOrder.func_doc = """**classmethod** CanConvertOpTypeToRotationOrder(opType) -> bool
Whether the given ``opType`` has a corresponding value in the
UsdGeomXformCommonAPI::RotationOrder enum (i.e., whether it is a
three-axis rotation).
Parameters
----------
opType : XformOp.Type
"""
result["XformCommonAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
"""
result["XformOp"].__doc__ = """
Schema wrapper for UsdAttribute for authoring and computing
transformation operations, as consumed by UsdGeomXformable schema.
The semantics of an op are determined primarily by its name, which
allows us to decode an op very efficiently. All ops are independent
attributes, which must live in the"xformOp"property namespace. The
op's primary name within the namespace must be one of
UsdGeomXformOpTypes, which determines the type of transformation
operation, and its secondary name (or suffix) within the namespace
(which is not required to exist), can be any name that distinguishes
it from other ops of the same type. Suffixes are generally imposed by
higer level xform API schemas.
**On packing order of rotateABC triples** The order in which the axis
rotations are recorded in a Vec3\\* for the six *rotateABC* Euler
triples **is always the same:** vec[0] = X, vec[1] = Y, vec[2] = Z.
The *A*, *B*, *C* in the op name dictate the order in which their
corresponding elements are consumed by the rotation, not how they are
laid out.
"""
result["XformOp"].GetOpTypeToken.func_doc = """**classmethod** GetOpTypeToken(opType) -> str
Returns the TfToken used to encode the given ``opType`` .
Note that an empty TfToken is used to represent TypeInvalid
Parameters
----------
opType : Type
"""
result["XformOp"].GetOpTypeEnum.func_doc = """**classmethod** GetOpTypeEnum(opTypeToken) -> Type
Returns the Type enum associated with the given ``opTypeToken`` .
Parameters
----------
opTypeToken : str
"""
result["XformOp"].GetOpName.func_doc = """**classmethod** GetOpName(opType, opSuffix, inverse) -> str
Returns the xformOp's name as it appears in xformOpOrder, given the
opType, the (optional) suffix and whether it is an inverse operation.
Parameters
----------
opType : Type
opSuffix : str
inverse : bool
----------------------------------------------------------------------
GetOpName() -> str
Returns the opName as it appears in the xformOpOrder attribute.
This will begin with"!invert!:xformOp:"if it is an inverse xform
operation. If it is not an inverse xformOp, it will begin
with'xformOp:'.
This will be empty for an invalid xformOp.
"""
result["XformOp"].GetOpType.func_doc = """GetOpType() -> Type
Return the operation type of this op, one of UsdGeomXformOp::Type.
"""
result["XformOp"].GetPrecision.func_doc = """GetPrecision() -> Precision
Returns the precision level of the xform op.
"""
result["XformOp"].IsInverseOp.func_doc = """IsInverseOp() -> bool
Returns whether the xformOp represents an inverse operation.
"""
result["XformOp"].GetOpTransform.func_doc = """**classmethod** GetOpTransform(time) -> Matrix4d
Return the 4x4 matrix that applies the transformation encoded in this
op at ``time`` .
Returns the identity matrix and issues a coding error if the op is
invalid.
If the op is valid, but has no authored value, the identity matrix is
returned and no error is issued.
Parameters
----------
time : TimeCode
----------------------------------------------------------------------
GetOpTransform(opType, opVal, isInverseOp) -> Matrix4d
Return the 4x4 matrix that applies the transformation encoded by op
``opType`` and data value ``opVal`` .
If ``isInverseOp`` is true, then the inverse of the tranformation
represented by the op/value pair is returned.
An error will be issued if ``opType`` is not one of the values in the
enum UsdGeomXformOp::Type or if ``opVal`` cannot be converted to a
suitable input to ``opType``
Parameters
----------
opType : Type
opVal : VtValue
isInverseOp : bool
"""
result["XformOp"].MightBeTimeVarying.func_doc = """MightBeTimeVarying() -> bool
Determine whether there is any possibility that this op's value may
vary over time.
The determination is based on a snapshot of the authored state of the
op, and may become invalid in the face of further authoring.
"""
result["XformOp"].GetAttr.func_doc = """GetAttr() -> Attribute
Explicit UsdAttribute extractor.
"""
result["XformOp"].IsDefined.func_doc = """IsDefined() -> bool
Return true if the wrapped UsdAttribute::IsDefined() , and in addition
the attribute is identified as a XformOp.
"""
result["XformOp"].GetName.func_doc = """GetName() -> str
UsdAttribute::GetName()
"""
result["XformOp"].GetBaseName.func_doc = """GetBaseName() -> str
UsdAttribute::GetBaseName()
"""
result["XformOp"].GetNamespace.func_doc = """GetNamespace() -> str
UsdAttribute::GetNamespace()
"""
result["XformOp"].SplitName.func_doc = """SplitName() -> list[str]
UsdAttribute::SplitName()
"""
result["XformOp"].GetTypeName.func_doc = """GetTypeName() -> ValueTypeName
UsdAttribute::GetTypeName()
"""
result["XformOp"].Get.func_doc = """Get(value, time) -> bool
Get the attribute value of the XformOp at ``time`` .
For inverted ops, this returns the raw, uninverted value.
Parameters
----------
value : T
time : TimeCode
"""
result["XformOp"].Set.func_doc = """Set(value, time) -> bool
Set the attribute value of the XformOp at ``time`` .
This only works on non-inverse operations. If invoked on an inverse
xform operation, a coding error is issued and no value is authored.
Parameters
----------
value : T
time : TimeCode
"""
result["XformOp"].GetTimeSamples.func_doc = """GetTimeSamples(times) -> bool
Populates the list of time samples at which the associated attribute
is authored.
Parameters
----------
times : list[float]
"""
result["XformOp"].GetTimeSamplesInInterval.func_doc = """GetTimeSamplesInInterval(interval, times) -> bool
Populates the list of time samples within the given ``interval`` , at
which the associated attribute is authored.
Parameters
----------
interval : Interval
times : list[float]
"""
result["XformOp"].GetNumTimeSamples.func_doc = """GetNumTimeSamples() -> int
Returns the number of time samples authored for this xformOp.
"""
result["XformOp"].__init__.func_doc = """__init__(attr, isInverseOp, arg3)
Parameters
----------
attr : Attribute
isInverseOp : bool
arg3 : _ValidAttributeTagType
----------------------------------------------------------------------
__init__(query, isInverseOp, arg3)
Parameters
----------
query : AttributeQuery
isInverseOp : bool
arg3 : _ValidAttributeTagType
----------------------------------------------------------------------
__init__(prim, opType, precision, opSuffix, inverse)
Parameters
----------
prim : Prim
opType : Type
precision : Precision
opSuffix : str
inverse : bool
----------------------------------------------------------------------
__init__()
----------------------------------------------------------------------
__init__(attr, isInverseOp)
Speculative constructor that will produce a valid UsdGeomXformOp when
``attr`` already represents an attribute that is XformOp, and produces
an *invalid* XformOp otherwise (i.e.
explicit-bool conversion operator will return false).
Calling ``UsdGeomXformOp::IsXformOp(attr)`` will return the same truth
value as this constructor, but if you plan to subsequently use the
XformOp anyways, just use this constructor.
``isInverseOp`` is set to true to indicate an inverse transformation
op.
This constructor exists mainly for internal use. Clients should use
AddXformOp API (or one of Add\\*Op convenience API) to create and
retain a copy of an UsdGeomXformOp object.
Parameters
----------
attr : Attribute
isInverseOp : bool
"""
result["XformOp"].Type.__doc__ = """
Enumerates the set of all transformation operation types.
"""
result["XformOp"].Precision.__doc__ = """
Precision with which the value of the tranformation operation is
encoded.
"""
result["GetStageUpAxis"].func_doc = """GetStageUpAxis(stage) -> str
Fetch and return ``stage`` 's upAxis.
If unauthored, will return the value provided by
UsdGeomGetFallbackUpAxis() . Exporters, however, are strongly
encouraged to always set the upAxis for every USD file they create.
one of: UsdGeomTokens->y or UsdGeomTokens->z, unless there was an
error, in which case returns an empty TfToken
Encoding Stage UpAxis
Parameters
----------
stage : UsdStageWeak
"""
result["SetStageUpAxis"].func_doc = """SetStageUpAxis(stage, axis) -> bool
Set ``stage`` 's upAxis to ``axis`` , which must be one of
UsdGeomTokens->y or UsdGeomTokens->z.
UpAxis is stage-level metadata, therefore see UsdStage::SetMetadata()
.
true if upAxis was successfully set. The stage's UsdEditTarget must be
either its root layer or session layer.
Encoding Stage UpAxis
Parameters
----------
stage : UsdStageWeak
axis : str
"""
result["GetFallbackUpAxis"].func_doc = """GetFallbackUpAxis() -> str
Return the site-level fallback up axis as a TfToken.
In a generic installation of USD, the fallback will be"Y". This can be
changed to"Z"by adding, in a plugInfo.json file discoverable by USD's
PlugPlugin mechanism:
.. code-block:: text
"UsdGeomMetrics": {
"upAxis": "Z"
}
If more than one such entry is discovered and the values for upAxis
differ, we will issue a warning during the first call to this
function, and ignore all of them, so that we devolve to deterministic
behavior of Y up axis until the problem is rectified.
"""
result["LinearUnits"].__doc__ = """"""
result["GetStageMetersPerUnit"].func_doc = """GetStageMetersPerUnit(stage) -> float
Return *stage* 's authored *metersPerUnit*, or 0.01 if unauthored.
Encoding Stage Linear Units
Parameters
----------
stage : UsdStageWeak
"""
result["StageHasAuthoredMetersPerUnit"].func_doc = """StageHasAuthoredMetersPerUnit(stage) -> bool
Return whether *stage* has an authored *metersPerUnit*.
Encoding Stage Linear Units
Parameters
----------
stage : UsdStageWeak
"""
result["SetStageMetersPerUnit"].func_doc = """SetStageMetersPerUnit(stage, metersPerUnit) -> bool
Author *stage* 's *metersPerUnit*.
true if metersPerUnit was successfully set. The stage's UsdEditTarget
must be either its root layer or session layer.
Encoding Stage Linear Units
Parameters
----------
stage : UsdStageWeak
metersPerUnit : float
"""
result["LinearUnitsAre"].func_doc = """LinearUnitsAre(authoredUnits, standardUnits, epsilon) -> bool
Return *true* if the two given metrics are within the provided
relative *epsilon* of each other, when you need to know an absolute
metric rather than a scaling factor.
Use like so:
.. code-block:: text
double stageUnits = UsdGeomGetStageMetersPerUnit(stage);
if (UsdGeomLinearUnitsAre(stageUnits, UsdGeomLinearUnits::meters))
// do something for meters
else if (UsdGeomLinearUnitsAre(stageUnits, UsdGeomLinearUnits::feet))
// do something for feet
*false* if either input is zero or negative, otherwise relative
floating-point comparison between the two inputs.
Encoding Stage Linear Units
Parameters
----------
authoredUnits : float
standardUnits : float
epsilon : float
""" | 403,670 | Python | 23.166128 | 237 | 0.737736 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdMedia/__DOC.py | def Execute(result):
result["SpatialAudio"].__doc__ = """
The SpatialAudio primitive defines basic properties for encoding
playback of an audio file or stream within a USD Stage. The
SpatialAudio schema derives from UsdGeomXformable since it can support
full spatial audio while also supporting non-spatial mono and stereo
sounds. One or more SpatialAudio prims can be placed anywhere in the
namespace, though it is advantageous to place truly spatial audio
prims under/inside the models from which the sound emanates, so that
the audio prim need only be transformed relative to the model, rather
than copying its animation.
Timecode Attributes and Time Scaling
====================================
*startTime* and *endTime* are timecode valued attributes which gives
them the special behavior that layer offsets affecting the layer in
which one of these values is authored are applied to the attribute's
value itself during value resolution. This allows audio playback to be
kept in sync with time sampled animation as the animation is affected
by layer offsets in the composition. But this behavior brings with it
some interesting edge cases and caveats when it comes to layer offsets
that include scale.
Although authored layer offsets may have a time scale which can scale
the duration between an authored *startTime* and *endTime*, we make no
attempt to infer any playback dilation of the actual audio media
itself. Given that *startTime* and *endTime* can be independently
authored in different layers with differing time scales, it is not
possible, in general, to define an"original timeframe"from which we
can compute a dilation to composed stage-time. Even if we could
compute a composed dilation this way, it would still be impossible to
flatten a stage or layer stack into a single layer and still retain
the composed audio dilation using this schema.
Although we do not expect it to be common, it is possible to apply a
negative time scale to USD layers, which mostly has the effect of
reversing animation in the affected composition. If a negative scale
is applied to a composition that contains authored *startTime* and
*endTime*, it will reverse their relative ordering in time. Therefore,
we stipulate when *playbackMode*
is"onceFromStartToEnd"or"loopFromStartToEnd", if *endTime* is less
than *startTime*, then begin playback at *endTime*, and continue until
*startTime*. When *startTime* and *endTime* are inverted, we do not,
however, stipulate that playback of the audio media itself be
inverted, since doing so"successfully"would require perfect knowledge
of when, within the audio clip, relevant audio ends (so that we know
how to offset the reversed audio to align it so that we reach
the"beginning"at *startTime*), and sounds played in reverse are not
likely to produce desirable results.
For any described attribute *Fallback* *Value* or *Allowed* *Values*
below that are text/tokens, the actual token is published and defined
in UsdMediaTokens. So to set an attribute to the value"rightHanded",
use UsdMediaTokens->rightHanded as the value.
"""
result["SpatialAudio"].__init__.func_doc = """__init__(prim)
Construct a UsdMediaSpatialAudio on UsdPrim ``prim`` .
Equivalent to UsdMediaSpatialAudio::Get (prim.GetStage(),
prim.GetPath()) for a *valid* ``prim`` , but will not immediately
throw an error for an invalid ``prim``
Parameters
----------
prim : Prim
----------------------------------------------------------------------
__init__(schemaObj)
Construct a UsdMediaSpatialAudio on the prim held by ``schemaObj`` .
Should be preferred over UsdMediaSpatialAudio (schemaObj.GetPrim()),
as it preserves SchemaBase state.
Parameters
----------
schemaObj : SchemaBase
"""
result["SpatialAudio"].GetFilePathAttr.func_doc = """GetFilePathAttr() -> Attribute
Path to the audio file.
In general, the formats allowed for audio files is no more constrained
by USD than is image-type. As with images, however, usdz has stricter
requirements based on DMA and format support in browsers and consumer
devices. The allowed audio filetypes for usdz are M4A, MP3, WAV (in
order of preference).
Usdz Specification
Declaration
``uniform asset filePath = @@``
C++ Type
SdfAssetPath
Usd Type
SdfValueTypeNames->Asset
Variability
SdfVariabilityUniform
"""
result["SpatialAudio"].CreateFilePathAttr.func_doc = """CreateFilePathAttr(defaultValue, writeSparsely) -> Attribute
See GetFilePathAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SpatialAudio"].GetAuralModeAttr.func_doc = """GetAuralModeAttr() -> Attribute
Determines how audio should be played.
Valid values are:
- spatial: Play the audio in 3D space if the device can support
spatial audio. if not, fall back to mono.
- nonSpatial: Play the audio without regard to the SpatialAudio
prim's position. If the audio media contains any form of stereo or
other multi-channel sound, it is left to the application to determine
whether the listener's position should be taken into account. We
expect nonSpatial to be the choice for ambient sounds and music sound-
tracks.
Declaration
``uniform token auralMode ="spatial"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
spatial, nonSpatial
"""
result["SpatialAudio"].CreateAuralModeAttr.func_doc = """CreateAuralModeAttr(defaultValue, writeSparsely) -> Attribute
See GetAuralModeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SpatialAudio"].GetPlaybackModeAttr.func_doc = """GetPlaybackModeAttr() -> Attribute
Along with *startTime* and *endTime*, determines when the audio
playback should start and stop during the stage's animation playback
and whether the audio should loop during its duration.
Valid values are:
- onceFromStart: Play the audio once, starting at *startTime*,
continuing until the audio completes.
- onceFromStartToEnd: Play the audio once beginning at *startTime*,
continuing until *endTime* or until the audio completes, whichever
comes first.
- loopFromStart: Start playing the audio at *startTime* and
continue looping through to the stage's authored *endTimeCode*.
- loopFromStartToEnd: Start playing the audio at *startTime* and
continue looping through, stopping the audio at *endTime*.
- loopFromStage: Start playing the audio at the stage's authored
*startTimeCode* and continue looping through to the stage's authored
*endTimeCode*. This can be useful for ambient sounds that should
always be active.
Declaration
``uniform token playbackMode ="onceFromStart"``
C++ Type
TfToken
Usd Type
SdfValueTypeNames->Token
Variability
SdfVariabilityUniform
Allowed Values
onceFromStart, onceFromStartToEnd, loopFromStart, loopFromStartToEnd,
loopFromStage
"""
result["SpatialAudio"].CreatePlaybackModeAttr.func_doc = """CreatePlaybackModeAttr(defaultValue, writeSparsely) -> Attribute
See GetPlaybackModeAttr() , and also Create vs Get Property Methods
for when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SpatialAudio"].GetStartTimeAttr.func_doc = """GetStartTimeAttr() -> Attribute
Expressed in the timeCodesPerSecond of the containing stage,
*startTime* specifies when the audio stream will start playing during
animation playback.
This value is ignored when *playbackMode* is set to loopFromStage as,
in this mode, the audio will always start at the stage's authored
*startTimeCode*. Note that *startTime* is expressed as a timecode so
that the stage can properly apply layer offsets when resolving its
value. See Timecode Attributes and Time Scaling for more details and
caveats.
Declaration
``uniform timecode startTime = 0``
C++ Type
SdfTimeCode
Usd Type
SdfValueTypeNames->TimeCode
Variability
SdfVariabilityUniform
"""
result["SpatialAudio"].CreateStartTimeAttr.func_doc = """CreateStartTimeAttr(defaultValue, writeSparsely) -> Attribute
See GetStartTimeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SpatialAudio"].GetEndTimeAttr.func_doc = """GetEndTimeAttr() -> Attribute
Expressed in the timeCodesPerSecond of the containing stage, *endTime*
specifies when the audio stream will cease playing during animation
playback if the length of the referenced audio clip is longer than
desired.
This only applies if *playbackMode* is set to onceFromStartToEnd or
loopFromStartToEnd, otherwise the *endTimeCode* of the stage is used
instead of *endTime*. If *endTime* is less than *startTime*, it is
expected that the audio will instead be played from *endTime* to
*startTime*. Note that *endTime* is expressed as a timecode so that
the stage can properly apply layer offsets when resolving its value.
See Timecode Attributes and Time Scaling for more details and caveats.
Declaration
``uniform timecode endTime = 0``
C++ Type
SdfTimeCode
Usd Type
SdfValueTypeNames->TimeCode
Variability
SdfVariabilityUniform
"""
result["SpatialAudio"].CreateEndTimeAttr.func_doc = """CreateEndTimeAttr(defaultValue, writeSparsely) -> Attribute
See GetEndTimeAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SpatialAudio"].GetMediaOffsetAttr.func_doc = """GetMediaOffsetAttr() -> Attribute
Expressed in seconds, *mediaOffset* specifies the offset from the
referenced audio file's beginning at which we should begin playback
when stage playback reaches the time that prim's audio should start.
If the prim's *playbackMode* is a looping mode, *mediaOffset* is
applied only to the first run-through of the audio clip; the second
and all other loops begin from the start of the audio clip.
Declaration
``uniform double mediaOffset = 0``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
Variability
SdfVariabilityUniform
"""
result["SpatialAudio"].CreateMediaOffsetAttr.func_doc = """CreateMediaOffsetAttr(defaultValue, writeSparsely) -> Attribute
See GetMediaOffsetAttr() , and also Create vs Get Property Methods for
when to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SpatialAudio"].GetGainAttr.func_doc = """GetGainAttr() -> Attribute
Multiplier on the incoming audio signal.
A value of 0"mutes"the signal. Negative values will be clamped to 0.
Declaration
``double gain = 1``
C++ Type
double
Usd Type
SdfValueTypeNames->Double
"""
result["SpatialAudio"].CreateGainAttr.func_doc = """CreateGainAttr(defaultValue, writeSparsely) -> Attribute
See GetGainAttr() , and also Create vs Get Property Methods for when
to use Get vs Create.
If specified, author ``defaultValue`` as the attribute's default,
sparsely (when it makes sense to do so) if ``writeSparsely`` is
``true`` - the default for ``writeSparsely`` is ``false`` .
Parameters
----------
defaultValue : VtValue
writeSparsely : bool
"""
result["SpatialAudio"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken]
Return a vector of names of all pre-declared attributes for this
schema class and all its ancestor classes.
Does not include attributes that may be authored by custom/extended
methods of the schemas involved.
Parameters
----------
includeInherited : bool
"""
result["SpatialAudio"].Get.func_doc = """**classmethod** Get(stage, path) -> SpatialAudio
Return a UsdMediaSpatialAudio holding the prim adhering to this schema
at ``path`` on ``stage`` .
If no prim exists at ``path`` on ``stage`` , or if the prim at that
path does not adhere to this schema, return an invalid schema object.
This is shorthand for the following:
.. code-block:: text
UsdMediaSpatialAudio(stage->GetPrimAtPath(path));
Parameters
----------
stage : Stage
path : Path
"""
result["SpatialAudio"].Define.func_doc = """**classmethod** Define(stage, path) -> SpatialAudio
Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is
defined (according to UsdPrim::IsDefined() ) on this stage.
If a prim adhering to this schema at ``path`` is already defined on
this stage, return that prim. Otherwise author an *SdfPrimSpec* with
*specifier* == *SdfSpecifierDef* and this schema's prim type name for
the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s
with ``specifier`` == *SdfSpecifierDef* and empty typeName at the
current EditTarget for any nonexistent, or existing but not *Defined*
ancestors.
The given *path* must be an absolute prim path that does not contain
any variant selections.
If it is impossible to author any of the necessary PrimSpecs, (for
example, in case *path* cannot map to the current UsdEditTarget 's
namespace) issue an error and return an invalid *UsdPrim*.
Note that this method may return a defined prim whose typeName does
not specify this schema class, in case a stronger typeName opinion
overrides the opinion at the current EditTarget.
Parameters
----------
stage : Stage
path : Path
"""
result["SpatialAudio"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type
""" | 14,690 | Python | 25.047872 | 138 | 0.752144 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Glf/__DOC.py | def Execute(result):
result["DrawTarget"].__doc__ = """
A class representing a GL render target with mutliple image
attachments.
A DrawTarget is essentially a custom render pass into which several
arbitrary variables can be output into. These can later be used as
texture samplers by GLSL shaders.
The DrawTarget maintains a map of named attachments that correspond to
GL_TEXTURE_2D mages. By default, DrawTargets also create a depth
component that is used both as a depth buffer during the draw pass,
and can later be accessed as a regular GL_TEXTURE_2D data. Stencils
are also available (by setting the format to GL_DEPTH_STENCIL and the
internalFormat to GL_DEPTH24_STENCIL8)
"""
result["DrawTarget"].AddAttachment.func_doc = """AddAttachment(name, format, type, internalFormat) -> None
Add an attachment to the DrawTarget.
Parameters
----------
name : str
format : GLenum
type : GLenum
internalFormat : GLenum
"""
result["DrawTarget"].WriteToFile.func_doc = """WriteToFile(name, filename, viewMatrix, projectionMatrix) -> bool
Write the Attachment buffer to an image file (debugging).
Parameters
----------
name : str
filename : str
viewMatrix : Matrix4d
projectionMatrix : Matrix4d
"""
result["DrawTarget"].Bind.func_doc = """Bind() -> None
Binds the framebuffer.
"""
result["DrawTarget"].Unbind.func_doc = """Unbind() -> None
Unbinds the framebuffer.
"""
result["DrawTarget"].__init__.func_doc = """__init__(size, requestMSAA)
Parameters
----------
size : Vec2i
requestMSAA : bool
----------------------------------------------------------------------
__init__(drawtarget)
Parameters
----------
drawtarget : DrawTarget
"""
result["GLQueryObject"].__doc__ = """
Represents a GL query object in Glf
"""
result["GLQueryObject"].__init__.func_doc = """__init__()
----------------------------------------------------------------------
__init__(arg1)
Parameters
----------
arg1 : GLQueryObject
"""
result["GLQueryObject"].Begin.func_doc = """Begin(target) -> None
Begin query for the given ``target`` target has to be one of
GL_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED,
GL_ANY_SAMPLES_PASSED_CONSERVATIVE, GL_PRIMITIVES_GENERATED
GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN GL_TIME_ELAPSED,
GL_TIMESTAMP.
Parameters
----------
target : GLenum
"""
result["GLQueryObject"].BeginSamplesPassed.func_doc = """BeginSamplesPassed() -> None
equivalent to Begin(GL_SAMPLES_PASSED).
The number of samples that pass the depth test for all drawing
commands within the scope of the query will be returned.
"""
result["GLQueryObject"].BeginPrimitivesGenerated.func_doc = """BeginPrimitivesGenerated() -> None
equivalent to Begin(GL_PRIMITIVES_GENERATED).
The number of primitives sent to the rasterizer by the scoped drawing
command will be returned.
"""
result["GLQueryObject"].BeginTimeElapsed.func_doc = """BeginTimeElapsed() -> None
equivalent to Begin(GL_TIME_ELAPSED).
The time that it takes for the GPU to execute all of the scoped
commands will be returned in nanoseconds.
"""
result["GLQueryObject"].End.func_doc = """End() -> None
End query.
"""
result["GLQueryObject"].GetResult.func_doc = """GetResult() -> int
Return the query result (synchronous) stalls CPU until the result
becomes available.
"""
result["GLQueryObject"].GetResultNoWait.func_doc = """GetResultNoWait() -> int
Return the query result (asynchronous) returns 0 if the result hasn't
been available.
"""
result["SimpleLight"].__doc__ = """"""
result["SimpleLight"].__init__.func_doc = """__init__(position)
Parameters
----------
position : Vec4f
"""
result["SimpleMaterial"].__doc__ = """"""
result["SimpleMaterial"].__init__.func_doc = """__init__()
"""
result["Texture"].__doc__ = """
Represents a texture object in Glf.
A texture is typically defined by reading texture image data from an
image file but a texture might also represent an attachment of a draw
target.
"""
result["Texture"].GetTextureMemoryAllocated.func_doc = """**classmethod** GetTextureMemoryAllocated() -> int
static reporting function
"""
result["SimpleLight"].transform = property(result["SimpleLight"].transform.fget, result["SimpleLight"].transform.fset, result["SimpleLight"].transform.fdel, """type : None
----------------------------------------------------------------------
type : Matrix4d
""")
result["SimpleLight"].ambient = property(result["SimpleLight"].ambient.fget, result["SimpleLight"].ambient.fset, result["SimpleLight"].ambient.fdel, """type : None
----------------------------------------------------------------------
type : Vec4f
""")
result["SimpleLight"].diffuse = property(result["SimpleLight"].diffuse.fget, result["SimpleLight"].diffuse.fset, result["SimpleLight"].diffuse.fdel, """type : None
----------------------------------------------------------------------
type : Vec4f
""")
result["SimpleLight"].specular = property(result["SimpleLight"].specular.fget, result["SimpleLight"].specular.fset, result["SimpleLight"].specular.fdel, """type : None
----------------------------------------------------------------------
type : Vec4f
""")
result["SimpleLight"].position = property(result["SimpleLight"].position.fget, result["SimpleLight"].position.fset, result["SimpleLight"].position.fdel, """type : None
----------------------------------------------------------------------
type : Vec4f
""")
result["SimpleLight"].spotDirection = property(result["SimpleLight"].spotDirection.fget, result["SimpleLight"].spotDirection.fset, result["SimpleLight"].spotDirection.fdel, """type : None
----------------------------------------------------------------------
type : Vec3f
""")
result["SimpleLight"].spotCutoff = property(result["SimpleLight"].spotCutoff.fget, result["SimpleLight"].spotCutoff.fset, result["SimpleLight"].spotCutoff.fdel, """type : None
----------------------------------------------------------------------
type : float
""")
result["SimpleLight"].spotFalloff = property(result["SimpleLight"].spotFalloff.fget, result["SimpleLight"].spotFalloff.fset, result["SimpleLight"].spotFalloff.fdel, """type : None
----------------------------------------------------------------------
type : float
""")
result["SimpleLight"].attenuation = property(result["SimpleLight"].attenuation.fget, result["SimpleLight"].attenuation.fset, result["SimpleLight"].attenuation.fdel, """type : None
----------------------------------------------------------------------
type : Vec3f
""")
result["SimpleLight"].shadowMatrices = property(result["SimpleLight"].shadowMatrices.fget, result["SimpleLight"].shadowMatrices.fset, result["SimpleLight"].shadowMatrices.fdel, """type : None
----------------------------------------------------------------------
type : list[Matrix4d]
""")
result["SimpleLight"].shadowResolution = property(result["SimpleLight"].shadowResolution.fget, result["SimpleLight"].shadowResolution.fset, result["SimpleLight"].shadowResolution.fdel, """type : None
----------------------------------------------------------------------
type : int
""")
result["SimpleLight"].shadowBias = property(result["SimpleLight"].shadowBias.fget, result["SimpleLight"].shadowBias.fset, result["SimpleLight"].shadowBias.fdel, """type : None
----------------------------------------------------------------------
type : float
""")
result["SimpleLight"].shadowBlur = property(result["SimpleLight"].shadowBlur.fget, result["SimpleLight"].shadowBlur.fset, result["SimpleLight"].shadowBlur.fdel, """type : None
----------------------------------------------------------------------
type : float
""")
result["SimpleLight"].shadowIndexStart = property(result["SimpleLight"].shadowIndexStart.fget, result["SimpleLight"].shadowIndexStart.fset, result["SimpleLight"].shadowIndexStart.fdel, """type : None
----------------------------------------------------------------------
type : int
""")
result["SimpleLight"].shadowIndexEnd = property(result["SimpleLight"].shadowIndexEnd.fget, result["SimpleLight"].shadowIndexEnd.fset, result["SimpleLight"].shadowIndexEnd.fdel, """type : None
----------------------------------------------------------------------
type : int
""")
result["SimpleLight"].hasShadow = property(result["SimpleLight"].hasShadow.fget, result["SimpleLight"].hasShadow.fset, result["SimpleLight"].hasShadow.fdel, """type : None
""")
result["SimpleLight"].isCameraSpaceLight = property(result["SimpleLight"].isCameraSpaceLight.fget, result["SimpleLight"].isCameraSpaceLight.fset, result["SimpleLight"].isCameraSpaceLight.fdel, """type : None
----------------------------------------------------------------------
type : bool
""")
result["SimpleLight"].isDomeLight = property(result["SimpleLight"].isDomeLight.fget, result["SimpleLight"].isDomeLight.fset, result["SimpleLight"].isDomeLight.fdel, """type : None
----------------------------------------------------------------------
type : bool
""")
result["SimpleMaterial"].ambient = property(result["SimpleMaterial"].ambient.fget, result["SimpleMaterial"].ambient.fset, result["SimpleMaterial"].ambient.fdel, """type : None
----------------------------------------------------------------------
type : Vec4f
""")
result["SimpleMaterial"].diffuse = property(result["SimpleMaterial"].diffuse.fget, result["SimpleMaterial"].diffuse.fset, result["SimpleMaterial"].diffuse.fdel, """type : None
----------------------------------------------------------------------
type : Vec4f
""")
result["SimpleMaterial"].specular = property(result["SimpleMaterial"].specular.fget, result["SimpleMaterial"].specular.fset, result["SimpleMaterial"].specular.fdel, """type : None
----------------------------------------------------------------------
type : Vec4f
""")
result["SimpleMaterial"].emission = property(result["SimpleMaterial"].emission.fget, result["SimpleMaterial"].emission.fset, result["SimpleMaterial"].emission.fdel, """type : None
----------------------------------------------------------------------
type : Vec4f
""")
result["SimpleMaterial"].shininess = property(result["SimpleMaterial"].shininess.fget, result["SimpleMaterial"].shininess.fset, result["SimpleMaterial"].shininess.fdel, """type : None
----------------------------------------------------------------------
type : float
""")
result["Texture"].memoryUsed = property(result["Texture"].memoryUsed.fget, result["Texture"].memoryUsed.fset, result["Texture"].memoryUsed.fdel, """type : int
Amount of memory used to store the texture.
""")
result["Texture"].memoryRequested = property(result["Texture"].memoryRequested.fget, result["Texture"].memoryRequested.fset, result["Texture"].memoryRequested.fdel, """type : None
Specify the amount of memory the user wishes to allocate to the
texture.
----------------------------------------------------------------------
type : int
Amount of memory the user wishes to allocate to the texture.
""")
result["Texture"].minFilterSupported = property(result["Texture"].minFilterSupported.fget, result["Texture"].minFilterSupported.fset, result["Texture"].minFilterSupported.fdel, """type : bool
""")
result["Texture"].magFilterSupported = property(result["Texture"].magFilterSupported.fget, result["Texture"].magFilterSupported.fset, result["Texture"].magFilterSupported.fdel, """type : bool
""") | 11,422 | Python | 27.274752 | 210 | 0.608125 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Trace/__init__.py | #
# Copyright 2018 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.
#
"""
Trace -- Utilities for counting and recording events.
"""
from pxr import Tf
Tf.PreparePythonModule()
del Tf
import contextlib
@contextlib.contextmanager
def TraceScope(label):
"""A context manager that calls BeginEvent on the global collector on enter
and EndEvent on exit."""
try:
collector = Collector()
eventId = collector.BeginEvent(label)
yield
finally:
collector.EndEvent(label)
del contextlib
def TraceFunction(obj):
"""A decorator that enables tracing the function that it decorates.
If you decorate with 'TraceFunction' the function will be traced in the
global collector."""
collector = Collector()
def decorate(func):
import inspect
if inspect.ismethod(func):
callableTypeLabel = 'method'
classLabel = func.__self__.__class__.__name__+'.'
else:
callableTypeLabel = 'func'
classLabel = ''
module = inspect.getmodule(func)
if module is not None:
moduleLabel = module.__name__+'.'
else:
moduleLabel = ''
label = 'Python {0}: {1}{2}{3}'.format(
callableTypeLabel,
moduleLabel,
classLabel,
func.__name__)
def invoke(*args, **kwargs):
with TraceScope(label):
return func(*args, **kwargs)
invoke.__name__ = func.__name__
# Make sure wrapper function gets attributes of wrapped function.
import functools
return functools.update_wrapper(invoke, func)
return decorate(obj)
def TraceMethod(obj):
"""A convenience. Same as TraceFunction but changes the recorded
label to use the term 'method' rather than 'function'."""
return TraceFunction(obj)
| 2,861 | Python | 30.8 | 80 | 0.665851 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Trace/__DOC.py | def Execute(result):
result["AggregateNode"].__doc__ = """
A representation of a call tree. Each node represents one or more
calls that occurred in the trace. Multiple calls to a child node are
aggregated into one node.
"""
result["Collector"].__doc__ = """
This is a singleton class that records TraceEvent instances and
populates TraceCollection instances.
All public methods of TraceCollector are safe to call from any thread.
"""
result["Collector"].BeginEvent.func_doc = """BeginEvent(key) -> TimeStamp
Record a begin event with *key* if ``Category`` is enabled.
A matching end event is expected some time in the future.
If the key is known at compile time ``BeginScope`` and ``Scope``
methods are preferred because they have lower overhead.
The TimeStamp of the TraceEvent or 0 if the collector is disabled.
BeginScope
Scope
Parameters
----------
key : Key
"""
result["Collector"].BeginEventAtTime.func_doc = """BeginEventAtTime(key, ms) -> None
Record a begin event with *key* at a specified time if ``Category`` is
enabled.
This version of the method allows the passing of a specific number of
elapsed milliseconds, *ms*, to use for this event. This method is used
for testing and debugging code.
Parameters
----------
key : Key
ms : float
"""
result["Collector"].EndEvent.func_doc = """EndEvent(key) -> TimeStamp
Record an end event with *key* if ``Category`` is enabled.
A matching begin event must have preceded this end event.
If the key is known at compile time EndScope and Scope methods are
preferred because they have lower overhead.
The TimeStamp of the TraceEvent or 0 if the collector is disabled.
EndScope
Scope
Parameters
----------
key : Key
"""
result["Collector"].EndEventAtTime.func_doc = """EndEventAtTime(key, ms) -> None
Record an end event with *key* at a specified time if ``Category`` is
enabled.
This version of the method allows the passing of a specific number of
elapsed milliseconds, *ms*, to use for this event. This method is used
for testing and debugging code.
Parameters
----------
key : Key
ms : float
"""
result["Collector"].Clear.func_doc = """Clear() -> None
Clear all pending events from the collector.
No TraceCollection will be made for these events.
"""
result["Collector"].GetLabel.func_doc = """GetLabel() -> str
Return the label associated with this collector.
"""
result["Collector"].__init__.func_doc = """__init__()
"""
result["Reporter"].__doc__ = """
This class converts streams of TraceEvent objects into call trees
which can then be used as a data source to a GUI or written out to a
file.
"""
result["Reporter"].Report.func_doc = """Report(s, iterationCount) -> None
Generates a report to the ostream *s*, dividing all times by
*iterationCount*.
Parameters
----------
s : ostream
iterationCount : int
"""
result["Reporter"].ReportTimes.func_doc = """ReportTimes(s) -> None
Generates a report of the times to the ostream *s*.
Parameters
----------
s : ostream
"""
result["Reporter"].ReportChromeTracing.func_doc = """ReportChromeTracing(s) -> None
Generates a timeline trace report suitable for viewing in Chrome's
trace viewer.
Parameters
----------
s : ostream
"""
result["Reporter"].GetLabel.func_doc = """GetLabel() -> str
Return the label associated with this reporter.
"""
result["Reporter"].UpdateTraceTrees.func_doc = """UpdateTraceTrees() -> None
This fully re-builds the event and aggregate trees from whatever the
current collection holds.
It is ok to call this multiple times in case the collection gets
appended on inbetween.
If we want to have multiple reporters per collector, this will need to
be changed so that all reporters reporting on a collector update their
respective trees.
"""
result["Reporter"].ClearTree.func_doc = """ClearTree() -> None
Clears event tree and counters.
"""
result["Reporter"].__init__.func_doc = """__init__(label, dataSource)
Parameters
----------
label : str
dataSource : DataSource
"""
result["AggregateNode"].inclusiveTime = property(result["AggregateNode"].inclusiveTime.fget, result["AggregateNode"].inclusiveTime.fset, result["AggregateNode"].inclusiveTime.fdel, """type : TimeStamp
Returns the total time of this node ands its children.
""")
result["AggregateNode"].exclusiveTime = property(result["AggregateNode"].exclusiveTime.fget, result["AggregateNode"].exclusiveTime.fset, result["AggregateNode"].exclusiveTime.fdel, """type : TimeStamp
Returns the time spent in this node but not its children.
""")
result["AggregateNode"].count = property(result["AggregateNode"].count.fget, result["AggregateNode"].count.fset, result["AggregateNode"].count.fdel, """type : int
Returns the call count of this node.
``recursive`` determines if recursive calls are counted.
""")
result["AggregateNode"].exclusiveCount = property(result["AggregateNode"].exclusiveCount.fget, result["AggregateNode"].exclusiveCount.fset, result["AggregateNode"].exclusiveCount.fdel, """type : int
Returns the exclusive count.
""")
result["AggregateNode"].children = property(result["AggregateNode"].children.fget, result["AggregateNode"].children.fset, result["AggregateNode"].children.fdel, """type : list[TraceAggregateNodePtr]
""")
result["AggregateNode"].key = property(result["AggregateNode"].key.fget, result["AggregateNode"].key.fset, result["AggregateNode"].key.fdel, """type : str
Returns the node's key.
""")
result["AggregateNode"].id = property(result["AggregateNode"].id.fget, result["AggregateNode"].id.fset, result["AggregateNode"].id.fdel, """type : Id
Returns the node's id.
""")
result["AggregateNode"].expanded = property(result["AggregateNode"].expanded.fget, result["AggregateNode"].expanded.fset, result["AggregateNode"].expanded.fdel, """type : bool
Returns whether this node is expanded in a gui.
----------------------------------------------------------------------
type : None
Sets whether or not this node is expanded in a gui.
""")
result["Collector"].enabled = property(result["Collector"].enabled.fget, result["Collector"].enabled.fset, result["Collector"].enabled.fdel, """**classmethod** type : bool
Returns whether collection of events is enabled for DefaultCategory.
----------------------------------------------------------------------
type : None
Enables or disables collection of events for DefaultCategory.
""")
result["Collector"].pythonTracingEnabled = property(result["Collector"].pythonTracingEnabled.fget, result["Collector"].pythonTracingEnabled.fset, result["Collector"].pythonTracingEnabled.fdel, """type : None
Set whether automatic tracing of all python scopes is enabled.
----------------------------------------------------------------------
type : bool
Returns whether automatic tracing of all python scopes is enabled.
""")
result["Reporter"].groupByFunction = property(result["Reporter"].groupByFunction.fget, result["Reporter"].groupByFunction.fset, result["Reporter"].groupByFunction.fdel, """type : bool
Returns the current group-by-function state.
----------------------------------------------------------------------
type : None
This affects only stack trace event reporting.
If ``true`` then all events in a function are grouped together
otherwise events are split out by address.
""")
result["Reporter"].foldRecursiveCalls = property(result["Reporter"].foldRecursiveCalls.fget, result["Reporter"].foldRecursiveCalls.fset, result["Reporter"].foldRecursiveCalls.fdel, """type : bool
Returns the current setting for recursion folding for stack trace
event reporting.
----------------------------------------------------------------------
type : None
When stack trace event reporting, this sets whether or not recursive
calls are folded in the output.
Recursion folding is useful when the stacks contain deep recursive
structures.
""")
result["Reporter"].shouldAdjustForOverheadAndNoise = property(result["Reporter"].shouldAdjustForOverheadAndNoise.fget, result["Reporter"].shouldAdjustForOverheadAndNoise.fset, result["Reporter"].shouldAdjustForOverheadAndNoise.fdel, """type : None
Set whether or not the reporter should adjust scope times for overhead
and noise.
""")
result["Reporter"].aggregateTreeRoot = property(result["Reporter"].aggregateTreeRoot.fget, result["Reporter"].aggregateTreeRoot.fset, result["Reporter"].aggregateTreeRoot.fdel, """type : AggregateNode
Returns the root node of the aggregated call tree.
""")
result["Reporter"].globalReporter.__doc__ = """**classmethod** globalReporter() -> Reporter
Returns the global reporter.
""" | 8,663 | Python | 23.474576 | 250 | 0.700681 |
omniverse-code/kit/exts/omni.usd.libs/pxr/Trace/__main__.py | #
# Copyright 2018 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.
#
# Execute a script with tracing enabled.
# Usage: python -m pxr.Trace [-o OUTPUT] [-c "command" | FILE]
from __future__ import print_function
import argparse, sys
parser = argparse.ArgumentParser(description='Trace script execution.')
parser.add_argument('-o', dest='output', metavar='OUTPUT',
type=str, default=None,
help='trace output; defaults to stdout')
parser.add_argument('-c', dest='cmd',
type=str,
help='trace <cmd> as a Python script')
parser.add_argument('file', metavar="FILE",
nargs='?',
default=None,
help='script to trace')
args = parser.parse_args()
if not args.cmd and not args.file:
print("Must specify a command or script to trace", file=sys.stderr)
sys.exit(1)
if args.cmd and args.file:
print("Only one of -c or FILE may be specified", file=sys.stderr)
sys.exit(1)
from pxr import Trace
env = {}
# Create a Main function that is traced so we always capture a useful
# top-level scope.
if args.file:
@Trace.TraceFunction
def Main():
exec(compile(open(args.file).read(), args.file, 'exec'), env)
else:
@Trace.TraceFunction
def Main():
exec(args.cmd, env)
try:
Trace.Collector().enabled = True
Main()
finally:
Trace.Collector().enabled = False
if args.output is not None:
Trace.Reporter.globalReporter.Report(args.output)
else:
Trace.Reporter.globalReporter.Report()
| 2,580 | Python | 31.670886 | 74 | 0.68062 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/cameraArgs.py | #
# Copyright 2019 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.
#
def AddCmdlineArgs(argsParser, defaultValue=None, altHelpText=''):
"""
Adds camera-related command line arguments to argsParser.
The resulting 'camera' argument will be an Sdf.Path. If no value is given
and defaultValue is not overridden, 'camera' will be a single-element path
containing the primary camera name.
"""
from pxr import Sdf
from pxr import UsdUtils
if defaultValue is None:
defaultValue = UsdUtils.GetPrimaryCameraName()
helpText = altHelpText
if not helpText:
helpText = (
'Which camera to use - may be given as either just the '
'camera\'s prim name (i.e. just the last element in the prim '
'path), or as a full prim path. Note that if only the prim name '
'is used and more than one camera exists with that name, which '
'one is used will effectively be random (default=%(default)s)')
# This avoids an Sdf warning if an empty string is given, which someone
# might do for example with usdview to open the app using the 'Free' camera
# instead of the primary camera.
def _ToSdfPath(inputArg):
if not inputArg:
return Sdf.Path.emptyPath
return Sdf.Path(inputArg)
argsParser.add_argument('--camera', '-cam', action='store',
type=_ToSdfPath, default=defaultValue, help=helpText)
| 2,434 | Python | 40.982758 | 79 | 0.708299 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/colorArgs.py | #
# Copyright 2019 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.
#
def AddCmdlineArgs(argsParser, defaultValue='sRGB', altHelpText=''):
"""
Adds color-related command line arguments to argsParser.
The resulting 'colorCorrectionMode' argument will be a Python string.
"""
helpText = altHelpText
if not helpText:
helpText = (
'the color correction mode to use (default=%(default)s)')
argsParser.add_argument('--colorCorrectionMode', '-color', action='store',
type=str, default=defaultValue,
choices=['disabled', 'sRGB', 'openColorIO'], help=helpText)
| 1,608 | Python | 40.256409 | 78 | 0.731343 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/complexityArgs.py | #
# Copyright 2019 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.
#
class RefinementComplexities(object):
"""
An enum-like container of standard complexity settings.
"""
class _RefinementComplexity(object):
"""
Class which represents a level of mesh refinement complexity. Each
level has a string identifier, a display name, and a float complexity
value.
"""
def __init__(self, compId, name, value):
self._id = compId
self._name = name
self._value = value
def __repr__(self):
return self.id
@property
def id(self):
return self._id
@property
def name(self):
return self._name
@property
def value(self):
return self._value
LOW = _RefinementComplexity("low", "Low", 1.0)
MEDIUM = _RefinementComplexity("medium", "Medium", 1.1)
HIGH = _RefinementComplexity("high", "High", 1.2)
VERY_HIGH = _RefinementComplexity("veryhigh", "Very High", 1.3)
_ordered = (LOW, MEDIUM, HIGH, VERY_HIGH)
@classmethod
def ordered(cls):
"""
Get a tuple of all complexity levels in order.
"""
return cls._ordered
@classmethod
def fromId(cls, compId):
"""
Get a complexity from its identifier.
"""
matches = [comp for comp in cls._ordered if comp.id == compId]
if len(matches) == 0:
raise ValueError("No complexity with id '{}'".format(compId))
return matches[0]
@classmethod
def fromName(cls, name):
"""
Get a complexity from its display name.
"""
matches = [comp for comp in cls._ordered if comp.name == name]
if len(matches) == 0:
raise ValueError("No complexity with name '{}'".format(name))
return matches[0]
@classmethod
def next(cls, comp):
"""
Get the next highest level of complexity. If already at the highest
level, return it.
"""
if comp not in cls._ordered:
raise ValueError("Invalid complexity: {}".format(comp))
nextIndex = min(
len(cls._ordered) - 1,
cls._ordered.index(comp) + 1)
return cls._ordered[nextIndex]
@classmethod
def prev(cls, comp):
"""
Get the next lowest level of complexity. If already at the lowest
level, return it.
"""
if comp not in cls._ordered:
raise ValueError("Invalid complexity: {}".format(comp))
prevIndex = max(0, cls._ordered.index(comp) - 1)
return cls._ordered[prevIndex]
def AddCmdlineArgs(argsParser, defaultValue=RefinementComplexities.LOW,
altHelpText=''):
"""
Adds complexity-related command line arguments to argsParser.
The resulting 'complexity' argument will be one of the standard
RefinementComplexities.
"""
helpText = altHelpText
if not helpText:
helpText = ('level of refinement to use (default=%(default)s)')
argsParser.add_argument('--complexity', '-c', action='store',
type=RefinementComplexities.fromId,
default=defaultValue,
choices=[c for c in RefinementComplexities.ordered()],
help=helpText)
| 4,297 | Python | 31.315789 | 77 | 0.62788 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/framesArgs.py | #
# Copyright 2019 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.
#
def _GetFloatStringPrecision(floatString):
"""
Gets the floating point precision specified by floatString.
floatString can either contain an actual float in string form, or it can be
a frame placeholder. We simply split the string on the dot (.) and return
the length of the part after the dot, if any.
If there is no dot in the string, a precision of zero is assumed.
"""
floatPrecision = 0
if not floatString:
return floatPrecision
floatStringParts = floatString.split('.')
if len(floatStringParts) > 1:
floatPrecision = len(floatStringParts[1])
return floatPrecision
class FrameSpecIterator(object):
"""
A simple iterator object that handles splitting multiple comma-separated
FrameSpecs into their equivalent UsdUtils.TimeCodeRanges, and then yields
all of the time codes in all of those ranges sequentially when iterated.
This object also stores the minimum floating point precision required to
disambiguate any neighboring time codes in the FrameSpecs given. This can
be used to validate that the frame placeholder in a frame format string has
enough precision to uniquely identify every frame without collisions.
"""
from pxr import UsdUtils
FRAMESPEC_SEPARATOR = ','
def __init__(self, frameSpec):
from pxr import UsdUtils
# Assume all frames are integral until we find a frame spec with a
# non-integral stride.
self._minFloatPrecision = 0
self._timeCodeRanges = []
subFrameSpecs = frameSpec.split(self.FRAMESPEC_SEPARATOR)
for subFrameSpec in subFrameSpecs:
timeCodeRange = UsdUtils.TimeCodeRange.CreateFromFrameSpec(
subFrameSpec)
self._timeCodeRanges.append(timeCodeRange)
specParts = subFrameSpec.split(
UsdUtils.TimeCodeRange.Tokens.StrideSeparator)
if len(specParts) == 2:
stride = specParts[1]
stridePrecision = _GetFloatStringPrecision(stride)
self._minFloatPrecision = max(self._minFloatPrecision,
stridePrecision)
def __iter__(self):
for timeCodeRange in self._timeCodeRanges:
for timeCode in timeCodeRange:
yield timeCode
@property
def minFloatPrecision(self):
return self._minFloatPrecision
def AddCmdlineArgs(argsParser, altDefaultTimeHelpText='', altFramesHelpText=''):
"""
Adds frame-related command line arguments to argsParser.
The resulting 'frames' argument will be an iterable of UsdTimeCodes.
If no command-line arguments are given, 'frames' will be a list containing
only Usd.TimeCode.EarliestTime(). If '--defaultTime' is given, 'frames'
will be a list containing only Usd.TimeCode.Default(). Otherwise,
'--frames' must be given a FrameSpec (or a comma-separated list of
multiple FrameSpecs), and 'frames' will be a FrameSpecIterator which when
iterated will yield the time codes specified by the FrameSpec(s).
"""
timeGroup = argsParser.add_mutually_exclusive_group()
helpText = altDefaultTimeHelpText
if not helpText:
helpText = (
'explicitly operate at the Default time code (the default '
'behavior is to operate at the Earliest time code)')
timeGroup.add_argument('--defaultTime', '-d', action='store_true',
dest='defaultTime', help=helpText)
helpText = altFramesHelpText
if not helpText:
helpText = (
'specify FrameSpec(s) of the time codes to operate on - A '
'FrameSpec consists of up to three floating point values for the '
'start time code, end time code, and stride of a time code range. '
'A single time code can be specified, or a start and end time '
'code can be specified separated by a colon (:). When a start '
'and end time code are specified, the stride may optionally be '
'specified as well, separating it from the start and end time '
'codes with (x). Multiple FrameSpecs can be combined as a '
'comma-separated list. The following are examples of valid '
'FrameSpecs: 123 - 101:105 - 105:101 - 101:109x2 - 101:110x2 - '
'101:104x0.5')
timeGroup.add_argument('--frames', '-f', action='store', type=str,
dest='frames', metavar='FRAMESPEC[,FRAMESPEC...]',
help=helpText)
def GetFramePlaceholder(frameFormat):
"""
Gets the frame placeholder in a frame format string.
This function expects the input frameFormat string to contain exactly one
frame placeholder. The placeholder must be composed of exactly one or two
groups of one or more hashes ('#'), and if there are two, they must be
separated by a dot ('.').
If no such placeholder exists in the frame format string, None is returned.
"""
if not frameFormat:
return None
import re
PLACEHOLDER_PATTERN = r'^[^#]*(?P<placeholder>#+(\.#+)?)[^#]*$'
matches = re.search(PLACEHOLDER_PATTERN, frameFormat)
if not matches:
return None
placeholder = matches.group(1)
return placeholder
def ConvertFramePlaceholderToFloatSpec(frameFormat):
"""
Converts the frame placeholder in a frame format string to a Python
{}-style float specifier for use with string.format().
This function expects the input frameFormat string to contain exactly one
frame placeholder. The placeholder must be composed of exactly one or two
groups of one or more hashes ('#'), and if there are two, they must be
separated by a dot ('.').
The hashes after the dot indicate the floating point precision to use in
the frame numbers inserted into the frame format string. If there is only
a single group of hashes, the precision is zero and the inserted frame
numbers will be integer values.
The overall width of the frame placeholder specifies the minimum width to
use when inserting frame numbers into the frame format string. Formatted
frame numbers smaller than the minimum width will be zero-padded on the
left until they reach the minimum width.
If the input frame format string does not contain exactly one frame
placeholder, this function will return None, indicating that this frame
format string cannot be used when operating with a frame range.
"""
placeholder = GetFramePlaceholder(frameFormat)
if not placeholder:
return None
# Frame numbers are zero-padded up to the field width.
specFill = 0
# The full width of the placeholder determines the minimum field width.
specWidth = len(placeholder)
# The hashes after the dot, if any, determine the precision. If there are
# none, integer frame numbers are used.
specPrecision = 0
parts = placeholder.split('.')
if len(parts) > 1:
specPrecision = len(parts[1])
floatSpec = ('{frame:' +
'{fill}{width}.{precision}f'.format(fill=specFill,
width=specWidth, precision=specPrecision) +
'}')
return frameFormat.replace(placeholder, floatSpec)
def ValidateCmdlineArgs(argsParser, args, frameFormatArgName=None):
"""
Validates the frame-related arguments in args parsed by argsParser.
This populates 'frames' with the appropriate iterable based on the
command-line arguments given, so it should be called after parse_args() is
called on argsParser.
When working with frame ranges, particularly when writing out images for
each frame, it is common to also have command-line arguments such as an
output image path for specifying where those images should be written. The
value given to this argument should include a frame placeholder so that it
can have the appropriate time code inserted. If the application has such an
argument, its name can be specified using frameFormatArgName. That arg will
be checked to ensure that it has a frame placeholder and it will be given
a value with that placeholder replaced with a Python format specifier so
that the value is ready to use with the str.format(frame=<timeCode>)
method. If a frame range is not provided as an argument, then it is an
error to include a frame placeholder in the frame format string.
"""
from pxr import Usd
framePlaceholder = None
frameFormat = None
if frameFormatArgName is not None:
frameFormat = getattr(args, frameFormatArgName)
framePlaceholder = GetFramePlaceholder(frameFormat)
frameFormat = ConvertFramePlaceholderToFloatSpec(frameFormat)
if args.frames:
args.frames = FrameSpecIterator(args.frames)
if frameFormatArgName is not None:
if not frameFormat:
argsParser.error('%s must contain exactly one frame number '
'placeholder of the form "###"" or "###.###". Note that '
'the number of hash marks is variable in each group.' %
frameFormatArgName)
placeholderPrecision = _GetFloatStringPrecision(framePlaceholder)
if placeholderPrecision < args.frames.minFloatPrecision:
argsParser.error('The given FrameSpecs require a minimum '
'floating point precision of %d, but the frame '
'placeholder in %s only specified a precision of %d (%s). '
'The precision of the frame placeholder must be equal to '
'or greater than %d.' % (args.frames.minFloatPrecision,
frameFormatArgName, placeholderPrecision,
framePlaceholder,args.frames.minFloatPrecision))
setattr(args, frameFormatArgName, frameFormat)
else:
if frameFormat:
argsParser.error('%s cannot contain a frame number placeholder '
'when not operating on a frame range.' % frameFormatArgName)
if args.defaultTime:
args.frames = [Usd.TimeCode.Default()]
else:
args.frames = [Usd.TimeCode.EarliestTime()]
return args
| 11,231 | Python | 40.6 | 80 | 0.685691 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/rendererArgs.py | #
# Copyright 2019 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.
#
def GetAllPluginArguments():
"""
Returns argument strings for all the renderer plugins available.
"""
from pxr import UsdImagingGL
return [ UsdImagingGL.Engine.GetRendererDisplayName(pluginId) for
pluginId in UsdImagingGL.Engine.GetRendererPlugins() ]
def GetPluginIdFromArgument(argumentString):
"""
Returns plugin id, if found, for the passed in argument string.
Valid argument strings are returned by GetAllPluginArguments().
"""
from pxr import UsdImagingGL
for p in UsdImagingGL.Engine.GetRendererPlugins():
if argumentString == UsdImagingGL.Engine.GetRendererDisplayName(p):
return p
return None
def AddCmdlineArgs(argsParser, altHelpText=''):
"""
Adds Hydra renderer-related command line arguments to argsParser.
The resulting 'rendererPlugin' argument will be a _RendererPlugin instance
representing one of the available Hydra renderer plugins.
"""
from pxr import UsdImagingGL
helpText = altHelpText
if not helpText:
helpText = (
'Hydra renderer plugin to use when generating images')
renderers = GetAllPluginArguments()
argsParser.add_argument('--renderer', '-r', action='store',
dest='rendererPlugin',
choices=renderers,
help=helpText)
| 2,386 | Python | 33.594202 | 78 | 0.726739 |
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/__DOC.py | def Execute(result):
result["FrameRecorder"].__doc__ = """
A utility class for recording images of USD stages.
UsdAppUtilsFrameRecorder uses Hydra to produce recorded images of a
USD stage looking through a particular UsdGeomCamera on that stage at
a particular UsdTimeCode. The images generated will be effectively the
same as what you would see in the viewer in usdview.
Note that it is assumed that an OpenGL context has already been setup.
"""
result["FrameRecorder"].__init__.func_doc = """__init__()
"""
result["FrameRecorder"].GetCurrentRendererId.func_doc = """GetCurrentRendererId() -> str
Gets the ID of the Hydra renderer plugin that will be used for
recording.
"""
result["FrameRecorder"].SetRendererPlugin.func_doc = """SetRendererPlugin(id) -> bool
Sets the Hydra renderer plugin to be used for recording.
Parameters
----------
id : str
"""
result["FrameRecorder"].SetImageWidth.func_doc = """SetImageWidth(imageWidth) -> None
Sets the width of the recorded image.
The height of the recorded image will be computed using this value and
the aspect ratio of the camera used for recording.
The default image width is 960 pixels.
Parameters
----------
imageWidth : int
"""
result["FrameRecorder"].SetComplexity.func_doc = """SetComplexity(complexity) -> None
Sets the level of refinement complexity.
The default complexity is"low"(1.0).
Parameters
----------
complexity : float
"""
result["FrameRecorder"].SetColorCorrectionMode.func_doc = """SetColorCorrectionMode(colorCorrectionMode) -> None
Sets the color correction mode to be used for recording.
By default, color correction is disabled.
Parameters
----------
colorCorrectionMode : str
"""
result["FrameRecorder"].SetIncludedPurposes.func_doc = """SetIncludedPurposes(purposes) -> None
Sets the UsdGeomImageable purposes to be used for rendering.
We will **always** include"default"purpose, and by default, we will
also include UsdGeomTokens->proxy. Use this method to explicitly
enumerate an alternate set of purposes to be included along
with"default".
Parameters
----------
purposes : list[TfToken]
"""
result["FrameRecorder"].Record.func_doc = """Record(stage, usdCamera, timeCode, outputImagePath) -> bool
Records an image and writes the result to ``outputImagePath`` .
The recorded image will represent the view from ``usdCamera`` looking
at the imageable prims on USD stage ``stage`` at time ``timeCode`` .
If ``usdCamera`` is not a valid camera, a camera will be computed to
automatically frame the stage geometry.
Returns true if the image was generated and written successfully, or
false otherwise.
Parameters
----------
stage : Stage
usdCamera : Camera
timeCode : TimeCode
outputImagePath : str
""" | 2,765 | Python | 19.954545 | 115 | 0.734177 |
omniverse-code/kit/exts/omni.usd.libs/omni/usd_libs/package.py | import functools
import os
import typing
import omni.kit.app
import omni.log
def _simple_yaml_load(file_path):
# avoid bringing in a new dependency on PyYaml to parse a simple yaml file
d = {}
with open(file_path, "r", encoding="utf-8") as f:
for line in f.readlines():
if ":" not in line:
continue
key, value = line.split(":", maxsplit=1)
value = value.strip()
if value.startswith("b'"):
value = value[2:-1]
d[key.strip()] = value
return d
def get_info_path() -> str:
app = omni.kit.app.get_app_interface()
manager = app.get_extension_manager()
# get the usd build information that is currently being built against
usd_libs_ext_id = manager.get_enabled_extension_id("omni.usd.libs")
usd_libs_path = manager.get_extension_path(usd_libs_ext_id)
return os.path.join(usd_libs_path, "PACKAGE-INFO.yaml")
@functools.lru_cache()
def get_info_data() -> typing.Optional[typing.Dict[str, object]]:
# get the current usd build information
package_info_path = get_info_path()
try:
yaml_data = _simple_yaml_load(package_info_path)
except FileNotFoundError:
omni.log.warn(f"{package_info_path} can not be found")
except Exception as err:
omni.log.warn(f"{package_info_path} can not be loaded: {err}")
else:
return yaml_data
return None
def get_name() -> str:
package_info_data = get_info_data()
return package_info_data.get("Package", "")
def get_version() -> str:
# get the current usd build information
package_info_data = get_info_data()
return package_info_data.get("Version", "")
| 1,707 | Python | 27 | 78 | 0.628588 |
omniverse-code/kit/exts/omni.usd.libs/omni/usd_libs/__init__.py | from .package import get_info_path, get_info_data, get_name, get_version | 72 | Python | 71.999928 | 72 | 0.777778 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/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 .service_discovery import ServiceDiscovery
g_singleton = None
# Search Service is register name, it actually service name is NGSearch in server side
# See the start up in omni.kit.search.service
REGISTERED_NAME_TO_SERVCIE = {
'Search Service': 'NGSearch',
}
class NucleusInfoExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
self._discovery = None
def on_startup(self, ext_id):
self._discovery = ServiceDiscovery()
# Save away this instance as singleton
global g_singleton
g_singleton = self
def on_shutdown(self):
if self._discovery:
self._discovery.destory()
global g_singleton
g_singleton = None
def is_service_available(self, service: str, nucleus_url: str):
if not self._discovery:
return False
if service in REGISTERED_NAME_TO_SERVCIE:
return self._discovery.is_service_supported_for_nucleus(nucleus_url, REGISTERED_NAME_TO_SERVCIE[service])
else:
return self._discovery.is_service_supported_for_nucleus(nucleus_url, service)
def get_nucleus_services(self, nucleus_url: str):
if not self._discovery:
return None
return self._discovery.get_nucleus_services(nucleus_url)
async def get_nucleus_services_async(self, nucleus_url: str):
if not self._discovery:
return None
return await self._discovery.get_nucleus_services_async(nucleus_url)
def get_instance():
return g_singleton | 1,989 | Python | 32.728813 | 117 | 0.689794 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import NucleusInfoExtension, get_instance
def get_nucleus_info() -> NucleusInfoExtension:
"""Returns :class:`NucleusInfoExtension` interface"""
return get_instance()
| 626 | Python | 38.187498 | 76 | 0.790735 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/service_discovery.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
import asyncio
import omni.client
from omni.kit.async_engine import run_coroutine
class ServiceDiscovery():
def __init__(self):
self._nucleus_services = {}
self._connection_status_sub = omni.client.register_connection_status_callback(self._server_status_changed)
def destory(self):
self._connection_status_sub = None
def _server_status_changed(self, url: str, status: omni.client.ConnectionStatus) -> None:
"""Collect signed in server's service information based upon server status changed."""
if status == omni.client.ConnectionStatus.CONNECTED:
# must run on main thread as this one does not have async loop...
run_coroutine(self.get_nucleus_services_async(url))
def _extract_server_from_url(self, 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
def is_service_supported_for_nucleus(self, nucleus_url: str, service_name: str):
if not nucleus_url:
return False
nucleus_url = self._extract_server_from_url(nucleus_url)
if nucleus_url in self._nucleus_services:
server_services =self._nucleus_services[nucleus_url]
for service in server_services:
if service.service_interface.name.startswith(service_name):
return True
return False
else:
self.get_nucleus_services(nucleus_url)
scheme=omni.client.break_url(nucleus_url).scheme
if scheme and scheme.startswith("omniverse"):
return True
return False
def get_nucleus_services(self, nucleus_url: str):
if not nucleus_url:
return None
nucleus_url = self._extract_server_from_url(nucleus_url)
if nucleus_url in self._nucleus_services:
return self._nucleus_services[nucleus_url]
asyncio.ensure_future(self.get_nucleus_services_async(nucleus_url))
return None
async def get_nucleus_services_async(self, nucleus_url: str):
try:
from idl.connection.transport.ws import WebSocketClient
from omni.discovery.client import DiscoverySearch
if not nucleus_url:
return None
nucleus_url = self._extract_server_from_url(nucleus_url)
if nucleus_url in self._nucleus_services:
return self._nucleus_services[nucleus_url]
nucleus_services = []
client_url = omni.client.break_url(nucleus_url)
transport = WebSocketClient(uri=f"ws://{client_url.host}:3333")
discovery = DiscoverySearch(transport)
async with discovery:
async for service in discovery.find_all():
nucleus_services.append(service)
self._nucleus_services[nucleus_url] = nucleus_services
return self._nucleus_services[nucleus_url]
except:
return None
| 3,512 | Python | 40.821428 | 114 | 0.654613 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.