file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
ft-lab/omniverse_sample_scripts/Geometry/SetMeshPrimvars.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Mesh":
continue
m = UsdGeom.Mesh(prim)
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
# Set primvar(float).
primvarV = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("dat1", Sdf.ValueTypeNames.Float)
attr = primvarV.GetAttr()
attr.Set((2.2))
if UsdGeom.primvarV(prim).HasPrimvar("dat1"): # Check primvar.
# Remove primvar.
UsdGeom.primvarV(prim).RemovePrimvar("dat1")
# Set primvar (float2).
# If there is already a primvar with the same name but a different type,
# it must be removed using RemoveProperty.
primvarV = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("dat1", Sdf.ValueTypeNames.Float2)
attr = primvarV.GetAttr()
attr.Set((1.0, 2.0))
# Set primvar (color).
primvarV = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("dat2", Sdf.ValueTypeNames.Color3f)
attr = primvarV.GetAttr()
attr.Set((1.0, 0.5, 0.2))
# Set primvar (float3 array)
primvarV = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("dat3", Sdf.ValueTypeNames.Float3Array)
attr = primvarV.GetAttr()
attr.Set([(0.1, 0.2, 0.5), (0.4, 0.05, 0.0), (0.1, 0.4, 0.05)])
|
ft-lab/omniverse_sample_scripts/Geometry/GetMeshPrimvars.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Mesh":
continue
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarsAPI = UsdGeom.PrimvarsAPI(prim)
primvars = primvarsAPI.GetPrimvars()
if len(primvars) > 0:
print("[" + prim.GetPath().pathString + "]")
for primvar in primvars:
primName = primvar.GetPrimvarName()
typeName = primvar.GetTypeName()
val = primvar.Get()
print(" " + primName + " (" + str(typeName) + ") : " + str(val))
|
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/CreateSimpleMesh.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
# Get root path.
rootPath = '/'
if defaultPrim.IsValid():
rootPath = defaultPrim.GetPath().pathString
# Create mesh.
meshGeom = UsdGeom.Mesh.Define(stage, rootPath + "/mesh")
# Set vertices.
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
# Set normals.
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.SetNormalsInterpolation("vertex")
# Set face vertex count.
meshGeom.CreateFaceVertexCountsAttr([4])
# Set face vertex indices.
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
# Set uvs.
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarV = UsdGeom.PrimvarsAPI(meshGeom).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
attr = primvarV.GetAttr()
attr.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
# Compute extent.
boundable = UsdGeom.Boundable(meshGeom.GetPrim())
extent = boundable.ComputeExtent(Usd.TimeCode(0))
# Set Extent.
meshGeom.CreateExtentAttr(extent)
# Subdivision is set to none.
meshGeom.CreateSubdivisionSchemeAttr().Set("none")
# Set position.
UsdGeom.XformCommonAPI(meshGeom).SetTranslate((0.0, 0.0, 0.0))
# Set rotation.
UsdGeom.XformCommonAPI(meshGeom).SetRotate((0.0, 0.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(meshGeom).SetScale((1.0, 1.0, 1.0))
|
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/CreateSimpleMeshWithSubset.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
# Get root path.
rootPath = '/'
if defaultPrim.IsValid():
rootPath = defaultPrim.GetPath().pathString
# --------------------------------------.
# Create new Material (OmniPBR).
# @param[in] materialPrimPath Prim path of Material
# @param[in] diffuseColor Diffuse color.
# --------------------------------------.
def createMaterialOmniPBR (materialPrimPath : str, diffuseColor : Gf.Vec3f):
material = UsdShade.Material.Define(stage, materialPrimPath)
shaderPath = materialPrimPath + '/Shader'
shader = UsdShade.Shader.Define(stage, shaderPath)
shader.SetSourceAsset('OmniPBR.mdl', 'mdl')
shader.GetPrim().CreateAttribute('info:mdl:sourceAsset:subIdentifier', Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set('OmniPBR')
# Set Diffuse color.
shader.CreateInput('diffuse_color_constant', Sdf.ValueTypeNames.Color3f).Set(diffuseColor)
# Connecting Material to Shader.
mdlOutput = material.CreateSurfaceOutput('mdl')
mdlOutput.ConnectToSource(shader.ConnectableAPI(), 'out')
return materialPrimPath
# --------------------------------------.
# Create mesh with subset.
# --------------------------------------.
def createMesh (meshPath : str):
# Create mesh.
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
# Set vertices.
meshGeom.CreatePointsAttr([(-10, 0, -10), (0, 0, -10), (10, 0, -10), (-10, 0, 0), (0, 0, 0), (10, 0, 0)])
# Set face vertex count.
meshGeom.CreateFaceVertexCountsAttr([4, 4])
# Set face vertex indices.
meshGeom.CreateFaceVertexIndicesAttr([0, 3, 4, 1, 1, 4, 5, 2])
# Set normals and UVs for each face vertex.
# Set normals.
normalList = []
for i in range(2):
normalList.extend([(0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0)])
meshGeom.CreateNormalsAttr(normalList)
meshGeom.SetNormalsInterpolation("faceVarying")
# Set uvs.
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarV = UsdGeom.PrimvarsAPI(meshGeom).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
attr = primvarV.GetAttr()
uvsList = []
uvsList.extend([(0.0, 1.0), (0.0, 0.0), (1.0, 0.0), (1.0, 1.0)])
uvsList.extend([(1.0, 1.0), (1.0, 0.0), (2.0, 0.0), (2.0, 1.0)])
attr.Set(uvsList)
# Subdivision is set to none.
meshGeom.CreateSubdivisionSchemeAttr().Set("none")
# Set position.
UsdGeom.XformCommonAPI(meshGeom).SetTranslate((0.0, 0.0, 0.0))
# Set rotation.
UsdGeom.XformCommonAPI(meshGeom).SetRotate((0.0, 0.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(meshGeom).SetScale((1.0, 1.0, 1.0))
# Create subset 1.
subsetPath = meshPath + "/submesh_1"
geomSubset1 = UsdGeom.Subset.Define(stage, subsetPath)
geomSubset1.CreateFamilyNameAttr("materialBind")
geomSubset1.CreateElementTypeAttr("face")
geomSubset1.CreateIndicesAttr([0]) # Set the index on the face.
# Bind material.
matPrim = stage.GetPrimAtPath(rootPath + "/Looks/mat1")
if matPrim.IsValid():
UsdShade.MaterialBindingAPI(geomSubset1).Bind(UsdShade.Material(matPrim))
# Create subset 2.
subsetPath = meshPath + "/submesh_2"
geomSubset2 = UsdGeom.Subset.Define(stage, subsetPath)
geomSubset2.CreateFamilyNameAttr("materialBind")
geomSubset2.CreateElementTypeAttr("face")
geomSubset2.CreateIndicesAttr([1]) # Set the index on the face.
# Bind material.
matPrim = stage.GetPrimAtPath(rootPath + "/Looks/mat2")
if matPrim.IsValid():
UsdShade.MaterialBindingAPI(geomSubset2).Bind(UsdShade.Material(matPrim))
# -----------------------------------------------------------.
# Create scope.
looksScopePath = rootPath + "/Looks"
scopePrim = stage.GetPrimAtPath(looksScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, looksScopePath)
# Create material.
createMaterialOmniPBR(rootPath + "/Looks/mat1", Gf.Vec3f(1.0, 0.0, 0.0))
createMaterialOmniPBR(rootPath + "/Looks/mat2", Gf.Vec3f(0.0, 1.0, 0.0))
# Create mesh.
createMesh(rootPath + "/mesh") |
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/GetMeshInfo.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# ---------------------------------------.
# Dump mesh data.
# ---------------------------------------.
def DumpMeshData (prim):
typeName = prim.GetTypeName()
if typeName == 'Mesh':
m = UsdGeom.Mesh(prim)
# Get prim name.
name = prim.GetName()
# Get prim path.
path = prim.GetPath().pathString
# Get show/hide.
showF = (m.ComputeVisibility() == 'inherited')
# Get the number of faces of Mesh.
facesCou = len(m.GetFaceVertexCountsAttr().Get())
# Get number of normals.
normalsCou = len(m.GetNormalsAttr().Get())
# Total number of vertices.
versCou = len(m.GetPointsAttr().Get())
# Get UV.
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarsAPI = UsdGeom.PrimvarsAPI(prim)
primvars = primvarsAPI.GetPrimvars()
uvsCou = 0
uvlayersCou = 0
for primvar in primvars:
typeName = str(primvar.GetTypeName().arrayType)
if typeName == 'float2[]' or typeName == 'texCoord2f[]':
# 'st'
pName = primvar.GetPrimvarName()
uvlayersCou += 1
uvsCou = len(primvar.Get())
# Get Material.
rel = UsdShade.MaterialBindingAPI(prim).GetDirectBindingRel()
pathList = rel.GetTargets()
print(f"[ {name} ] {path}")
print(f"Show : {showF}")
print(f"Points : {versCou}")
print(f"Faces : {facesCou}")
print(f"uvs : {uvsCou}")
print(f"normals : {normalsCou}")
print(f"UV sets : {uvlayersCou}")
if len(pathList) > 0:
print("Material : ")
for mPath in pathList:
print(f" {mPath.pathString}")
print("")
# ---------------------------------------.
# Traverse the hierarchy.
# ---------------------------------------.
def TraverseHierarchy (prim):
DumpMeshData(prim)
# Recursively traverse the hierarchy.
pChildren = prim.GetChildren()
for cPrim in pChildren:
TraverseHierarchy(cPrim)
# ----------------------------------------------------.
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
TraverseHierarchy(prim)
|
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/CreateGear.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import math
import omni.ui
# Get stage.
stage = omni.usd.get_context().get_stage()
# -------------------------------------------------------.
# Calculate normal.
# -------------------------------------------------------.
def calcTriangleNormal (v1 : Gf.Vec3d, v2 : Gf.Vec3d, v3 : Gf.Vec3d):
e1 = v2 - v1
e2 = v3 - v2
e1 = Gf.Vec4f(e1[0], e1[1], e1[2],1.0)
e2 = Gf.Vec4f(e2[0], e2[1], e2[2],1.0)
e3 = Gf.HomogeneousCross(e1, e2)
n = Gf.Vec3d(e3[0], e3[1], e3[2])
return n.GetNormalized()
# -------------------------------------------------------.
# Attach thickness.
# @param[in] primPath Target Prim path.
# @param[in] thickness Thickness.
# -------------------------------------------------------.
def AttachThickness (primPath : str, thickness : float):
prim = stage.GetPrimAtPath(primPath)
if prim.IsValid() == False:
return
if prim.GetTypeName() != 'Mesh':
return
m = UsdGeom.Mesh(prim)
# Number of faces.
faceVCouList = m.GetFaceVertexCountsAttr().Get()
faceCou = len(faceVCouList)
if faceCou == 0:
return
normalsList = m.GetNormalsAttr().Get()
normalsCou = len(normalsList)
if normalsCou == 0:
return
normalV = normalsList[0]
versList = m.GetPointsAttr().Get()
versCou = len(versList)
if versCou < 3:
return
faceVIList = m.GetFaceVertexIndicesAttr().Get()
faceVICou = len(faceVIList)
# Stores the face number for each vertex.
vFList = [[]] * (versCou)
for i in range(versCou):
vFList[i] = []
index = 0
for i in range(len(faceVCouList)):
faceVCou = faceVCouList[i]
for j in range(faceVCou):
vI = faceVIList[index + j]
vFList[vI].append(i)
index += faceVCou
faceIndicesList = [[]] * faceCou
for i in range(faceCou):
faceIndicesList[i] = []
# Rearrange the vertex indices per face.
index = 0
for i in range(faceCou):
faceVCou = faceVCouList[i]
for j in range(faceVCou):
faceIndicesList[i].append(faceVIList[index + j])
index += faceVCou
# Create a list of independent edges.
edgesList = []
for i in range(faceCou):
faceVCou = faceVCouList[i]
for j in range(faceVCou):
vI1 = faceIndicesList[i][j]
vI2 = faceIndicesList[i][(j + 1) % faceVCou]
chkF = False
cI = -1
for k in range(len(edgesList)):
if (edgesList[k][0] == vI1 and edgesList[k][1] == vI2) or (edgesList[k][0] == vI2 and edgesList[k][1] == vI1):
chkF = True
cI = k
break
if chkF == False:
edgesList.append([vI1, vI2, 1])
else:
cou = edgesList[cI][2]
edgesList[cI] = [vI1, vI2, cou + 1]
edgesOneList = []
for p in edgesList:
if p[2] == 1:
edgesOneList.append([p[0], p[1]])
# Create a symmetrical face.
faceVCouList2 = [0] * (faceCou * 2)
normalsList2 = [(0.0, 0.0, 0.0)] * (normalsCou * 2)
versList2 = [(0.0, 0.0, 0.0)] * (versCou * 2)
faceVIList2 = [0] * (faceVICou * 2)
for i in range(faceCou):
faceVCouList2[i] = faceVCouList[i]
faceVCouList2[i + faceCou] = faceVCouList[i]
for i in range(faceVICou):
faceVIList2[i] = faceVIList[i]
faceVIList2[i + faceVICou] = faceVIList[faceVICou - i - 1] + versCou
for i in range(normalsCou):
normalsList2[i] = normalsList[i]
normalsList2[i + normalsCou] = -normalsList[i]
for i in range(versCou):
versList2[i] = versList[i]
n = normalsList[i]
versList2[i + versCou] = versList[i] - (n * thickness)
# Create side faces.
vIndex = len(versList2)
for edgeI in edgesOneList:
e1 = edgeI[0]
e2 = edgeI[1]
i1 = e1
i2 = e2
i3 = e1 + versCou
i4 = e2 + versCou
v1 = versList2[i2]
v2 = versList2[i1]
v3 = versList2[i3]
v4 = versList2[i4]
n = calcTriangleNormal(v1, v2, v3)
faceVCouList2.append(4)
for j in range(4):
normalsList2.append(n)
versList2.append(v1)
versList2.append(v2)
versList2.append(v3)
versList2.append(v4)
for j in range(4):
faceVIList2.append(vIndex + j)
vIndex += 4
m.CreatePointsAttr(versList2)
m.CreateNormalsAttr(normalsList2)
m.CreateFaceVertexCountsAttr(faceVCouList2)
m.CreateFaceVertexIndicesAttr(faceVIList2)
# -------------------------------------------------------.
# Create gear.
# @param[in] name Prim name.
# @param[in] gearR Radius of gear.
# @param[in] filletCount Number of gear divisions.
# @param[in] filletHeight Fillet height.
# @param[in] gearWidth Gear width.
# -------------------------------------------------------.
def CreateGear (name : str, gearR : float, filletCount : int, filletHeight : float, gearWidth : float):
angle = 360.0 / filletCount # Angle of one tooth.
# Calculate the length of one tooth on the circumference.
D = (gearR * math.sin((angle / 2.0) * math.pi / 180.0)) * 2
dHalf = D * 0.5
dQuarter = D * 0.25
centerV = Gf.Vec3d(0, 0, 0)
versList = []
versList.append(centerV)
faceIndexList = []
maxVCou = 1 + (5 * filletCount)
index = 1
aV = 0.0
for i in range(filletCount):
# Vertices of a single tooth.
vDirX = math.cos(aV * math.pi / 180.0)
vDirY = math.sin(aV * math.pi / 180.0)
v2X = -vDirY
v2Y = vDirX
vD = Gf.Vec3d(vDirX, vDirY, 0)
vCrossD = Gf.Vec3d(v2X, v2Y, 0)
vCenter = vD * gearR
v1 = vCenter - (vCrossD * dHalf)
v2 = v1 + (vCrossD * dQuarter)
v3 = v2 + (vD * filletHeight)
v4 = v3 + (vCrossD * dHalf)
v5 = v4 - (vD * filletHeight)
v6 = v5 + (vCrossD * dQuarter)
dd = D * 0.1
vCD = vCrossD * dd
v3 += vCD
v4 -= vCD
v2 -= vCD
v5 += vCD
versList.append(v1)
versList.append(v2)
versList.append(v3)
versList.append(v4)
versList.append(v5)
faceIndexList.append(0)
faceIndexList.append(index)
faceIndexList.append(index + 1)
faceIndexList.append(index + 2)
faceIndexList.append(index + 3)
faceIndexList.append(index + 4)
if index + 5 >= maxVCou:
faceIndexList.append(1)
else:
faceIndexList.append(index + 5)
index += 5
aV += angle
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
# Get root path.
rootPath = '/'
if defaultPrim.IsValid():
rootPath = defaultPrim.GetPath().pathString
# Create mesh.
pathName = rootPath + '/gears'
prim = stage.GetPrimAtPath(pathName)
if prim.IsValid() == False:
UsdGeom.Xform.Define(stage, pathName)
pathMeshName0 = pathName + '/' + name
pathMeshName = pathMeshName0
index = 0
while True:
pathMeshName = pathMeshName0
if index > 0:
pathMeshName += '_' + str(index)
prim = stage.GetPrimAtPath(pathMeshName)
if prim.IsValid() == False:
break
index += 1
meshGeom = UsdGeom.Mesh.Define(stage, pathMeshName)
# Set vertices.
stVersList = []
stNormalList = []
for i in range(len(versList)):
stVersList.append((versList[i][0], versList[i][1], versList[i][2]))
stNormalList.append((0, 0, 1))
meshGeom.CreatePointsAttr(stVersList)
# Set normals.
meshGeom.CreateNormalsAttr(stNormalList)
# Set face vertex count.
faceVCouList = []
for i in range(filletCount):
faceVCouList.append(7)
meshGeom.CreateFaceVertexCountsAttr(faceVCouList)
# Set face vertex indices.
meshGeom.CreateFaceVertexIndicesAttr(faceIndexList)
# Set position.
UsdGeom.XformCommonAPI(meshGeom).SetTranslate((0.0, 0.0, 0.0))
# Set rotation.
UsdGeom.XformCommonAPI(meshGeom).SetRotate((0.0, 0.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(meshGeom).SetScale((1.0, 1.0, 1.0))
# Attach thickness.
if gearWidth > 0.0:
AttachThickness(pathMeshName, gearWidth)
# --------------------------------------------------------.
# Main UI.
# --------------------------------------------------------.
# Clicked button event.
def onButtonClick (hNameStringField, hRadiusFloatField, hFilletCouIntField, hFilletHeightFloatField, hGearWidthFloatField):
name = hNameStringField.model.get_value_as_string()
if name == '':
name = 'gear'
radius = hRadiusFloatField.model.get_value_as_float()
if radius < 0.00001:
radius = 0.00001
filletCou = hFilletCouIntField.model.get_value_as_int()
if filletCou < 4:
filletCou = 4
filletHeight = hFilletHeightFloatField.model.get_value_as_float()
if filletHeight < 0.00001:
filletHeight = 0.00001
gearWidth = hGearWidthFloatField.model.get_value_as_float()
if gearWidth < 0.00001:
gearWidth = 0.00001
# Create Cear.
CreateGear(name, radius, filletCou, filletHeight, gearWidth)
# ------------------------------------------.
my_window = omni.ui.Window("Create Gear", width=350, height=250)
with my_window.frame:
with omni.ui.VStack(height=0):
labelWidth = 120
with omni.ui.Placer(offset_x=8, offset_y=8):
# Set label.
f = omni.ui.Label("Create Gear.")
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Name : ", width=labelWidth)
hNameStringField = omni.ui.StringField(width=200, height=0)
hNameStringField.model.set_value("gear")
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Radius : ", width=labelWidth)
hRadiusFloatField = omni.ui.FloatField(width=200, height=0)
hRadiusFloatField.model.set_value(10.0)
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Number of fillet : ", width=labelWidth)
hFilletCouIntField = omni.ui.IntField(width=200, height=0)
hFilletCouIntField.model.set_value(32)
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Fillet height : ", width=labelWidth)
hFilletHeightFloatField = omni.ui.FloatField(width=200, height=0)
hFilletHeightFloatField.model.set_value(1.0)
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Gear width : ", width=labelWidth)
hGearWidthFloatField = omni.ui.FloatField(width=200, height=0)
hGearWidthFloatField.model.set_value(2.0)
with omni.ui.Placer(offset_x=8, offset_y=4):
# Set button.
btn = omni.ui.Button("Create", width=200, height=0)
btn.set_clicked_fn(lambda name = hNameStringField, f = hRadiusFloatField, f2 = hFilletCouIntField, f3 = hFilletHeightFloatField, f4 = hGearWidthFloatField: onButtonClick(name, f, f2, f3, f4))
|
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/readme.md | # CreateMesh
Meshを生成/Mesh情報を取得します。
|ファイル|説明|
|---|---|
|[CreateSimpleMesh.py](./CreateSimpleMesh.py)|簡単な1枚板のMeshを作成<br>|
|[CreateMeshInterpolation.py](./CreateMeshInterpolation.py)|2つの四角形で構成されるMeshを作成。<br>「頂点ごと(vertex)」「面の頂点ごと(faceVarying)」の法線/UVの指定。|
|[CreateSimpleMeshWithSubset.py](./CreateSimpleMeshWithSubset.py)|2つの面を持つMeshにて、面のマテリアルを別々に指定。|
|[CreateGear.py](./CreateGear.py)|歯車のMeshを作成<br>|
|[GetMeshInfo.py](./GetMeshInfo.py)|選択形状がMeshの場合のMesh情報を取得|
|
ft-lab/omniverse_sample_scripts/Geometry/CreateMesh/CreateMeshInterpolation.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
# Get root path.
rootPath = '/'
if defaultPrim.IsValid():
rootPath = defaultPrim.GetPath().pathString
# ------------------------------------------------.
# Create mesh.
# @param[in] path Prim path.
# @param[in] interpolation "vertex" or "faceVarying".
# ------------------------------------------------.
def createTestMesh (path : str, interpolation : str = "vertex", pos : Gf.Vec3f = Gf.Vec3f(0, 0, 0)):
if interpolation != "vertex" and interpolation != "faceVarying":
return
# Create mesh.
meshGeom = UsdGeom.Mesh.Define(stage, path)
# Set vertices.
meshGeom.CreatePointsAttr([(-10, 0, -10), (0, 0, -10), (10, 0, -10), (-10, 0, 0), (0, 0, 0), (10, 0, 0)])
# Set face vertex count.
meshGeom.CreateFaceVertexCountsAttr([4, 4])
# Set face vertex indices.
meshGeom.CreateFaceVertexIndicesAttr([0, 3, 4, 1, 1, 4, 5, 2])
if interpolation == "vertex":
# Set normals and UVs for each vertex.
# Set normals.
meshGeom.CreateNormalsAttr([(0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0)])
meshGeom.SetNormalsInterpolation("vertex")
# Set uvs.
# USD 22.11 : The specification has been changed to use UsdGeom.PrimvarsAPI.
primvarV = UsdGeom.PrimvarsAPI(meshGeom).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
attr = primvarV.GetAttr()
attr.Set([(0.0, 1.0), (1.0, 1.0), (2.0, 1.0), (0.0, 0.0), (1.0, 0.0), (2.0, 0.0)])
else:
# Set normals and UVs for each face vertex.
# Set normals.
normalList = []
for i in range(2):
normalList.extend([(0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0)])
meshGeom.CreateNormalsAttr(normalList)
meshGeom.SetNormalsInterpolation("faceVarying")
# Set uvs.
primvarV = UsdGeom.PrimvarsAPI(meshGeom).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
attr = primvarV.GetAttr()
uvsList = []
uvsList.extend([(0.0, 1.0), (0.0, 0.0), (1.0, 0.0), (1.0, 1.0)])
uvsList.extend([(1.0, 1.0), (1.0, 0.0), (2.0, 0.0), (2.0, 1.0)])
attr.Set(uvsList)
# Subdivision is set to none.
meshGeom.CreateSubdivisionSchemeAttr().Set("none")
# Set position.
UsdGeom.XformCommonAPI(meshGeom).SetTranslate((pos[0], pos[1], pos[2]))
# Set rotation.
UsdGeom.XformCommonAPI(meshGeom).SetRotate((0.0, 0.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(meshGeom).SetScale((1.0, 1.0, 1.0))
# -----------------------------------------------.
createTestMesh(rootPath + "/mesh_vertex", "vertex", Gf.Vec3f(0, 0, 0))
createTestMesh(rootPath + "/mesh_faceVarying", "faceVarying", Gf.Vec3f(0, 0, 20))
|
ft-lab/omniverse_sample_scripts/Geometry/CreateCube/CreateCube.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create cube.
pathName = '/World/cube'
cubeGeom = UsdGeom.Cube.Define(stage, pathName)
# Set cube size.
cubeGeom.CreateSizeAttr(10.0)
# Set color.
cubeGeom.CreateDisplayColorAttr([(0.0, 1.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(cubeGeom).SetTranslate((0.0, 5.0, 0.0))
# Set scale.
UsdGeom.XformCommonAPI(cubeGeom).SetScale((2.0, 1.0, 2.0))
|
ft-lab/omniverse_sample_scripts/Geometry/CreateCube/readme.md | # CreateCube
|ファイル|説明|
|---|---|
|[CreateCube.py](./CreateCube.py)|直方体を作成<br>|
|
ft-lab/omniverse_sample_scripts/Geometry/CreateSphere/GetSphereInfo.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf
xformCache = UsdGeom.XformCache(0)
# ---------------------------------------.
# Dump sphere data.
# ---------------------------------------.
def DumpSphereData (prim):
typeName = prim.GetTypeName()
if typeName == 'Sphere':
sphereGeom = UsdGeom.Sphere(prim)
# Get prim name.
name = prim.GetName()
# Get prim path.
path = prim.GetPath().pathString
# Get show/hide.
showF = (sphereGeom.ComputeVisibility() == 'inherited')
# Decompose transform.
globalPose = xformCache.GetLocalToWorldTransform(prim)
translate, rotation, scale = UsdSkel.DecomposeTransform(globalPose)
# Get radius.
r = sphereGeom.GetRadiusAttr().Get()
# Get Material.
rel = UsdShade.MaterialBindingAPI(prim).GetDirectBindingRel()
pathList = rel.GetTargets()
print(f"[ {name} ] {path}")
print(f"Show : {showF}")
print(f"Radius : {r * scale[0]} , {r * scale[1]} , {r * scale[2]}")
if len(pathList) > 0:
print("Material : ")
for mPath in pathList:
print(f" {mPath.pathString}")
print("")
# ---------------------------------------.
# Traverse the hierarchy.
# ---------------------------------------.
def TraverseHierarchy (prim):
DumpSphereData(prim)
# Recursively traverse the hierarchy.
pChildren = prim.GetChildren()
for cPrim in pChildren:
TraverseHierarchy(cPrim)
# ----------------------------------------------------.
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
TraverseHierarchy(prim)
|
ft-lab/omniverse_sample_scripts/Geometry/CreateSphere/CReateSphereWithRefinement.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
pathName = '/World/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, pathName)
# Set radius.
sphereGeom.CreateRadiusAttr(5.0)
# Set color.
sphereGeom.CreateDisplayColorAttr([(1.0, 0.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(sphereGeom).SetTranslate((0.0, 5.0, 0.0))
# Set refinement.
objPrim = stage.GetPrimAtPath(pathName)
objPrim.CreateAttribute('refinementEnableOverride', Sdf.ValueTypeNames.Bool).Set(True)
objPrim.CreateAttribute('refinementLevel', Sdf.ValueTypeNames.Int).Set(2)
|
ft-lab/omniverse_sample_scripts/Geometry/CreateSphere/readme.md | # CreateSphere
球を作成します。
|ファイル|説明|
|---|---|
|[CreateSphere.py](./CreateSphere.py)|簡単な球を作成<br>|
|[CreateSphereWithRefinement.py](./CReateSphereWithRefinement.py)|作成する球の分割数を増やす。<br>属性"Refinement"を指定。<br>|
|[GetSphereInfo.py](./GetSphereInfo.py)|球の情報を取得|
|
ft-lab/omniverse_sample_scripts/Geometry/CreateSphere/CreateSphere.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
pathName = '/World/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, pathName)
# Set radius.
sphereGeom.CreateRadiusAttr(5.0)
# Set color.
sphereGeom.CreateDisplayColorAttr([(1.0, 0.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(sphereGeom).SetTranslate((0.0, 5.0, 0.0))
|
ft-lab/omniverse_sample_scripts/Extensions/readme.md | # Extension
簡単なサンプルのExtensionです。
Extensionはモジュール的にOmniverse(Kit)を使ったアプリを拡張します。
ExtensionはベースはPythonとして記載し、別途C言語(動的ライブラリとして関数呼び出し)で外部機能を実装することができます。
## Extensionの詳しいドキュメント
Extensionは構成のルールがあります。
Omniverse Createの[Help]-[Developers Manual]からOmniverse Kitのドキュメントの「Extensions」で詳しく解説されています。
## Extension作成に関する情報
* [extension.tomlでの記述内容](./knowledge/config_info.md)
## サンプル
|Extension|説明|
|---|---|
|[ft_lab.sample.hello](./ft_lab.sample.hello)|開始(startup)/破棄(shutdown)のみの簡単なExtension|
|[ft_lab.sample.callDLL](./ft_lab.sample.callDLL)|C言語のDLLより関数を読み込む|
|[ft_lab.sample.menu](./ft_lab.sample.menu)|メニューを追加。<br>|
|[ft_lab.sample.loadStage](./ft_lab.sample.loadStage)|Extension内に配置したusdファイルを新規Stageとして読み込む|
|[ft_lab.sample.widgets](./ft_lab.sample.widgets)|omni.uiの使用例。<br>ウィンドウを表示し、ウィジットを配置。<br>|
|[ft_lab.sample.widgets_progressBar](./ft_lab.sample.widgets_progressBar)|omni.ui.ProgressBarの使用例。<br>ボタンを押すとプログレスバーの開始/停止。<br>|
|[ft_lab.sample.uiScene](./ft_lab.sample.uiScene)|omni.ui.sceneの使用例。<br>ウィンドウを表示し、SceneViewに描画を行う。<br>|
|[ft_lab.sample.uiSceneDraw](./ft_lab.sample.uiSceneDraw)|omni.ui.sceneの使用例。<br>ウィンドウを表示し、SceneViewに順番を考慮した描画を行う。<br>また、描画を更新し、SceneViewでアニメーションする。<br>|
|[ft_lab.sample.uiSceneViewportOverlay](./ft_lab.sample.uiSceneViewportOverlay)|Kit.104以上で動作。<br>omni.ui.sceneの使用例。<br>ViewportにSceneViewをオーバレイ表示する。<br>カメラと同じ変換行列を使用し、3Dのワールド座標指定でワイヤーフレーム描画します。<br>「[Viewport](../UI/Viewport/readme.md)」もご参照くださいませ。|
|[ft_lab.sample.uiSceneShowPrimName](./ft_lab.sample.uiSceneShowPrimName)|Kit.104以上で動作。<br>omni.ui.sceneの使用例。<br>ViewportにSceneViewをオーバレイ表示する。<br>選択Prim名を形状のローカル座標の中心に表示。<br>NDC座標でラベルの描画を行います。<br>「[Viewport](../UI/Viewport/readme.md)」もご参照くださいませ。|
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/readme.md | # ft_lab.sample.hello
"ft_lab.sample.hello" はExtensionの簡単なサンプルです。
"omni.example.hello"を参考にしました。
## Extensionの構成
"ft_lab.sample.hello" Extensionの構成です。
```
[ft_lab.sample.hello]
[config]
extension.toml
[data]
icon.png ... Icon file (256 x 256 pixel).
preview.png
[docs]
CHANGELOG.md
index.rst
README.md
[ft_lab]
[sample]
[hello]
__init__.py
hello.py
```
## data/icon.png
アイコンファイル(256 x 256 pixel)。
"config/extension.toml"から参照されます。
## data/preview.png
ExtensionウィンドウのOVERVIEWで表示される画像です。
"config/extension.toml"から参照されます。
## docs
ドキュメント。
|ファイル名|説明|
|---|---|
|index.rst|ドキュメントの構造を記載したファイル。|
|README.md|OVERVIEWに表示される内容。|
|CHANGELOG.md|CHANGELOGに表示される内容。|
### index.rst
```
ft_lab.sample.hello
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
```
## config/extension.toml
"extension.toml"はExtentionの設定を記載します。
```
[package]
# Version.
version = "0.0.1"
# Authors.
authors = ["ft-lab"]
# The title and description.
title = "Python Extension Example"
description="xxxxxx."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# ChangeLog.
changelog="docs/CHANGELOG.md"
# Preview image.
preview_image = "data/preview.png"
# Icon image (256x256).
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.hello"
```
## ft_lab.sample.hello
"ft_lab.sample.hello"内は、"ft_lab/sample/hello"の階層でフォルダを構成します。
```
[ft_lab]
[sample]
[hello]
__init__.py
hello.py
```
### __init__.py
開始するメインファイル (hello.py)のインポートを指定します.
```
from .hello import *
```
### hello.py
Extensionの開始時と終了時に呼び出すメソッドを指定します。
```python
import omni.ext
class HelloExtension(omni.ext.IExt):
# Call startup.
def on_startup(self, ext_id):
print("[ft_lab.sample.hello] HelloExtension startup")
# Call shutdown.
def on_shutdown(self):
print("[ft_lab.sample.hello] HelloExtension shutdown")
```
このときのクラス名"HelloExtension"はどのような名前でも認識されるようでした。
"on_startup"でExtensionを開始したときの処理を記載します。
"on_shutdown"でExtensionを終了したときの処理を記載します。
## Omniverse CreateにExtensionを入れる
Omniverse Createが"pkg/create-2021.3.8"にインストールされているとします。
このとき、開発者が作成したExtensionを"pkg/create-2021.3.8/exts"に入れます。
なお、"pkg/create-2021.3.8/kit/exts"はOmniverse KitとしてのExtension、
"pkg/create-2021.3.8/kit/extscore"はコアExtensionとなり、
これらはOmniverseの内部的に使用されるExtensionのため、ここには独自Extensionは入れないほうがよさそうです。
作成した"ft_lab.sample.hello"をフォルダごと"pkg/create-2021.3.8/exts"に格納します。
Omniverse Createを起動したままでもExtensionを所定のフォルダに入れると、自動的にExtensionが認識されます。
メインメニューの"Window"-"Extensions" を選択し、Extensionsウィンドウを表示します。
Extensionのリストで"Python Extension Example"が存在するのを確認できました。

|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Python Extension Example"
description="Very simple extension."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.hello"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/ft_lab/sample/hello/hello.py | 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 HelloExtension(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):
print("[ft_lab.sample.hello] HelloExtension startup")
def on_shutdown(self):
print("[ft_lab.sample.hello] HelloExtension shutdown")
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/ft_lab/sample/hello/__init__.py | from .hello import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.hello`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/docs/README.md | # Python Extension Example [ft_lab.sample.hello]
sample extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.hello/docs/index.rst | ft_lab.sample.hello
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/readme.md | # ft_lab.sample.loadStage
"ft_lab.sample.loadStage" は、あらかじめ用意したusdファイルを開くだけのExtensionです。
## Extensionの構成
"ft_lab.sample.loadStage" Extensionの構成です。
```
[ft_lab.sample.loadStage]
[config]
extension.toml
[data]
icon.png ... Icon file (256 x 256 pixel).
preview.png
[docs]
CHANGELOG.md
index.rst
README.md
[ft_lab]
[sample]
[loadStage]
__init__.py
main.py
```
## data/icon.png
アイコンファイル(256 x 256 pixel)。
"config/extension.toml"から参照されます。
## data/preview.png
ExtensionウィンドウのOVERVIEWで表示される画像です。
"config/extension.toml"から参照されます。
## docs
ドキュメント。
|ファイル名|説明|
|---|---|
|index.rst|ドキュメントの構造を記載したファイル。|
|README.md|OVERVIEWに表示される内容。|
|CHANGELOG.md|CHANGELOGに表示される内容。|
### index.rst
```
ft_lab.sample.loadStage
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
```
## config/extension.toml
"extension.toml"はExtentionの設定を記載します。
```
[package]
# Version.
version = "0.0.1"
# Authors.
authors = ["ft-lab"]
# The title and description.
title = "Python Extension Example"
description="xxxxxx."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# ChangeLog.
changelog="docs/CHANGELOG.md"
# Preview image.
preview_image = "data/preview.png"
# Icon image (256x256).
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.loadStage"
```
## ft_lab.sample.loadStage
"ft_lab.sample.loadStage"内は、"ft_lab/sample/loadStage"の階層でフォルダを構成します。
```
[ft_lab]
[sample]
[loadStage]
__init__.py
main.py
```
### __init__.py
開始するメインファイル (hello.py)のインポートを指定します.
```
from .main import *
```
### main.py
```python
from pathlib import Path
# Get USD file.
usdPath = Path(__file__).parent.joinpath("usd")
usdFile = f"{usdPath}/test.usd"
# Load stage.
omni.usd.get_context().open_stage(usdFile)
```
「Path(__file__)」で、main.py自身の絶対パスを返します。
「parent」でその親のフォルダ、「joinpath("usd")」でusdフォルダ。
この場合は、usdPathは「ft_lab/sample/loadStage/usd」のパスになります。
usdFileは「ft_lab/sample/loadStage/usd/test.usd」となります。
Extension内にusdファイルを入れている構成です。
「omni.usd.get_context().open_stage(usdFile)」で指定のパスのファイルをステージとして読み込みます。
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Load Stage"
description="Sample of opening usd."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.loadStage"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/ft_lab/sample/loadStage/main.py | from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf
import omni.ext
from pathlib import Path
class LoadStageExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[ft_lab.sample.loadStage] LoadStageExtension startup")
# Get USD file.
usdPath = Path(__file__).parent.joinpath("usd")
usdFile = f"{usdPath}/test.usd"
# Load stage.
omni.usd.get_context().open_stage(usdFile)
def on_shutdown(self):
print("[ft_lab.sample.loadStage] LoadStageExtension shutdown")
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/ft_lab/sample/loadStage/__init__.py | from .main import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.loadStage`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/docs/README.md | # Python Extension Example [ft_lab.sample.loadStage]
sample extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.loadStage/docs/index.rst | ft_lab.sample.loadStage
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "UI Scene draw example"
description="omni.ui scene draw example"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.uiSceneDraw"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/ft_lab/sample/uiSceneDraw/main.py | import omni.ext
import omni.ui
from omni.ui import color as cl
from omni.ui import scene as sc
from pathlib import Path
import math
# -------------------------------------.
# Scene draw process.
# -------------------------------------.
class SceneDraw(sc.Manipulator):
_angle1 = 0.0
_angle2 = 0.0
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._angle1 = 0.0
self._angle2 = 45.0
def on_build(self):
# Consider the order. This uses the z-value Depth.
# -1.0 < depth <= 0.0
depth = 0.0
moveT = sc.Matrix44.get_translation_matrix(0.0, 0.0, depth)
with sc.Transform(transform=moveT):
sc.Rectangle(2.0, 2.0, wireframe=False, color=cl("#003000"))
depth = -0.1
rotT = sc.Matrix44.get_rotation_matrix(0, 0, self._angle1, True)
moveT = sc.Matrix44.get_translation_matrix(0.25, 0.3, depth)
viewT = moveT * rotT
with sc.Transform(transform=viewT):
sc.Rectangle(1.5, 0.15, wireframe=False, color=cl("#3030ff"))
depth = -0.15
rotT = sc.Matrix44.get_rotation_matrix(0, 0, self._angle2, True)
moveT = sc.Matrix44.get_translation_matrix(-0.25, -0.1, depth)
viewT = moveT * rotT
with sc.Transform(transform=viewT):
sc.Rectangle(1.5, 0.15, wireframe=False, color=cl("#ff3030"))
self._angle1 = math.fmod(self._angle1 + 0.2, 360.0)
self._angle2 = math.fmod(self._angle2 + 0.1, 360.0)
self.invalidate()
# ----------------------------------------------------------.
class UISceneDrawExtension(omni.ext.IExt):
_window = None
_scene_view = None
# ------------------------------------------------.
# Init window.
# ------------------------------------------------.
def init_window (self):
imagesPath = Path(__file__).parent.joinpath("images")
# Create new window.
self._window = omni.ui.Window("UI Scene Draw Window", width=400, height=400)
# ------------------------------------------.
with self._window.frame:
# Create window UI.
with omni.ui.VStack(height=0):
omni.ui.Spacer(height=4)
omni.ui.Label("Use omni.ui.scene for custom drawing.")
omni.ui.Spacer(height=4)
self._scene_view = sc.SceneView(
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=300
)
with self._scene_view.scene:
SceneDraw()
# ------------------------------------------------.
# Term window.
# ------------------------------------------------.
def term_window (self):
if self._window != None:
self._window = None
# ------------------------------------------------.
# Startup.
# ------------------------------------------------.
def on_startup(self, ext_id):
self.init_window()
# ------------------------------------------------.
# Shutdown.
# ------------------------------------------------.
def on_shutdown(self):
self.term_window()
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/ft_lab/sample/uiSceneDraw/__init__.py | from .main import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.uiSceneDraw`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/docs/README.md | # Python Extension Example [ft_lab.sample.uiSceneDraw]
sample extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneDraw/docs/index.rst | ft_lab.sample.uiSceneDraw
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/readme.md | # ft_lab.sample.menu
"ft_lab.sample.menu" はメニューを追加する簡単なサンプルExtensionです。
## Extensionの構成
"ft_lab.sample.menu" Extensionの構成です。
```
[ft_lab.sample.menu]
[config]
extension.toml
[data]
icon.png ... Icon file (256 x 256 pixel).
preview.png
[docs]
CHANGELOG.md
index.rst
README.md
[ft_lab]
[sample]
[menu]
__init__.py
main.py
```
## data/icon.png
アイコンファイル(256 x 256 pixel)。
"config/extension.toml"から参照されます。
## data/preview.png
ExtensionウィンドウのOVERVIEWで表示される画像です。
"config/extension.toml"から参照されます。
## docs
ドキュメント。
|ファイル名|説明|
|---|---|
|index.rst|ドキュメントの構造を記載したファイル。|
|README.md|OVERVIEWに表示される内容。|
|CHANGELOG.md|CHANGELOGに表示される内容。|
### index.rst
```
ft_lab.sample.menu
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
```
## config/extension.toml
"extension.toml"はExtentionの設定を記載します。
```
[package]
version = "0.0.1"
authors = ["ft-lab"]
title = "Menu Test"
description="Sample of adding a Menu."
readme = "docs/README.md"
repository = ""
category = "Example"
keywords = ["kit", "example"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
[[python.module]]
name = "ft_lab.sample.menu"
```
## ft_lab.sample.menu
"ft_lab.sample.menu"内は、"ft_lab/sample/menu"の階層でフォルダを構成します。
```
[ft_lab]
[sample]
[menu]
__init__.py
main.py
```
### __init__.py
開始するメインファイル (main.py)のインポートを指定します.
```
from .main import *
```
### main.py
Extensionの開始時と終了時に呼び出すメソッドを指定します。
```python
class MenuExtension(omni.ext.IExt):
# Menu list.
_menu_list = None
_sub_menu_list = None
# Menu name.
_menu_name = "MenuTest"
def on_startup(self, ext_id):
print("[ft_lab.sample.menu] MenuExtension startup")
# Initialize menu.
self.init_menu()
def on_shutdown(self):
print("[ft_lab.sample.menu] MenuExtension shutdown")
# Term menu.
self.term_menu()
```
"on_startup"でExtensionを開始したときの処理を記載します。
ここの「self.init_menu()」にてメニューを作成しています。
"on_shutdown"でExtensionを終了したときの処理を記載します。
ここの「self.term_menu()」にてメニューの破棄処理を行っています。
メニューの初期化処理は以下のように記載。
```python
def init_menu (self):
async def _rebuild_menus():
await omni.kit.app.get_app().next_update_async()
omni.kit.menu.utils.rebuild_menus()
def menu_select (mode):
if mode == 0:
print("Select MenuItem 1.")
if mode == 1:
print("Select MenuItem 2.")
if mode == 2:
print("Select MenuItem 3.")
if mode == 10:
print("Select Sub MenuItem 1.")
if mode == 11:
print("Select Sub MenuItem 2.")
self._sub_menu_list = [
MenuItemDescription(name="Sub MenuItem 1", onclick_fn=lambda: menu_select(10)),
MenuItemDescription(name="Sub MenuItem 2", onclick_fn=lambda: menu_select(11)),
]
self._menu_list = [
MenuItemDescription(name="MenuItem 1", onclick_fn=lambda: menu_select(0)),
MenuItemDescription(name="MenuItem 2", onclick_fn=lambda: menu_select(1)),
MenuItemDescription(name="MenuItem 3", onclick_fn=lambda: menu_select(2)),
MenuItemDescription(),
MenuItemDescription(name="SubMenu", sub_menu=self._sub_menu_list),
]
# Rebuild with additional menu items.
omni.kit.menu.utils.add_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
```
self._sub_menu_listにメニュー項目を格納しています。
「MenuItemDescription(name="SubMenu", sub_menu=self._sub_menu_list)」でサブメニューを追加しています。
```python
omni.kit.menu.utils.add_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
```
で、メニュー項目を追加し、遅延でメニューを更新しています。
メニュー項目が選択されたときに、選択されているメニュー項目名をprintしています。
メニューの破棄処理は以下のように記載。
```python
def term_menu (self):
async def _rebuild_menus():
await omni.kit.app.get_app().next_update_async()
omni.kit.menu.utils.rebuild_menus()
# Remove and rebuild the added menu items.
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
```
「omni.kit.menu.utils.remove_menu_items」で追加したメニュー項目を削除。
「asyncio.ensure_future(_rebuild_menus())」で遅延でメニューを更新しています。
## Omniverse CreateにExtensionを入れる
Omniverse Createが"pkg/create-2021.3.8"にインストールされているとします。
作成した"ft_lab.sample.menu"をフォルダごと"pkg/create-2021.3.8/exts"に格納します。
Omniverse Createを起動したままでもExtensionを所定のフォルダに入れると、自動的にExtensionが認識されます。
メインメニューの"Window"-"Extensions" を選択し、Extensionsウィンドウを表示します。
Extensionのリストで"Python Extension Example"が存在するのを確認できました。

これをOnにすると、"MenuTest"というメニュー項目が表示されます。

Offにした場合"MenuTest"内は空になりますが、トップメニューの"MenuTest"は残ってしまうようです (Omniverse Create 2021.3.8で確認)。
Omniverse Code 2022.1.0ではこの問題は起きなかったため、この現象は将来Kit側で修正されるものと思われます。
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Menu Test"
description="Sample of adding a Menu."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.menu"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/ft_lab/sample/menu/main.py | import omni.ext
import asyncio
import omni.kit.menu.utils
import omni.kit.undo
import omni.kit.commands
import omni.usd
from omni.kit.menu.utils import MenuItemDescription
class MenuExtension(omni.ext.IExt):
# Menu list.
_menu_list = None
_sub_menu_list = None
# Menu name.
_menu_name = "MenuTest"
# ------------------------------------------.
# Initialize menu.
# ------------------------------------------.
def init_menu (self):
async def _rebuild_menus():
await omni.kit.app.get_app().next_update_async()
omni.kit.menu.utils.rebuild_menus()
def menu_select (mode):
if mode == 0:
print("Select MenuItem 1.")
if mode == 1:
print("Select MenuItem 2.")
if mode == 2:
print("Select MenuItem 3.")
if mode == 10:
print("Select Sub MenuItem 1.")
if mode == 11:
print("Select Sub MenuItem 2.")
self._sub_menu_list = [
MenuItemDescription(name="Sub MenuItem 1", onclick_fn=lambda: menu_select(10)),
MenuItemDescription(name="Sub MenuItem 2", onclick_fn=lambda: menu_select(11)),
]
self._menu_list = [
MenuItemDescription(name="MenuItem 1", onclick_fn=lambda: menu_select(0)),
MenuItemDescription(name="MenuItem 2", onclick_fn=lambda: menu_select(1)),
MenuItemDescription(name="MenuItem 3", onclick_fn=lambda: menu_select(2)),
MenuItemDescription(),
MenuItemDescription(name="SubMenu", sub_menu=self._sub_menu_list),
]
# Rebuild with additional menu items.
omni.kit.menu.utils.add_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
# ------------------------------------------.
# Term menu.
# It seems that the additional items in the top menu will not be removed.
# ------------------------------------------.
def term_menu (self):
async def _rebuild_menus():
await omni.kit.app.get_app().next_update_async()
omni.kit.menu.utils.rebuild_menus()
# Remove and rebuild the added menu items.
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._menu_name)
asyncio.ensure_future(_rebuild_menus())
# ------------------------------------------.
def on_startup(self, ext_id):
print("[ft_lab.sample.menu] MenuExtension startup")
# Initialize menu.
self.init_menu()
def on_shutdown(self):
print("[ft_lab.sample.menu] MenuExtension shutdown")
# Term menu.
self.term_menu()
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/ft_lab/sample/menu/__init__.py | from .main import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.menu`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/docs/README.md | # Python Extension Example [ft_lab.sample.menu]
menu sample extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.menu/docs/index.rst | ft_lab.sample.menu
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/readme.md | # ft_lab.sample.callDLL
"ft_lab.sample.hello" はExtensionからC言語のDLLを呼び出す簡単なサンプルです。
## Extensionの構成
"ft_lab.sample.callDLL" Extensionの構成です。
```
[ft_lab.sample.callDLL]
[bin]
[win]
[x64]
OmniverseSimpleDLL.dll ... dll(Win 64bit).
[config]
extension.toml
[data]
icon.png ... Icon file (256 x 256 pixel).
preview.png
[docs]
CHANGELOG.md
index.rst
README.md
[ft_lab]
[sample]
[callDLL]
__init__.py
callDLL.py
[build]
[OmniverseSimpleDLL] ... DLL source project for VS2017.
```
[build]フォルダは説明のために入れていますが、Extensionの構成としては不要な要素です。
削除しても問題ありません。
## data/icon.png
アイコンファイル(256 x 256 pixel)。
"config/extension.toml"から参照されます。
## data/preview.png
ExtensionウィンドウのOVERVIEWで表示される画像です。
"config/extension.toml"から参照されます。
## docs
ドキュメント。
|ファイル名|説明|
|---|---|
|index.rst|ドキュメントの構造を記載したファイル。|
|README.md|OVERVIEWに表示される内容。|
|CHANGELOG.md|CHANGELOGに表示される内容。|
### index.rst
```
ft_lab.sample.callDLL
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
```
## config/extension.toml
"extension.toml"はExtentionの設定を記載します。
```
[package]
# Version.
version = "0.0.1"
# Authors.
authors = ["ft-lab"]
# The title and description.
title = "Calling function from dll"
description="This is sample of calling function from dll using Python's LoadLibrary."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# ChangeLog.
changelog="docs/CHANGELOG.md"
# Preview image.
preview_image = "data/preview.png"
# Icon image (256x256).
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.callDLL"
# Load native library.
[[native.library]]
path = "bin/win/x64/OmniverseSimpleDLL.dll"
```
[[native.library]]にDLLを参照するための相対パスを指定します(DLLファイル名も含む)。
上記の場合は、Extension実行時に自動的に"bin/win/x64/"がdllの検索パスとして参照されます。
## ft_lab.sample.callDLL
"ft_lab.sample.callDLL"内は、"ft_lab/sample/callDLL"の階層でフォルダを構成します。
```
[ft_lab]
[sample]
[callDLL]
__init__.py
callDLL.py
```
### __init__.py
開始するメインファイル (callDLL.py)のインポートを指定します.
```
from .callDLL import *
```
### callDLL.py
Extensionの開始時と終了時に呼び出すメソッドを指定します。
"dll = cdll.LoadLibrary(r"OmniverseSimpleDLL.dll")"の指定によりDLLが読み込まれます。
```python
import omni.ext
from ctypes import *
# Load library.
# Add the search path for [[native.library]] to "config/extension.toml".
dll = cdll.LoadLibrary(r"OmniverseSimpleDLL.dll")
# ----------------------------------------------------.
# Call external function.
# ----------------------------------------------------.
def callExtFunc():
if dll == None:
return
v = dll.ext_add(3, 8)
print("dll.ext_add(3, 8) : " + str(v))
v2 = dll.ext_sub(3, 8)
print("dll.ext_sub(3, 8) : " + str(v2))
# ----------------------------------------------------.
class CallDLLExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[ft_lab.sample.callDLL] HelloExtension startup")
callExtFunc()
def on_shutdown(self):
print("[ft_lab.sample.callDLL] HelloExtension shutdown")
```
"ext_add"、"ext_sub"がDLLに定義されている外部関数になります。
## Omniverse CreateにExtensionを入れる
Omniverse Createが"pkg/create-2021.3.8"にインストールされているとします。
このとき、開発者が作成したExtensionを"pkg/create-2021.3.8/exts"に入れます。
作成した"ft_lab.sample.callDLL"をフォルダごと"pkg/create-2021.3.8/exts"に格納します。
Omniverse Createを起動したままでもExtensionを所定のフォルダに入れると、自動的にExtensionが認識されます。
メインメニューの"Window"-"Extensions" を選択し、Extensionsウィンドウを表示します。
Extensionのリストで"Calling function from dll"が存在するのを確認できました。

|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/build/OmniverseSimpleDLL/OmniverseSimpleDLL/sources/dllmain.cpp |
#include <windows.h>
#include <stdio.h>
#define DLL_API extern "C" __declspec(dllexport)
// ----------------------------------------------------------------.
// DLLMain.
// ----------------------------------------------------------------.
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// ----------------------------------------------------------------.
// External functions.
// ----------------------------------------------------------------.
DLL_API int ext_add (int a, int b) {
return a + b;
}
DLL_API int ext_sub (int a, int b) {
return a - b;
}
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Calling function from dll"
description="This is sample of calling function from dll using Python's LoadLibrary."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.callDLL"
# Load native library.
[[native.library]]
path = "bin/win/x64/OmniverseSimpleDLL.dll"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/ft_lab/sample/callDLL/__init__.py | from .callDLL import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/ft_lab/sample/callDLL/callDLL.py | import omni.ext
from ctypes import *
# Load library.
# Add the search path for [[native.library]] to "config/extension.toml".
dll = cdll.LoadLibrary(r"OmniverseSimpleDLL.dll")
# ----------------------------------------------------.
# Call external function.
# ----------------------------------------------------.
def callExtFunc():
if dll == None:
return
v = dll.ext_add(3, 8)
print("dll.ext_add(3, 8) : " + str(v))
v2 = dll.ext_sub(3, 8)
print("dll.ext_sub(3, 8) : " + str(v2))
# ----------------------------------------------------.
class CallDLLExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[ft_lab.sample.callDLL] HelloExtension startup")
callExtFunc()
def on_shutdown(self):
print("[ft_lab.sample.callDLL] HelloExtension shutdown")
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.callDLL`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/docs/README.md | # Calling function from dll [ft_lab.sample.callDLL]
This is sample of calling function from dll using Python's LoadLibrary.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.callDLL/docs/index.rst | ft_lab.sample.callDLL
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Widgets ProgressBar example"
description="omni.ui widgets ProgressBar example"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.widgets_progressBar"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/ft_lab/sample/widgets_progressBar/extension.py | import omni.ext
import omni.ui
from pathlib import Path
import os.path
import carb.tokens
import carb.events
import time
# ----------------------------------------------------------.
class WidgetsExtension(omni.ext.IExt):
_window = None
_btn = None # omni.ui.Button.
_progressBar = None # omni.ui.ProgressBar.
_progressValue = 0.2 # PrograssBar value.
_progressStart = True # True if Progress is to proceed.
_subs = None # Update Events.
_timeV = 0
# ------------------------------------.
# Update event.
# ------------------------------------.
def on_update (self, e: carb.events.IEvent):
# Processing every 0.2 seconds.
curTimeV = time.time()
if curTimeV - self._timeV > 0.2:
self._timeV = curTimeV
# Update progressBar.
if self._progressStart:
self._progressValue += 0.05
if self._progressValue > 1.0:
self._progressValue -= 1.0
self._progressBar.model.set_value(self._progressValue)
# ------------------------------------------------.
# Init window.
# ------------------------------------------------.
def init_window (self):
self._progressStart = True
self._timeV = time.time()
# Create new window.
self._window = omni.ui.Window("Widgets Window(ProgressBar)", width=300, height=100)
# Callback when button is clicked.
def onButtonClicked (self):
if self._progressStart:
self._progressStart = False
else:
self._progressStart = True
# Change button text.
if self._progressStart:
self._btn.text = "Stop"
else:
self._btn.text = "Start"
# ------------------------------------------.
with self._window.frame:
# Create window UI.
with omni.ui.VStack(height=0):
# ------------------------------------------.
# ProgressBar & Button.
# ------------------------------------------.
omni.ui.Spacer(height=4)
self._progressBar = omni.ui.ProgressBar(height=14, style={"color": 0xffdd0000})
self._progressBar.model.set_value(self._progressValue)
omni.ui.Spacer(height=4)
self._btn = omni.ui.Button(" Button ")
self._btn.set_clicked_fn(lambda s = self : onButtonClicked(s))
if self._progressStart:
self._btn.text = "Stop"
else:
self._btn.text = "Start"
omni.ui.Spacer(height=4)
# Register for update events.
# To clear the event, specify "subs=None".
self._subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self.on_update)
# ------------------------------------------------.
# Term window.
# ------------------------------------------------.
def term_window (self):
if self._subs != None:
self._subs = None
if self._window != None:
self._window = None
# ------------------------------------------------.
# Startup.
# ------------------------------------------------.
def on_startup(self, ext_id):
self.init_window()
# ------------------------------------------------.
# Shutdown.
# ------------------------------------------------.
def on_shutdown(self):
self.term_window()
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/ft_lab/sample/widgets_progressBar/__init__.py | from .extension import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.widgets_progressBar`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/docs/README.md | # Python Extension Example [ft_lab.sample.widgets_progressBar]
sample extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets_progressBar/docs/index.rst | ft_lab.sample.widgets_progressBar
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Extensions/knowledge/config_info.md | # extension.tomlでの記述内容
"extension.toml"に記載する内容の覚書です。
## 他のExtensionを使用し、機能を呼び出したい
他のExtensionの機能を使用したい場合、[dependencies]にExtension名を追加します。
```
[dependencies]
"omni.audioplayer" = {}
```
この場合は「omni.audioplayer」を有効にします。
こうすることで、Pythonで「import omni.audioplayer」が使用できるようになります。
なお、参照で記載するExtension名は [[python.module]] に記載しているものと同じになります。
以下は「omni.audioplayer」内の"extension.toml"の記載です。
```
[[python.module]]
name = "omni.audioplayer"
```
ここで記載しているExtensionがOnになっていない場合は、対象のExtensionを起動した時に自動的にOnになります。
## 外部のC/C++モジュールを呼び出す
Windows環境の場合、dllの形で外部関数を作成します。
これをExtensionから呼び出すことができます。
```
[[native.library]]
path = "bin/win/x64/OmniverseSimpleDLL.dll"
```
DLL呼び出しのサンプルExtensionは「[ft_lab.sample.callDLL](../ft_lab.sample.callDLL)」をご参照くださいませ。
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "Widgets example"
description="omni.ui widgets example"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.widgets"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/ft_lab/sample/widgets/extension.py | import omni.ext
import omni.ui
from pathlib import Path
import os.path
import carb.tokens
# ----------------------------------------------------------.
class WidgetsExtension(omni.ext.IExt):
_window = None
_sField = None
_label0 = None
_radioCollection = None
_label1 = None
_checkbox = None
_label2 = None
_combobox = None
_label3 = None
_slider = None
_label4 = None
# ------------------------------------------------.
# Init window.
# ------------------------------------------------.
def init_window (self):
imagesPath = Path(__file__).parent.joinpath("images")
# Create new window.
self._window = omni.ui.Window("Widgets Window", width=300, height=400)
# Radio Button Style.
style = {
"": {"background_color": 0x0, "image_url": f"{imagesPath}/radio_off.svg"},
":checked": {"image_url": f"{imagesPath}/radio_on.svg"},
}
def onButtonClicked (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
v = uiFieldModel.model.get_value_as_string()
uiLabel.text = "Input : " + v
def onRadioValueChanged (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
v = uiFieldModel.get_value_as_int()
uiLabel.text = "Select Radio : " + str(v)
def onCheckBoxValueChanged (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
b = uiFieldModel.get_value_as_bool()
uiLabel.text = "CheckBox : " + str(b)
def onComboBoxValueChanged (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
v = uiFieldModel.get_value_as_int()
uiLabel.text = "ComboBox : " + str(v)
def onSliderValueChanged (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
v = uiFieldModel.get_value_as_float()
uiLabel.text = "Slider : " + str(v)
# ------------------------------------------.
with self._window.frame:
# Create window UI.
with omni.ui.VStack(height=0):
# ------------------------------------------.
# StringField & Button.
# ------------------------------------------.
omni.ui.Spacer(height=4)
self._sField = omni.ui.StringField(width=120, height=14, style={"color": 0xffffffff})
self._sField.model.set_value("xxx")
omni.ui.Spacer(height=4)
omni.ui.Spacer(height=4)
btn = omni.ui.Button(" Button ")
omni.ui.Spacer(height=4)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label0 = omni.ui.Label("")
btn.set_clicked_fn(lambda s = self._sField, l = self._label0: onButtonClicked(s, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# Radio Button.
# ------------------------------------------.
# Radio button.
self._radioCollection = omni.ui.RadioCollection()
radioLBtnList = []
with omni.ui.HStack(width=0):
for i in range(3):
with omni.ui.HStack(style=style):
radio = omni.ui.RadioButton(radio_collection=self._radioCollection, width=30, height=30)
omni.ui.Label(f"Radio {i} ", name="text")
radioLBtnList.append(radio)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label1 = omni.ui.Label("")
# Update label.
onRadioValueChanged(self._radioCollection.model, self._label1)
for radio in radioLBtnList:
radio.set_clicked_fn(lambda f = self._radioCollection.model, l = self._label1: onRadioValueChanged(f, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# CheckBox.
# ------------------------------------------.
# CheckBox
omni.ui.Spacer(height=4)
with omni.ui.HStack(width=0):
self._checkbox = omni.ui.CheckBox()
omni.ui.Label(" CheckBox")
omni.ui.Spacer(height=4)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label2 = omni.ui.Label("")
# Update label.
onCheckBoxValueChanged(self._checkbox.model, self._label2)
self._checkbox.model.add_value_changed_fn(lambda f = self._checkbox.model, l = self._label2: onCheckBoxValueChanged(f, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# ComboBox.
# ------------------------------------------.
# ComboBox
omni.ui.Spacer(height=4)
self._combobox = omni.ui.ComboBox(1, "Item1", "Item2", "Item3")
omni.ui.Spacer(height=4)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label3 = omni.ui.Label("")
# Update label.
onComboBoxValueChanged(self._combobox.model.get_item_value_model(), self._label3)
cModel = self._combobox.model.get_item_value_model()
cModel.add_value_changed_fn(lambda f = cModel, l = self._label3: onComboBoxValueChanged(f, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# Slider.
# ------------------------------------------.
# Slider.
omni.ui.Spacer(height=4)
self._slider = omni.ui.FloatSlider(min=0.0, max=10.0)
self._slider.model.set_value(1.2)
omni.ui.Spacer(height=4)
# Label.
with omni.ui.HStack(width=0):
omni.ui.Spacer(width=8)
self._label4 = omni.ui.Label("")
onSliderValueChanged(self._slider.model, self._label4)
self._slider.model.add_value_changed_fn(lambda f = self._slider.model, l = self._label4: onSliderValueChanged(f, l))
# Separator.
omni.ui.Spacer(height=4)
omni.ui.Line(style={"border_width":2, "color":0xff202020})
omni.ui.Spacer(height=4)
# ------------------------------------------.
# Image.
# ------------------------------------------.
# Kit file path.
kitAbsPath = os.path.abspath(carb.tokens.get_tokens_interface().resolve("${kit}"))
# Load image (RGBA).
imagePath = Path(kitAbsPath).joinpath("resources").joinpath("desktop-icons")
imagePath = f"{imagePath}/omniverse_64.png"
omni.ui.Image(imagePath, width=64, height=64)
# ------------------------------------------------.
# Term window.
# ------------------------------------------------.
def term_window (self):
if self._window != None:
self._window = None
# ------------------------------------------------.
# Startup.
# ------------------------------------------------.
def on_startup(self, ext_id):
self.init_window()
# ------------------------------------------------.
# Shutdown.
# ------------------------------------------------.
def on_shutdown(self):
self.term_window()
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/ft_lab/sample/widgets/__init__.py | from .extension import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.widgets`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/docs/README.md | # Python Extension Example [ft_lab.sample.widgets]
sample extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/docs/index.rst | ft_lab.sample.widgets
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneViewportOverlay/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "UI Scene draw viewport overlay example"
description="omni.ui scene draw viewport overlay example"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
"omni.ui.scene" = {}
"omni.kit.viewport.utility" = {}
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.uiSceneViewportOverlay"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneViewportOverlay/ft_lab/sample/uiSceneViewportOverlay/extension.py | from pxr import Usd, UsdGeom, CameraUtil, UsdShade, Sdf, Gf, Tf
import omni.ext
import omni.ui
from omni.ui import color as cl
from omni.ui import scene as sc
import omni.kit
from pathlib import Path
import math
# Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window
import omni.kit.viewport.utility
# Reference : https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene
# ----------------------------------------------------------.
class UISceneViewportOverlayExtension(omni.ext.IExt):
_scene_view = None
_stage = None
_viewport_api = None
_active_vp_window = None
# ------------------------------------------------.
# Init window.
# ------------------------------------------------.
def init_window (self, ext_id : str):
imagesPath = Path(__file__).parent.joinpath("images")
# Get current stage.
self._stage = omni.usd.get_context().get_stage()
# Kit104 : Get active viewport window.
self._active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
self._viewport_api = self._active_vp_window.viewport_api
with self._active_vp_window.get_frame(ext_id):
self._scene_view = sc.SceneView()
with self._scene_view.scene:
# Edges of cube
cubeSize = 100.0
sc.Line([-cubeSize, -cubeSize, -cubeSize], [cubeSize, -cubeSize, -cubeSize])
sc.Line([-cubeSize, cubeSize, -cubeSize], [cubeSize, cubeSize, -cubeSize])
sc.Line([-cubeSize, -cubeSize, cubeSize], [cubeSize, -cubeSize, cubeSize])
sc.Line([-cubeSize, cubeSize, cubeSize], [cubeSize, cubeSize, cubeSize])
sc.Line([-cubeSize, -cubeSize, -cubeSize], [-cubeSize, cubeSize, -cubeSize])
sc.Line([cubeSize, -cubeSize, -cubeSize], [cubeSize, cubeSize, -cubeSize])
sc.Line([-cubeSize, -cubeSize, cubeSize], [-cubeSize, cubeSize, cubeSize])
sc.Line([cubeSize, -cubeSize, cubeSize], [cubeSize, cubeSize, cubeSize])
sc.Line([-cubeSize, -cubeSize, -cubeSize], [-cubeSize, -cubeSize, cubeSize])
sc.Line([-cubeSize, cubeSize, -cubeSize], [-cubeSize, cubeSize, cubeSize])
sc.Line([cubeSize, -cubeSize, -cubeSize], [cubeSize, -cubeSize, cubeSize])
sc.Line([cubeSize, cubeSize, -cubeSize], [cubeSize, cubeSize, cubeSize])
# Use Transform to change position.
moveT = sc.Matrix44.get_translation_matrix(0, 0, 0)
with sc.Transform(transform=moveT):
sc.Label("Hello Omniverse !!", alignment = omni.ui.Alignment.CENTER, color=cl("#ffff00a0"), size=20)
# Register the SceneView with the Viewport to get projection and view updates
self._viewport_api.add_scene_view(self._scene_view)
# ------------------------------------------------.
# Term window.
# ------------------------------------------------.
def term_window (self):
if self._scene_view:
# Empty the SceneView of any elements it may have
self._scene_view.scene.clear()
# Be a good citizen, and un-register the SceneView from Viewport updates
if self._active_vp_window:
self._active_vp_window.viewport_api.remove_scene_view(self._scene_view)
self._active_vp_window = None
# ------------------------------------------------.
# Startup.
# ------------------------------------------------.
def on_startup(self, ext_id):
self.init_window(ext_id)
# ------------------------------------------------.
# Shutdown.
# ------------------------------------------------.
def on_shutdown(self):
self.term_window()
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneViewportOverlay/ft_lab/sample/uiSceneViewportOverlay/__init__.py | from .extension import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneViewportOverlay/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.uiSceneViewportOverlay`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneViewportOverlay/docs/README.md | # Python Extension Example [ft_lab.sample.uiSceneViewportOverlay]
sample extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneViewportOverlay/docs/index.rst | ft_lab.sample.uiSceneViewportOverlay
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneShowPrimName/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "UI Scene draw viewport overlay example"
description="omni.ui scene draw viewport overlay example"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
"omni.ui.scene" = {}
"omni.kit.viewport.utility" = {}
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.uiSceneShowPrimName"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneShowPrimName/ft_lab/sample/uiSceneShowPrimName/extension.py | from pxr import Usd, UsdGeom, CameraUtil, UsdShade, UsdSkel, Sdf, Gf, Tf
import omni.ext
import omni.ui
from omni.ui import color as cl
from omni.ui import scene as sc
import omni.kit
import omni.kit.app
import carb.events
from pathlib import Path
import time
# Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window
import omni.kit.viewport.utility
# Reference : https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene
# -------------------------------------.
# Scene draw process.
# -------------------------------------.
class SceneDraw (sc.Manipulator):
_viewport_api = None
def __init__(self, viewport_api, **kwargs):
super().__init__ (**kwargs)
# Set Viewport API.
self._viewport_api = viewport_api
# -------------------------------------------.
# Repaint.
# -------------------------------------------.
def on_build (self):
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
time_code = Usd.TimeCode.Default()
xformCache = UsdGeom.XformCache(time_code)
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid():
# Get world Transform.
globalPose = xformCache.GetLocalToWorldTransform(prim)
# Decompose transform.
translate, rotation, scale = UsdSkel.DecomposeTransform(globalPose)
# World to NDC space (X : -1.0 to +1.0, Y : -1.0 to +1.0).
ndc_pos = self._viewport_api.world_to_ndc.Transform(translate)
# Translation matrix.
moveT = sc.Matrix44.get_translation_matrix(ndc_pos[0], ndc_pos[1], 0.0)
# Draw prim name.
with sc.Transform(transform=moveT):
sc.Label(prim.GetName(), alignment = omni.ui.Alignment.CENTER, color=cl("#ffff00a0"), size=20)
# ----------------------------------------------------------.
class UISceneShowPrimNameExtension(omni.ext.IExt):
_scene_view = None
_stage = None
_sceneDraw = None
_time = 0
_selectedPrimPaths = None
_active_vp_window = None
_viewport_api = None
_active_viewport_name = ""
_ext_id = ""
# ------------------------------------------------.
# Update event.
# Update when selection shape changes.
# Update when the active viewport is switched.
# ------------------------------------------------.
def on_update (self, e: carb.events.IEvent):
# Check every 0.2 seconds.
curTime = time.time()
diffTime = curTime - self._time
if diffTime > 0.2:
self._time = curTime
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# Selection changed.
if self._selectedPrimPaths == None or self._selectedPrimPaths != paths:
self._selectedPrimPaths = paths
# Update drawing.
if self._sceneDraw != None:
self._sceneDraw.invalidate()
# If the active viewport name has changed.
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
if active_vp_window != None and active_vp_window.name != self._active_viewport_name:
# Rebuild overlay.
self.term_window()
self.init_window(self._ext_id)
# ------------------------------------------------.
# Init window.
# ------------------------------------------------.
def init_window (self, ext_id : str):
self._ext_id = ext_id
# Get current stage.
self._stage = omni.usd.get_context().get_stage()
self._time = time.time()
# Kit104 : Get active viewport window.
self._active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
# Get viewport API.
self._viewport_api = self._active_vp_window.viewport_api
# Register a callback to be called when the camera in the viewport is changed.
self._subs_viewport_change = self._viewport_api.subscribe_to_view_change(self._viewport_changed)
with self._active_vp_window.get_frame(ext_id):
self._scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self._scene_view.scene:
ObjectInfoManipulator(model=ObjectInfoModel())
# Register the SceneView with the Viewport to get projection and view updates
self._viewport_api.add_scene_view(self._scene_view)
# ------------------------------------------------.
# Term window.
# ------------------------------------------------.
def term_window (self):
if self._scene_view:
# Empty the SceneView of any elements it may have
self._scene_view.scene.clear()
# Be a good citizen, and un-register the SceneView from Viewport updates
if self._active_vp_window:
self._active_vp_window.viewport_api.remove_scene_view(self._scene_view)
self._active_vp_window = None
# ------------------------------------------------.
# Startup.
# ------------------------------------------------.
def on_startup(self, ext_id):
self.init_window(ext_id)
# ------------------------------------------------.
# Shutdown.
# ------------------------------------------------.
def on_shutdown(self):
self.term_window()
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneShowPrimName/ft_lab/sample/uiSceneShowPrimName/__init__.py | from .extension import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneShowPrimName/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.uiSceneShowPrimName`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneShowPrimName/docs/README.md | # Python Extension Example [ft_lab.sample.uiSceneShowPrimName]
sample extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneShowPrimName/docs/index.rst | ft_lab.sample.uiSceneShowPrimName
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiScene/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["ft-lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "UI Scene example"
description="omni.ui scene example"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
# Main python module this extension provides.
[[python.module]]
name = "ft_lab.sample.uiScene"
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiScene/ft_lab/sample/uiScene/extension.py | import omni.ext
import omni.ui
from omni.ui import color as cl
from omni.ui import scene as sc
from pathlib import Path
# ----------------------------------------------------------.
class UISceneExtension(omni.ext.IExt):
_window = None
_scene_view = None
# ------------------------------------------------.
# Init window.
# ------------------------------------------------.
def init_window (self):
imagesPath = Path(__file__).parent.joinpath("images")
# Create new window.
self._window = omni.ui.Window("UI Scene Window", width=300, height=400)
# ------------------------------------------.
with self._window.frame:
# Create window UI.
with omni.ui.VStack(height=0):
omni.ui.Spacer(height=4)
omni.ui.Label("Use omni.ui.scene for custom drawing.")
omni.ui.Spacer(height=4)
self._scene_view = sc.SceneView(
aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT,
height=200
)
with self._scene_view.scene:
sc.Line([-1.0, -1.0, 0], [1.0, 1.0, 0], color=cl.red, thickness=2)
sc.Line([-1.0, 1.0, 0], [1.0, -1.0, 0], color=cl.green, thickness=1)
sc.Arc(0.5, color=cl("#5040ff"))
sc.Rectangle(0.3, 0.3, wireframe=False, color=cl("#c0ff00"))
# Use Transform to change position.
moveT = sc.Matrix44.get_translation_matrix(0.0, -0.8, 0)
with sc.Transform(transform=moveT):
sc.Label("Test", alignment = omni.ui.Alignment.CENTER, color=cl.black, size=20)
# ------------------------------------------------.
# Term window.
# ------------------------------------------------.
def term_window (self):
if self._window != None:
self._window = None
# ------------------------------------------------.
# Startup.
# ------------------------------------------------.
def on_startup(self, ext_id):
self.init_window()
# ------------------------------------------------.
# Shutdown.
# ------------------------------------------------.
def on_shutdown(self):
self.term_window()
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiScene/ft_lab/sample/uiScene/__init__.py | from .extension import *
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiScene/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``ft_lab.sample.uiScene`` extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiScene/docs/README.md | # Python Extension Example [ft_lab.sample.uiScene]
sample extension.
|
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiScene/docs/index.rst | ft_lab.sample.uiScene
###########################
.. toctree::
:maxdepth: 1
README
CHANGELOG
|
ft-lab/omniverse_sample_scripts/Rendering/readme.md | # Rendering
レンダリング画像を取得します。
|サンプル|説明|
|---|---|
|[Capture](./Capture)|レンダリング画像を取得|
|
ft-lab/omniverse_sample_scripts/Rendering/Capture/CaptureRenderingColorToBuffer.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import asyncio
from PIL import Image
import ctypes
import carb
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_buffer
# See also : https://forums.developer.nvidia.com/t/how-to-get-the-backbuffer-of-omniverses-current-viewport/236825
# -------------------------------------------.
# Capture LDR.
# -------------------------------------------.
async def capture():
# Get active viewport.
active_viewport = get_active_viewport()
await active_viewport.wait_for_rendered_frames()
# Called when capture is complete.
callbackExit = False
def capture_callback(buffer, buffer_size, width, height, format):
nonlocal callbackExit
print(f"Buffer size : {buffer_size}")
print(f"Resolution : {width} x {height} ")
print(f"TextureFormat : {format}") # TextureFormat.RGBA8_UNORM
# Get capture image.
if str(format) == "TextureFormat.RGBA8_UNORM":
# Get buffer from void *.
try:
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.POINTER(ctypes.c_byte * buffer_size)
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
content = ctypes.pythonapi.PyCapsule_GetPointer(buffer, None)
except Exception as e:
carb.log_error(f"Failed to get capture buffer: {e}")
callbackExit = True
return
# Create image.
# content.contents is RGBA buffers.
image = Image.frombytes("RGBA", (width, height), content.contents)
# Show.
image.show()
callbackExit = True
# Capturing.
cap_obj = capture_viewport_to_buffer(active_viewport, capture_callback)
await omni.kit.app.get_app_interface().next_update_async()
# Wait for a callback to return from a callback.
while callbackExit == False:
await asyncio.sleep(0.05)
print(f"Capture complete.")
# -------------------------------------------.
asyncio.ensure_future( capture() )
|
ft-lab/omniverse_sample_scripts/Rendering/Capture/CaptureRenderingColorToFile.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import asyncio
import carb
import carb.settings
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file
# See also : omni.kit.capture.
# -------------------------------------------.
# Capture LDR/HDR.
# -------------------------------------------.
async def capture(filePath : str, hdr : bool = False):
# Assign ldr/hdr in settings.
settings = carb.settings.get_settings()
prevAsyncRendering = settings.get("/app/asyncRendering")
prevAsyncRenderingLowLatency = settings.get("/app/asyncRenderingLowLatency")
prevHdr = settings.get("/app/captureFrame/hdr")
settings.set("/app/asyncRendering", False)
settings.set("/app/asyncRenderingLowLatency", False)
settings.set("/app/captureFrame/hdr", hdr)
# Get active viewport.
active_viewport = get_active_viewport()
await active_viewport.wait_for_rendered_frames()
# Capturing.
cap_obj = capture_viewport_to_file(active_viewport, filePath)
await omni.kit.app.get_app_interface().next_update_async()
# awaiting completion.
result = await cap_obj.wait_for_result(completion_frames=30)
settings.set("/app/asyncRendering", prevAsyncRendering)
settings.set("/app/asyncRenderingLowLatency", prevAsyncRenderingLowLatency)
settings.set("/app/captureFrame/hdr", prevHdr)
print(f"Capture complete [{filePath}].")
# -------------------------------------------.
asyncio.ensure_future( capture("K:/temp/output.png") )
# HDR capture not working?
asyncio.ensure_future( capture("K:/temp/output.exr", True) )
|
ft-lab/omniverse_sample_scripts/Rendering/Capture/readme.md | # Capture
レンダリング画像を取得。
Kit.104で動作するように確認。
"omni.kit.viewport.utility"を使用したキャプチャ。
|サンプル|説明|
|---|---|
|[CaptureRenderingColorToFile.py](./CaptureRenderingColorToFile.py) |レンダリング画像をファイルに保存。|
|[CaptureRenderingColorToBuffer.py](./CaptureRenderingColorToBuffer.py) |レンダリング画像をバッファ(RGBA)で取得し、PILのImageで表示。|
|[CaptureCameraRenderingColorToBuffer.py](./CaptureCameraRenderingColorToBuffer.py) |指定のカメラからのレンダリングを行い、PILのImageで表示。<br>レンダリングのViewportは非表示にして、オフラインレンダリングを行う。|
## 古い実装
キャプチャを行うには、Extensionの"omni.syntheticdata"をOnにして使用する必要があります。
|サンプル|説明|
|---|---|
|[CaptureRenderingDepth.py](./CaptureRenderingDepth.py)|Synthetic Data Sensorを使用して、レンダリングのDepthをファイル保存。<br>また、Viewportで"Synthetic Data Sensor"の"Depth"をOnにしておく必要があります。<br>|
|
ft-lab/omniverse_sample_scripts/Rendering/Capture/CaptureRenderingDepth.py | """
Use "Synthetic Data Sensor".
This requires that Extension "omni.syntheticdata" be enabled.
Set "Depth" of "Synthetic Data Sensor" to On.
"""
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.ui
import omni.kit.app
import omni.syntheticdata # Use omni.syntheticdata extension.
import numpy as np
from PIL import Image
import itertools
# Colorize Helpers (ref : omni.syntheticdata)
def colorize_depth(depth_image):
height, width = depth_image.shape[:2]
colorized_image = np.zeros((height, width, 4))
depth_image[depth_image == 0.0] = 1e-5
depth_image = np.clip(depth_image, 0, 255)
depth_image -= np.min(depth_image)
depth_image /= np.max(depth_image) + 1e-8
colorized_image[:, :, 0] = depth_image
colorized_image[:, :, 1] = depth_image
colorized_image[:, :, 2] = depth_image
colorized_image[:, :, 3] = 1
colorized_image = (colorized_image * 255).astype(int)
return colorized_image
# Get main window viewport.
window = omni.ui.Window('Viewport')
viewportI = omni.kit.viewport_legacy.acquire_viewport_interface()
vWindow = viewportI.get_viewport_window(None)
iface = omni.syntheticdata._syntheticdata.acquire_syntheticdata_interface()
sensor_list = iface.get_sensor_list(vWindow)
for sensorD in sensor_list:
if iface.get_sensor_type(sensorD) == omni.syntheticdata._syntheticdata.SensorType.DepthLinear:
# Get viewport image.
data = iface.get_sensor_host_float_texture_array(sensorD)
# Get size.
hei, wid = data.shape[:2]
# Store data (buff[hei][wid]).
buff = np.frombuffer(data, np.float32).reshape(hei, wid, -1)
buff[buff == buff.max()] = 0
# Save the Viewport image as a file.
# The path should be rewritten to match your environment.
filePath = "K:/temp/output_depth.png"
# Convert float32 to RGBA.
rgbaBuff = colorize_depth(buff.squeeze())
rgbaBuff2 = list(itertools.chain.from_iterable(rgbaBuff))
rgbaBuff3 = []
for item in rgbaBuff2:
rgbaBuff3.append((item[0], item[1], item[2], item[3]))
# Create new image (with PIL).
im = Image.new("RGBA", (wid, hei), (0, 0, 0, 0))
im.putdata(rgbaBuff3) # store rgba.
im.save(filePath, quality=95)
|
ft-lab/omniverse_sample_scripts/Rendering/Capture/CaptureCameraRenderingColorToBuffer.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import asyncio
from PIL import Image
import ctypes
import carb
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_buffer, create_viewport_window, get_viewport_from_window_name
from omni.kit.viewport.utility.camera_state import ViewportCameraState
# See also : https://forums.developer.nvidia.com/t/how-to-get-the-backbuffer-of-omniverses-current-viewport/236825
# -------------------------------------------.
# Search for viewport with specified name.
# -------------------------------------------.
def SearchViewportWindow(window_name : str):
try:
from omni.kit.viewport.window import get_viewport_window_instances
for window in get_viewport_window_instances(None):
if window.title == window_name:
return window
except ImportError:
pass
return None
# -------------------------------------------.
# Capture LDR.
# -------------------------------------------.
async def captureCamera(cameraPrimPath : str):
if cameraPrimPath == None or cameraPrimPath == "":
carb.log_error("Camera path is not specified.")
return
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(cameraPrimPath)
if prim.IsValid() == False:
carb.log_error(f"[{cameraPrimPath}] could not be found.")
return
# Create a Viewport corresponding to the camera.
# If a Viewport already exists, reuse it.
viewportName = "Viewport Camera"
#viewport_api = get_viewport_from_window_name(viewportName)
viewport_api = None
viewportWindow = SearchViewportWindow(viewportName)
if viewportWindow != None:
viewport_api = viewportWindow.viewport_api
if viewport_api == None:
# Create new viewport.
viewportWindow = create_viewport_window(viewportName, width=800, height=600)
viewport_api = viewportWindow.viewport_api
# Hide Viewport
viewportWindow.visible = False
if viewport_api == None:
carb.log_error("Viewport could not be created.")
return
viewport_api.set_active_camera(cameraPrimPath)
await viewport_api.wait_for_rendered_frames()
# Called when capture is complete.
cImage = None
callbackExit = False
def capture_callback(buffer, buffer_size, width, height, format):
nonlocal cImage
nonlocal callbackExit
print(f"Buffer size : {buffer_size}")
print(f"Resolution : {width} x {height} ")
print(f"TextureFormat : {format}") # TextureFormat.RGBA8_UNORM
if str(format) != "TextureFormat.RGBA8_UNORM":
callbackExit = True
return
# Get capture image.
try:
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.POINTER(ctypes.c_byte * buffer_size)
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
content = ctypes.pythonapi.PyCapsule_GetPointer(buffer, None)
except Exception as e:
carb.log_error(f"Failed to get capture buffer: {e}")
callbackExit = True
return
# Create image.
# content.contents is RGBA buffers.
cImage = Image.frombytes("RGBA", (width, height), content.contents)
callbackExit = True
# Capturing.
cap_obj = capture_viewport_to_buffer(viewport_api, capture_callback)
await omni.kit.app.get_app_interface().next_update_async()
# Wait for a callback to return from a callback.
while callbackExit == False:
await asyncio.sleep(0.05)
# Destroy Viewport window.
# Note that Viewport must be discarded completely or it will consume the GPU.
viewportWindow.destroy()
viewportWindow = None
print(f"Capture complete.")
# Show image.
if cImage != None:
cImage.show()
# -------------------------------------------.
asyncio.ensure_future( captureCamera("/World/Camera") )
|
ft-lab/omniverse_sample_scripts/Camera/GetCurrentCamera.py | from pxr import Usd, UsdGeom, CameraUtil, UsdShade, Sdf, Gf, Tf
import omni.kit
# Get viewport.
# Kit103 : changed from omni.kit.viewport to omni.kit.viewport_legacy
#viewport = omni.kit.viewport_legacy.get_viewport_interface()
#viewportWindow = viewport.get_viewport_window()
# Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window
import omni.kit.viewport.utility
# Get active viewport window.
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
# Get camera path ("/OmniverseKit_Persp" etc).
cameraPath = viewport_api.camera_path.pathString
print("Active camera path : " + cameraPath)
# Get stage.
stage = omni.usd.get_context().get_stage()
#time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond()
time_code = Usd.TimeCode.Default()
# Get active camera.
cameraPrim = stage.GetPrimAtPath(cameraPath)
if cameraPrim.IsValid():
camera = UsdGeom.Camera(cameraPrim) # UsdGeom.Camera
cameraV = camera.GetCamera(time_code) # Gf.Camera
print("Aspect : " + str(cameraV.aspectRatio))
print("fov(H) : " + str(cameraV.GetFieldOfView(Gf.Camera.FOVHorizontal)))
print("fov(V) : " + str(cameraV.GetFieldOfView(Gf.Camera.FOVVertical)))
print("FocalLength : " + str(cameraV.focalLength))
print("World to camera matrix : " + str(cameraV.transform))
viewMatrix = cameraV.frustum.ComputeViewMatrix()
print("View matrix : {viewMatrix}")
viewInv = viewMatrix.GetInverse()
# Camera position(World).
cameraPos = viewInv.Transform(Gf.Vec3f(0, 0, 0))
print(f"Camera position(World) : {cameraPos}")
# Camera vector(World).
cameraVector = viewInv.TransformDir(Gf.Vec3f(0, 0, -1))
print(f"Camera vector(World) : {cameraVector}")
projectionMatrix = cameraV.frustum.ComputeProjectionMatrix()
print(f"Projection matrix : {projectionMatrix}")
#cv = CameraUtil.ScreenWindowParameters(cameraV)
#print(cv.screenWindow)
|
ft-lab/omniverse_sample_scripts/Camera/readme.md | # Camera
カメラ操作を行います。
カメラはUsdGeom.Camera ( https://graphics.pixar.com/usd/release/api/class_usd_geom_camera.html ) を使用します。
Omniverse Kit.102では「omni.kit.viewport」を使っていましたが、kit.103では「omni.kit.viewport_legacy」となりました(とりあえずの変更)。
kit.104では「omni.kit.viewport_legacy」は廃止になっています。
```python
import omni.kit.viewport.utility
# Get active viewport window.
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
# Get camera path ("/OmniverseKit_Persp" etc).
cameraPath = viewport_api.camera_path.pathString
```
としてviewport_apiからカメラのPrimパスを取得します。
kit.104は"Viewport 2.0"となっており、複数のViewportを持つことができます。
そのため、アクティブなビューポートを"omni.kit.viewport.utility.get_active_viewport_window()"から取得してきています。
## サンプル
Kit104以上で動作。
|ファイル|説明|
|---|---|
|[CreateCamera.py](./CreateCamera.py)|カメラを作成|
|[GetCurrentCamera.py](./GetCurrentCamera.py)|カレントのカメラを情報を取得|
|[CalcPanoramaCameraVector.py](./CalcPanoramaCameraVector.py)|立体視用の2つのカメラを作成|
|
ft-lab/omniverse_sample_scripts/Camera/CalcPanoramaCameraVector.py | from pxr import Usd, UsdGeom, CameraUtil, UsdShade, Sdf, Gf, Tf
import omni.kit
# IPD (cm).
ipdValue = 6.4
# Get viewport.
# Kit103 : changed from omni.kit.viewport to omni.kit.viewport_legacy
#viewport = omni.kit.viewport_legacy.get_viewport_interface()
#viewportWindow = viewport.get_viewport_window()
# Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window
import omni.kit.viewport.utility
# Get active viewport window.
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
# Get camera path ("/OmniverseKit_Persp" etc).
cameraPath = viewport_api.camera_path.pathString
# Get stage.
stage = omni.usd.get_context().get_stage()
#time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond()
time_code = Usd.TimeCode.Default()
# ---------------------------------.
# Create new camera.
# ---------------------------------.
def createNewCamera (orgCamera : Gf.Camera, pathName : str, position : Gf.Vec3f, direction : Gf.Vec3f):
cameraGeom = UsdGeom.Camera.Define(stage, pathName)
cameraGeom.CreateFocusDistanceAttr(orgCamera.GetFocusDistanceAttr().Get())
cameraGeom.CreateFocalLengthAttr(orgCamera.GetFocalLengthAttr().Get())
cameraGeom.CreateFStopAttr(orgCamera.GetFStopAttr().Get())
# Set position.
UsdGeom.XformCommonAPI(cameraGeom).SetTranslate((position[0], position[1], position[2]))
# Set rotation(Y-Up (0, 1, 0)).
m = Gf.Matrix4f().SetLookAt(Gf.Vec3f(0, 0, 0), direction, Gf.Vec3f(0, 1, 0))
rV = -m.ExtractRotation().Decompose(Gf.Vec3d(1, 0, 0), Gf.Vec3d(0, 1, 0), Gf.Vec3d(0, 0, 1))
UsdGeom.XformCommonAPI(cameraGeom).SetRotate((rV[0], rV[1], rV[2]), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(cameraGeom).SetScale((1, 1, 1))
# ---------------------------------.
# Get active camera.
cameraPrim = stage.GetPrimAtPath(cameraPath)
if cameraPrim.IsValid():
camera = UsdGeom.Camera(cameraPrim) # UsdGeom.Camera
cameraV = camera.GetCamera(time_code) # Gf.Camera
# Get view matrix.
viewMatrix = cameraV.frustum.ComputeViewMatrix()
# Two camera positions in the view.
ipdH = ipdValue * 0.5
leftVPos = Gf.Vec3f(-ipdH, 0, 0)
rightVPos = Gf.Vec3f( ipdH, 0, 0)
# Camera vector(World).
viewInv = viewMatrix.GetInverse()
vVector = viewInv.TransformDir(Gf.Vec3f(0, 0, -1))
# Convert to camera position in world coordinates.
leftWPos = viewInv.Transform(leftVPos)
rightWPos = viewInv.Transform(rightVPos)
# Create camera.
pathStr = '/World'
leftPathStr = pathStr + '/camera_left'
createNewCamera(camera, leftPathStr, leftWPos, vVector)
rightPathStr = pathStr + '/camera_right'
createNewCamera(camera, rightPathStr, rightWPos, vVector)
|
ft-lab/omniverse_sample_scripts/Camera/CreateCamera.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create camera.
pathName = '/World/camera'
cameraGeom = UsdGeom.Camera.Define(stage, pathName)
cameraGeom.CreateFocalLengthAttr(24.0)
cameraGeom.CreateFocusDistanceAttr(400.0)
cameraGeom.CreateFStopAttr(0.0)
cameraGeom.CreateProjectionAttr('perspective')
# Set position.
UsdGeom.XformCommonAPI(cameraGeom).SetTranslate((0.0, 20.0, 40.0))
# Set rotation.
UsdGeom.XformCommonAPI(cameraGeom).SetRotate((-20, 15.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(cameraGeom).SetScale((1, 1, 1))
# Change active camera.
# Kit103 : changed from omni.kit.viewport to omni.kit.viewport_legacy
#viewport = omni.kit.viewport_legacy.get_viewport_interface()
#viewport.get_viewport_window().set_active_camera(pathName)
# Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window
import omni.kit.viewport.utility
# Get active viewport window.
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
viewport_api.set_active_camera(pathName)
|
ft-lab/omniverse_sample_scripts/Samples/readme.md | # Samples
実用的に使えそうなスクリプトのサンプルです。
|サンプル|説明|
|---|---|
|[CreateSimpleCurve](./CreateSimpleCurve)|複数のSphereをつなぐチューブ形状を生成|
|[UnitsToCentimeters](./UnitsToCentimeters)|Stageの単位をセンチメートルに統一(MetersPerUnitを0.01にする)|
|
ft-lab/omniverse_sample_scripts/Samples/CreateSimpleCurve/readme.md | # CreateSimpleCurve
Xform内の複数のSphereを使用し、Spbereをスプライン補間したチューブ形状を作成します。
## 使い方
複数のSphereを配置します。
このSphereをつなぐようにスプラインでチューブ形状がMeshとして作成されることになります。

また、Xformに対してマテリアルを割り当てておきます。
Xformを選択した状態でScript Editorで「[CreateSimpleCurve.py](./CreateSimpleCurve.py)」を実行します。
Create Curveウィンドウが表示されました。

"Number of divisions"で分割数を指定して"Create"ボタンを押します。
Sphereを曲線上でつないだチューブ形状がMeshとして生成されます。


|
ft-lab/omniverse_sample_scripts/Samples/CreateSimpleCurve/CreateSimpleCurve.py | # ----------------------------------------------------------.
# SplineのCurveを作成するスクリプト.
# ----------------------------------------------------------.
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf
from scipy import interpolate
import numpy as np
import math
import omni.ui
# Get stage.
stage = omni.usd.get_context().get_stage()
rootPath = '/World'
# --------------------------------------------------------.
# 3Dの頂点座標より、スプラインとして細分割した頂点を返す.
# @param[in] vList Gf.Vec3fの配列.4つ以上であること.
# @param[in] divCou 分割数。len(vList)よりも大きい値のこと.
# @return 再分割されたGf.Vec3fの配列.
# --------------------------------------------------------.
def curveInterpolation (vList, divCou : int):
# XYZを配列に分離.
xList = []
yList = []
zList = []
for p in vList:
xList.append(p[0])
yList.append(p[1])
zList.append(p[2])
retVList = []
tck,u = interpolate.splprep([xList, yList, zList], k=3, s=0)
u = np.linspace(0, 1, num=divCou, endpoint=True)
spline = interpolate.splev(u, tck)
for i in range(divCou):
retVList.append(Gf.Vec3f(spline[0][i], spline[1][i], spline[2][i]))
return retVList
# --------------------------------------------------------.
# 選択Primの子で球の座標を配列に格納.
# @return Gf.Vec3fの配列, 半径(cm), マテリアル.
# --------------------------------------------------------.
def getSelectedSpheresPoint ():
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
if len(paths) == 0:
return None
xformCache = UsdGeom.XformCache(0)
prim = stage.GetPrimAtPath(paths[0])
# retRに半径(cm)が入る。vPosList[]に頂点座標が入る.
retR = -1.0
vPosList = []
pChildren = prim.GetChildren()
for cPrim in pChildren:
typeName = cPrim.GetTypeName()
if typeName == 'Sphere':
globalPose = xformCache.GetLocalToWorldTransform(cPrim)
# Decompose transform.
translate, rotation, scale = UsdSkel.DecomposeTransform(globalPose)
# 半径を取得.
if retR < 0.0:
sphereGeom = UsdGeom.Sphere(cPrim)
r = sphereGeom.GetRadiusAttr().Get()
retR = r * scale[0]
vPosList.append(translate)
if len(vPosList) == 0:
return None
# primに割り当てられているマテリアルを取得.
material = None
rel = UsdShade.MaterialBindingAPI(prim).GetDirectBindingRel()
pathList = rel.GetTargets()
if len(pathList) > 0:
materialPath = pathList[0]
material = UsdShade.Material(stage.GetPrimAtPath(materialPath))
return vPosList, retR, material
# --------------------------------------------------------.
# 外積の計算.
# --------------------------------------------------------.
def calcCross (v1 : Gf.Vec3f, v2 : Gf.Vec3f):
v1_2 = Gf.Vec4f(v1[0], v1[1], v1[2], 1.0)
v2_2 = Gf.Vec4f(v2[0], v2[1], v2[2], 1.0)
v3 = Gf.HomogeneousCross(v1_2, v2_2)
return Gf.Vec3f(v3[0], v3[1], v3[2])
# --------------------------------------------------------.
# 進行方向からベクトルを計算.
# @param[in] vDir 進行方向のベクトル.
# @return 4x4行列.
# --------------------------------------------------------.
def calcDirToMatrix (vDir : Gf.Vec3f):
vDir0 = vDir.GetNormalized()
m = Gf.Matrix4f()
vX = Gf.Vec3f(1.0, 0.0, 0.0)
vY = Gf.Vec3f(0.0, 1.0, 0.0)
dirY = vY
angleV = Gf.Dot(vDir0, vY)
if math.fabs(angleV) > 0.999:
dirY = vX
dirX = calcCross(vDir0, dirY)
dirX = dirX.GetNormalized()
dirY = calcCross(dirX, vDir0)
dirY = dirY.GetNormalized()
m[0, 0] = dirX[0]
m[0, 1] = dirX[1]
m[0, 2] = dirX[2]
m[1, 0] = dirY[0]
m[1, 1] = dirY[1]
m[1, 2] = dirY[2]
m[2, 0] = vDir0[0]
m[2, 1] = vDir0[1]
m[2, 2] = vDir0[2]
return m
# --------------------------------------------------------.
# 頂点の配列と半径、分割数により、チューブ状のMeshを作成.
# @param[in] name 形状名.
# @param[in] vList Gf.Vec3fの配列.
# @param[in] radiusV 半径.
# @param[in] divUCou 円の分割数.
# @param[in] divVCou 進行方向での分割数.
# @param[in] material 割り当てるマテリアル.
# --------------------------------------------------------.
def createTubeMesh (name : str, vList, radiusV : float, divUCou : int, divVCou : int, material : UsdShade.Material):
pathStr = rootPath + '/cables'
prim = stage.GetPrimAtPath(pathStr)
if prim.IsValid() == False:
UsdGeom.Xform.Define(stage, pathStr)
prim = stage.GetPrimAtPath(pathStr)
# 子形状に同一名がある場合は連番を付ける.
newName = name
index = 0
pChildren = prim.GetChildren()
if pChildren != None:
while True:
chkF = False
for cPrim in pChildren:
name2 = cPrim.GetName()
if name2 == newName:
index += 1
newName = name + '_' + str(index)
chkF = True
break
if chkF == False:
break
name = newName
meshName = pathStr + '/' + name
meshGeom = UsdGeom.Mesh.Define(stage, meshName)
# Bind material.
if material != None:
UsdShade.MaterialBindingAPI(meshGeom).Bind(material)
# +Zを中心とした半径radiusVのポイントを計算.
circleV = []
dd = (math.pi * 2.0) / ((float)(divUCou))
dPos = 0.0
for i in range(divUCou):
circleV.append(Gf.Vec3f(math.cos(dPos), math.sin(dPos), 0.0))
dPos += dd
# ポリゴンメッシュのポイントと法線.
m = Gf.Matrix4f()
vDir0 = Gf.Vec3f(0.0, 0.0, 1.0)
newVList = []
newVNList = []
vListCou = len(vList)
for i in range(vListCou):
if i + 1 >= vListCou:
p1 = vList[i]
else:
p1 = vList[i]
p2 = vList[(i + 1) % vListCou]
vDir = (p2 - p1).GetNormalized()
if i == 0:
m = calcDirToMatrix(p2 - p1)
vDir0 = vDir
else:
mInv = m.GetInverse()
pV0 = mInv.TransformDir(vDir0)
pV1 = mInv.TransformDir(vDir)
m0 = calcDirToMatrix(pV0)
m1 = calcDirToMatrix(pV1)
m = (m1.GetInverse() * m0).GetInverse() * m
for j in range(divUCou):
p = circleV[j]
p = m.Transform(Gf.Vec3f(p[0] * radiusV, p[1] * radiusV, p[2] * radiusV))
pp = p + p1
newVList.append([pp[0], pp[1], pp[2]])
pN = p.GetNormalized()
newVNList.append([pN[0], pN[1], pN[2]])
vDir0 = vDir
meshGeom.CreatePointsAttr(newVList)
meshGeom.CreateNormalsAttr(newVNList)
# 面の頂点数の配列を格納.
facesCou = (vListCou - 1) * divUCou
faceVCouList = [int] * (facesCou)
for i in range(facesCou):
faceVCouList[i] = 4
meshGeom.CreateFaceVertexCountsAttr(faceVCouList)
# ポリゴンメッシュの面を配置.
faceIndexList = []
iPos = 0
vCou = vListCou - 1
for i in range(vCou):
for j in range(divUCou):
i0 = iPos + j
i1 = iPos + ((j + 1) % divUCou)
if i + 1 >= vListCou:
i2 = ((j + 1) % divUCou)
i3 = j
else:
i2 = iPos + divUCou + ((j + 1) % divUCou)
i3 = iPos + divUCou + j
faceIndexList.append(i3)
faceIndexList.append(i2)
faceIndexList.append(i1)
faceIndexList.append(i0)
iPos += divUCou
meshGeom.CreateFaceVertexIndicesAttr(faceIndexList)
# ------------------------------------------.
# Clicked button event.
# ------------------------------------------.
def onButtonClick(hDivCouIntField):
hDivCou = hDivCouIntField.model.get_value_as_int()
if hDivCou < 4:
hDivCou = 4
# 選択Primの子で球の座標を配列に格納.
retV = getSelectedSpheresPoint()
if retV == None:
print("Select an XForm that contains spheres.")
else:
vPosList, retR, material = retV
# 頂点座標の配置から、細分化した頂点を計算.
newVPosList = curveInterpolation(vPosList, hDivCou)
# チューブ形状を作成.
createTubeMesh('cable', newVPosList, retR, 12, hDivCou, material)
# --------------------------------------------------------.
# メイン部.
# --------------------------------------------------------.
# ------------------------------------------.
# Create new window.
my_window = omni.ui.Window("Create Curve", width=300, height=200)
with my_window.frame:
with omni.ui.VStack(height=0):
hDivCouIntField = None
with omni.ui.Placer(offset_x=8, offset_y=8):
# Set label.
f = omni.ui.Label("Select a Prim with multiple spheres as children.")
with omni.ui.Placer(offset_x=8, offset_y=4):
with omni.ui.HStack(width=300):
omni.ui.Label("Number of divisions : ", width=50)
hDivCouIntField = omni.ui.IntField(width=200, height=0)
hDivCouIntField.model.set_value(50)
with omni.ui.Placer(offset_x=8, offset_y=4):
# Set button.
btn = omni.ui.Button("Create", width=200, height=0)
btn.set_clicked_fn(lambda f = hDivCouIntField: onButtonClick(f))
|
ft-lab/omniverse_sample_scripts/Samples/UnitsToCentimeters/readme.md | # UnitsToCentimeters
Stageの単位をセンチメートルに統一します。
[UnitsToCentimeters.py](./UnitsToCentimeters.py) は、
metersPerUnitを0.01に変換するスクリプトです。
## 使い方
このスクリプトは、StageのmetersPerUnitが0.01(センチメートル)でない場合に
DefaultPrimのscaleを調整し、metersPerUnitを0.01に置き換えます。
ルートPrimがXformで「DefaultPrim」の指定がされているのが必要条件になります。
なお、Nucleus上のusdファイルの場合はmetersPerUnitの変更が許可されないことがありました。
そのため、このスクリプトはローカルのusdに対して行うようにしてください。
なお、このスクリプトはファイル保存は行いません。
必要であれば、処理後にusdファイルを保存してご使用くださいませ。
|
ft-lab/omniverse_sample_scripts/Samples/UnitsToCentimeters/UnitsToCentimeters.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get metersPerUnit (default : 0.01).
metersPerUnit = UsdGeom.GetStageMetersPerUnit(stage)
# ----------------------------------------------------------------------.
# Convert the scale of Mesh and Xform so that metersPerUnit is 0.01.
# ----------------------------------------------------------------------.
def ConvPrimScale (_metersPerUnit, path):
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == False:
return False
# Set xformOpOrder (Xform/Mesh).
transformOrder = prim.GetAttribute('xformOpOrder')
typeName = prim.GetTypeName()
if typeName == 'Xform' or typeName == 'Mesh':
tV = prim.GetAttribute('xformOp:scale')
if tV.IsValid() == False:
if prim.GetAttribute('xformOp:translate').IsValid() == False:
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(0, 0, 0))
if prim.GetAttribute('xformOp:scale').IsValid() == False:
prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(1, 1, 1))
if prim.GetAttribute('xformOp:rotateXYZ').IsValid() == False:
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(0, 0, 0))
transformOrder = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False)
transformOrder.Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
if transformOrder.IsValid() and transformOrder.Get() != None:
tV = prim.GetAttribute('xformOp:scale')
if tV.IsValid():
scaleV = tV.Get()
scale = _metersPerUnit / 0.01
tV.Set(scaleV * scale)
return True
return False
# ----------------------------------------------------------------------.
if abs(metersPerUnit - 0.01) < 1e-5:
print("The units of Stage are already centimeters.")
else:
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
if defaultPrim == None or defaultPrim.IsValid() == False:
print("DefaultPrim does not exist.")
else:
path = defaultPrim.GetPath().pathString
if ConvPrimScale(metersPerUnit, path) == False:
print("Failed to change DefaultPrim.")
else:
# Set metersPerUnit.
try:
UsdGeom.SetStageMetersPerUnit(stage, 0.01)
print("DefaultPrim has been successfully changed.")
except Exception as e:
print(e)
|
ft-lab/omniverse_sample_scripts/Samples/FlipMeshNormals/FlipMeshNormals.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# ------------------------------------------------------------.
# Flip mesh normals.
# ------------------------------------------------------------.
def FlipMeshNormals (prim):
if prim.GetTypeName() == 'Mesh':
m = UsdGeom.Mesh(prim)
# If it is displayed.
if m.ComputeVisibility() == 'inherited':
# Get prim path.
path = prim.GetPath().pathString
print(prim.GetName())
pChildren = prim.GetChildren()
for cPrim in pChildren:
FlipMeshNormals(cPrim)
# ------------------------------------------------------------.
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid():
FlipMeshNormals(prim)
|
ft-lab/omniverse_sample_scripts/Settings/GetRenderingSize.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import carb.settings
# Get rendering size.
# If Render Resolution is "Viewport", -1 will be set.
settings = carb.settings.get_settings()
width = settings.get('/app/renderer/resolution/width')
height = settings.get('/app/renderer/resolution/height')
print("Rendering size : " + str(width) + " x " + str(height))
# Set rendering size.
#settings.set('/app/renderer/resolution/width', 1280)
#settings.set('/app/renderer/resolution/height', 720)
|
ft-lab/omniverse_sample_scripts/Settings/GetKitPath.py | import os.path
import carb.tokens
kitPath = os.path.abspath(carb.tokens.get_tokens_interface().resolve("${kit}"))
print(kitPath)
|
ft-lab/omniverse_sample_scripts/Settings/readme.md | # Settings
carb.settingsより、設定を取得します。
これは"/kit/config/kit-core.json"の情報を読み取ります。
|ファイル|説明|
|---|---|
|[GetKitVersion.py](./GetKitVersion.py)|Omniverse Kitのバージョンを取得|
|[GetKitPath.py](./GetKitPath.py)|Omniverse Kitの絶対パスを取得|
|[GetRenderingSize.py](./GetRenderingSize.py)|レンダリングサイズを取得|
|[GetRenderMode.py](./GetRenderMode.py)|Render Mode(RTX Real-time/RTX Path-traced)を取得、設定<br>Render Modeは、コルーチン内で「await omni.kit.app.get_app().next_update_async()」で1フレーム待ってから変更したほうが安全。|
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.