python_code
stringlengths 0
679k
| repo_name
stringlengths 9
41
| file_path
stringlengths 6
149
|
---|---|---|
import torch
import torch.distributed as dist
from torch.nn.modules import Module
from torch.autograd import Variable
def _flatten_dense_tensors(tensors):
"""Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of
same dense type.
Since inputs are dense, the resulting tensor will be a concatenated 1D
buffer. Element-wise operation on this buffer will be equivalent to
operating individually.
Arguments:
tensors (Iterable[Tensor]): dense tensors to flatten.
Returns:
A contiguous 1D buffer containing input tensors.
"""
if len(tensors) == 1:
return tensors[0].contiguous().view(-1)
flat = torch.cat([t.contiguous().view(-1) for t in tensors], dim=0)
return flat
def _unflatten_dense_tensors(flat, tensors):
"""View a flat buffer using the sizes of tensors. Assume that tensors are of
same dense type, and that flat is given by _flatten_dense_tensors.
Arguments:
flat (Tensor): flattened dense tensors to unflatten.
tensors (Iterable[Tensor]): dense tensors whose sizes will be used to
unflatten flat.
Returns:
Unflattened dense tensors with sizes same as tensors and values from
flat.
"""
outputs = []
offset = 0
for tensor in tensors:
numel = tensor.numel()
outputs.append(flat.narrow(0, offset, numel).view_as(tensor))
offset += numel
return tuple(outputs)
'''
This version of DistributedDataParallel is designed to be used in conjunction with the multiproc.py
launcher included with this example. It assumes that your run is using multiprocess with 1
GPU/process, that the model is on the correct device, and that torch.set_device has been
used to set the device.
Parameters are broadcasted to the other processes on initialization of DistributedDataParallel,
and will be allreduced at the finish of the backward pass.
'''
class DistributedDataParallel(Module):
def __init__(self, module):
super(DistributedDataParallel, self).__init__()
#fallback for PyTorch 0.3
if not hasattr(dist, '_backend'):
self.warn_on_half = True
else:
self.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False
self.module = module
for p in self.module.state_dict().values():
if not torch.is_tensor(p):
continue
dist.broadcast(p, 0)
def allreduce_params():
if(self.needs_reduction):
self.needs_reduction = False
buckets = {}
for param in self.module.parameters():
if param.requires_grad and param.grad is not None:
tp = type(param.data)
if tp not in buckets:
buckets[tp] = []
buckets[tp].append(param)
if self.warn_on_half:
if torch.cuda.HalfTensor in buckets:
print("WARNING: gloo dist backend for half parameters may be extremely slow." +
" It is recommended to use the NCCL backend in this case. This currently requires" +
"PyTorch built from top of tree master.")
self.warn_on_half = False
for tp in buckets:
bucket = buckets[tp]
grads = [param.grad.data for param in bucket]
coalesced = _flatten_dense_tensors(grads)
dist.all_reduce(coalesced)
coalesced /= dist.get_world_size()
for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)):
buf.copy_(synced)
for param in list(self.module.parameters()):
def allreduce_hook(*unused):
param._execution_engine.queue_callback(allreduce_params)
if param.requires_grad:
param.register_hook(allreduce_hook)
def forward(self, *inputs, **kwargs):
self.needs_reduction = True
return self.module(*inputs, **kwargs)
'''
def _sync_buffers(self):
buffers = list(self.module._all_buffers())
if len(buffers) > 0:
# cross-node buffer sync
flat_buffers = _flatten_dense_tensors(buffers)
dist.broadcast(flat_buffers, 0)
for buf, synced in zip(buffers, _unflatten_dense_tensors(flat_buffers, buffers)):
buf.copy_(synced)
def train(self, mode=True):
# Clear NCCL communicator and CUDA event cache of the default group ID,
# These cache will be recreated at the later call. This is currently a
# work-around for a potential NCCL deadlock.
if dist._backend == dist.dist_backend.NCCL:
dist._clear_group_cache()
super(DistributedDataParallel, self).train(mode)
self.module.train(mode)
'''
'''
Modifies existing model to do gradient allreduce, but doesn't change class
so you don't need "module"
'''
def apply_gradient_allreduce(module):
if not hasattr(dist, '_backend'):
module.warn_on_half = True
else:
module.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False
for p in module.state_dict().values():
if not torch.is_tensor(p):
continue
dist.broadcast(p, 0)
def allreduce_params():
if(module.needs_reduction):
module.needs_reduction = False
buckets = {}
for param in module.parameters():
if param.requires_grad and param.grad is not None:
tp = param.data.dtype
if tp not in buckets:
buckets[tp] = []
buckets[tp].append(param)
if module.warn_on_half:
if torch.cuda.HalfTensor in buckets:
print("WARNING: gloo dist backend for half parameters may be extremely slow." +
" It is recommended to use the NCCL backend in this case. This currently requires" +
"PyTorch built from top of tree master.")
module.warn_on_half = False
for tp in buckets:
bucket = buckets[tp]
grads = [param.grad.data for param in bucket]
coalesced = _flatten_dense_tensors(grads)
dist.all_reduce(coalesced)
coalesced /= dist.get_world_size()
for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)):
buf.copy_(synced)
for param in list(module.parameters()):
def allreduce_hook(*unused):
Variable._execution_engine.queue_callback(allreduce_params)
if param.requires_grad:
param.register_hook(allreduce_hook)
def set_needs_reduction(self, input, output):
self.needs_reduction = True
module.register_forward_hook(set_needs_reduction)
return module
| tacotron2-master | distributed.py |
import random
import numpy as np
import torch
import torch.utils.data
import layers
from utils import load_wav_to_torch, load_filepaths_and_text
from text import text_to_sequence
class TextMelLoader(torch.utils.data.Dataset):
"""
1) loads audio,text pairs
2) normalizes text and converts them to sequences of one-hot vectors
3) computes mel-spectrograms from audio files.
"""
def __init__(self, audiopaths_and_text, hparams):
self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)
self.text_cleaners = hparams.text_cleaners
self.max_wav_value = hparams.max_wav_value
self.sampling_rate = hparams.sampling_rate
self.load_mel_from_disk = hparams.load_mel_from_disk
self.stft = layers.TacotronSTFT(
hparams.filter_length, hparams.hop_length, hparams.win_length,
hparams.n_mel_channels, hparams.sampling_rate, hparams.mel_fmin,
hparams.mel_fmax)
random.seed(hparams.seed)
random.shuffle(self.audiopaths_and_text)
def get_mel_text_pair(self, audiopath_and_text):
# separate filename and text
audiopath, text = audiopath_and_text[0], audiopath_and_text[1]
text = self.get_text(text)
mel = self.get_mel(audiopath)
return (text, mel)
def get_mel(self, filename):
if not self.load_mel_from_disk:
audio, sampling_rate = load_wav_to_torch(filename)
if sampling_rate != self.stft.sampling_rate:
raise ValueError("{} {} SR doesn't match target {} SR".format(
sampling_rate, self.stft.sampling_rate))
audio_norm = audio / self.max_wav_value
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
melspec = self.stft.mel_spectrogram(audio_norm)
melspec = torch.squeeze(melspec, 0)
else:
melspec = torch.from_numpy(np.load(filename))
assert melspec.size(0) == self.stft.n_mel_channels, (
'Mel dimension mismatch: given {}, expected {}'.format(
melspec.size(0), self.stft.n_mel_channels))
return melspec
def get_text(self, text):
text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners))
return text_norm
def __getitem__(self, index):
return self.get_mel_text_pair(self.audiopaths_and_text[index])
def __len__(self):
return len(self.audiopaths_and_text)
class TextMelCollate():
""" Zero-pads model inputs and targets based on number of frames per setep
"""
def __init__(self, n_frames_per_step):
self.n_frames_per_step = n_frames_per_step
def __call__(self, batch):
"""Collate's training batch from normalized text and mel-spectrogram
PARAMS
------
batch: [text_normalized, mel_normalized]
"""
# Right zero-pad all one-hot text sequences to max input length
input_lengths, ids_sorted_decreasing = torch.sort(
torch.LongTensor([len(x[0]) for x in batch]),
dim=0, descending=True)
max_input_len = input_lengths[0]
text_padded = torch.LongTensor(len(batch), max_input_len)
text_padded.zero_()
for i in range(len(ids_sorted_decreasing)):
text = batch[ids_sorted_decreasing[i]][0]
text_padded[i, :text.size(0)] = text
# Right zero-pad mel-spec
num_mels = batch[0][1].size(0)
max_target_len = max([x[1].size(1) for x in batch])
if max_target_len % self.n_frames_per_step != 0:
max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step
assert max_target_len % self.n_frames_per_step == 0
# include mel padded and gate padded
mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len)
mel_padded.zero_()
gate_padded = torch.FloatTensor(len(batch), max_target_len)
gate_padded.zero_()
output_lengths = torch.LongTensor(len(batch))
for i in range(len(ids_sorted_decreasing)):
mel = batch[ids_sorted_decreasing[i]][1]
mel_padded[i, :, :mel.size(1)] = mel
gate_padded[i, mel.size(1)-1:] = 1
output_lengths[i] = mel.size(1)
return text_padded, input_lengths, mel_padded, gate_padded, \
output_lengths
| tacotron2-master | data_utils.py |
from torch import nn
class Tacotron2Loss(nn.Module):
def __init__(self):
super(Tacotron2Loss, self).__init__()
def forward(self, model_output, targets):
mel_target, gate_target = targets[0], targets[1]
mel_target.requires_grad = False
gate_target.requires_grad = False
gate_target = gate_target.view(-1, 1)
mel_out, mel_out_postnet, gate_out, _ = model_output
gate_out = gate_out.view(-1, 1)
mel_loss = nn.MSELoss()(mel_out, mel_target) + \
nn.MSELoss()(mel_out_postnet, mel_target)
gate_loss = nn.BCEWithLogitsLoss()(gate_out, gate_target)
return mel_loss + gate_loss
| tacotron2-master | loss_function.py |
import numpy as np
from scipy.io.wavfile import read
import torch
def get_mask_from_lengths(lengths):
max_len = torch.max(lengths).item()
ids = torch.arange(0, max_len, out=torch.cuda.LongTensor(max_len))
mask = (ids < lengths.unsqueeze(1)).bool()
return mask
def load_wav_to_torch(full_path):
sampling_rate, data = read(full_path)
return torch.FloatTensor(data.astype(np.float32)), sampling_rate
def load_filepaths_and_text(filename, split="|"):
with open(filename, encoding='utf-8') as f:
filepaths_and_text = [line.strip().split(split) for line in f]
return filepaths_and_text
def to_gpu(x):
x = x.contiguous()
if torch.cuda.is_available():
x = x.cuda(non_blocking=True)
return torch.autograd.Variable(x)
| tacotron2-master | utils.py |
import os
import time
import argparse
import math
from numpy import finfo
import torch
from distributed import apply_gradient_allreduce
import torch.distributed as dist
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data import DataLoader
from model import Tacotron2
from data_utils import TextMelLoader, TextMelCollate
from loss_function import Tacotron2Loss
from logger import Tacotron2Logger
from hparams import create_hparams
def reduce_tensor(tensor, n_gpus):
rt = tensor.clone()
dist.all_reduce(rt, op=dist.reduce_op.SUM)
rt /= n_gpus
return rt
def init_distributed(hparams, n_gpus, rank, group_name):
assert torch.cuda.is_available(), "Distributed mode requires CUDA."
print("Initializing Distributed")
# Set cuda device so everything is done on the right GPU.
torch.cuda.set_device(rank % torch.cuda.device_count())
# Initialize distributed communication
dist.init_process_group(
backend=hparams.dist_backend, init_method=hparams.dist_url,
world_size=n_gpus, rank=rank, group_name=group_name)
print("Done initializing distributed")
def prepare_dataloaders(hparams):
# Get data, data loaders and collate function ready
trainset = TextMelLoader(hparams.training_files, hparams)
valset = TextMelLoader(hparams.validation_files, hparams)
collate_fn = TextMelCollate(hparams.n_frames_per_step)
if hparams.distributed_run:
train_sampler = DistributedSampler(trainset)
shuffle = False
else:
train_sampler = None
shuffle = True
train_loader = DataLoader(trainset, num_workers=1, shuffle=shuffle,
sampler=train_sampler,
batch_size=hparams.batch_size, pin_memory=False,
drop_last=True, collate_fn=collate_fn)
return train_loader, valset, collate_fn
def prepare_directories_and_logger(output_directory, log_directory, rank):
if rank == 0:
if not os.path.isdir(output_directory):
os.makedirs(output_directory)
os.chmod(output_directory, 0o775)
logger = Tacotron2Logger(os.path.join(output_directory, log_directory))
else:
logger = None
return logger
def load_model(hparams):
model = Tacotron2(hparams).cuda()
if hparams.fp16_run:
model.decoder.attention_layer.score_mask_value = finfo('float16').min
if hparams.distributed_run:
model = apply_gradient_allreduce(model)
return model
def warm_start_model(checkpoint_path, model, ignore_layers):
assert os.path.isfile(checkpoint_path)
print("Warm starting model from checkpoint '{}'".format(checkpoint_path))
checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
model_dict = checkpoint_dict['state_dict']
if len(ignore_layers) > 0:
model_dict = {k: v for k, v in model_dict.items()
if k not in ignore_layers}
dummy_dict = model.state_dict()
dummy_dict.update(model_dict)
model_dict = dummy_dict
model.load_state_dict(model_dict)
return model
def load_checkpoint(checkpoint_path, model, optimizer):
assert os.path.isfile(checkpoint_path)
print("Loading checkpoint '{}'".format(checkpoint_path))
checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
model.load_state_dict(checkpoint_dict['state_dict'])
optimizer.load_state_dict(checkpoint_dict['optimizer'])
learning_rate = checkpoint_dict['learning_rate']
iteration = checkpoint_dict['iteration']
print("Loaded checkpoint '{}' from iteration {}" .format(
checkpoint_path, iteration))
return model, optimizer, learning_rate, iteration
def save_checkpoint(model, optimizer, learning_rate, iteration, filepath):
print("Saving model and optimizer state at iteration {} to {}".format(
iteration, filepath))
torch.save({'iteration': iteration,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
'learning_rate': learning_rate}, filepath)
def validate(model, criterion, valset, iteration, batch_size, n_gpus,
collate_fn, logger, distributed_run, rank):
"""Handles all the validation scoring and printing"""
model.eval()
with torch.no_grad():
val_sampler = DistributedSampler(valset) if distributed_run else None
val_loader = DataLoader(valset, sampler=val_sampler, num_workers=1,
shuffle=False, batch_size=batch_size,
pin_memory=False, collate_fn=collate_fn)
val_loss = 0.0
for i, batch in enumerate(val_loader):
x, y = model.parse_batch(batch)
y_pred = model(x)
loss = criterion(y_pred, y)
if distributed_run:
reduced_val_loss = reduce_tensor(loss.data, n_gpus).item()
else:
reduced_val_loss = loss.item()
val_loss += reduced_val_loss
val_loss = val_loss / (i + 1)
model.train()
if rank == 0:
print("Validation loss {}: {:9f} ".format(iteration, val_loss))
logger.log_validation(val_loss, model, y, y_pred, iteration)
def train(output_directory, log_directory, checkpoint_path, warm_start, n_gpus,
rank, group_name, hparams):
"""Training and validation logging results to tensorboard and stdout
Params
------
output_directory (string): directory to save checkpoints
log_directory (string) directory to save tensorboard logs
checkpoint_path(string): checkpoint path
n_gpus (int): number of gpus
rank (int): rank of current gpu
hparams (object): comma separated list of "name=value" pairs.
"""
if hparams.distributed_run:
init_distributed(hparams, n_gpus, rank, group_name)
torch.manual_seed(hparams.seed)
torch.cuda.manual_seed(hparams.seed)
model = load_model(hparams)
learning_rate = hparams.learning_rate
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
weight_decay=hparams.weight_decay)
if hparams.fp16_run:
from apex import amp
model, optimizer = amp.initialize(
model, optimizer, opt_level='O2')
if hparams.distributed_run:
model = apply_gradient_allreduce(model)
criterion = Tacotron2Loss()
logger = prepare_directories_and_logger(
output_directory, log_directory, rank)
train_loader, valset, collate_fn = prepare_dataloaders(hparams)
# Load checkpoint if one exists
iteration = 0
epoch_offset = 0
if checkpoint_path is not None:
if warm_start:
model = warm_start_model(
checkpoint_path, model, hparams.ignore_layers)
else:
model, optimizer, _learning_rate, iteration = load_checkpoint(
checkpoint_path, model, optimizer)
if hparams.use_saved_learning_rate:
learning_rate = _learning_rate
iteration += 1 # next iteration is iteration + 1
epoch_offset = max(0, int(iteration / len(train_loader)))
model.train()
is_overflow = False
# ================ MAIN TRAINNIG LOOP! ===================
for epoch in range(epoch_offset, hparams.epochs):
print("Epoch: {}".format(epoch))
for i, batch in enumerate(train_loader):
start = time.perf_counter()
for param_group in optimizer.param_groups:
param_group['lr'] = learning_rate
model.zero_grad()
x, y = model.parse_batch(batch)
y_pred = model(x)
loss = criterion(y_pred, y)
if hparams.distributed_run:
reduced_loss = reduce_tensor(loss.data, n_gpus).item()
else:
reduced_loss = loss.item()
if hparams.fp16_run:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
if hparams.fp16_run:
grad_norm = torch.nn.utils.clip_grad_norm_(
amp.master_params(optimizer), hparams.grad_clip_thresh)
is_overflow = math.isnan(grad_norm)
else:
grad_norm = torch.nn.utils.clip_grad_norm_(
model.parameters(), hparams.grad_clip_thresh)
optimizer.step()
if not is_overflow and rank == 0:
duration = time.perf_counter() - start
print("Train loss {} {:.6f} Grad Norm {:.6f} {:.2f}s/it".format(
iteration, reduced_loss, grad_norm, duration))
logger.log_training(
reduced_loss, grad_norm, learning_rate, duration, iteration)
if not is_overflow and (iteration % hparams.iters_per_checkpoint == 0):
validate(model, criterion, valset, iteration,
hparams.batch_size, n_gpus, collate_fn, logger,
hparams.distributed_run, rank)
if rank == 0:
checkpoint_path = os.path.join(
output_directory, "checkpoint_{}".format(iteration))
save_checkpoint(model, optimizer, learning_rate, iteration,
checkpoint_path)
iteration += 1
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output_directory', type=str,
help='directory to save checkpoints')
parser.add_argument('-l', '--log_directory', type=str,
help='directory to save tensorboard logs')
parser.add_argument('-c', '--checkpoint_path', type=str, default=None,
required=False, help='checkpoint path')
parser.add_argument('--warm_start', action='store_true',
help='load model weights only, ignore specified layers')
parser.add_argument('--n_gpus', type=int, default=1,
required=False, help='number of gpus')
parser.add_argument('--rank', type=int, default=0,
required=False, help='rank of current gpu')
parser.add_argument('--group_name', type=str, default='group_name',
required=False, help='Distributed group name')
parser.add_argument('--hparams', type=str,
required=False, help='comma separated name=value pairs')
args = parser.parse_args()
hparams = create_hparams(args.hparams)
torch.backends.cudnn.enabled = hparams.cudnn_enabled
torch.backends.cudnn.benchmark = hparams.cudnn_benchmark
print("FP16 Run:", hparams.fp16_run)
print("Dynamic Loss Scaling:", hparams.dynamic_loss_scaling)
print("Distributed Run:", hparams.distributed_run)
print("cuDNN Enabled:", hparams.cudnn_enabled)
print("cuDNN Benchmark:", hparams.cudnn_benchmark)
train(args.output_directory, args.log_directory, args.checkpoint_path,
args.warm_start, args.n_gpus, args.rank, args.group_name, hparams)
| tacotron2-master | train.py |
import torch
from librosa.filters import mel as librosa_mel_fn
from audio_processing import dynamic_range_compression
from audio_processing import dynamic_range_decompression
from stft import STFT
class LinearNorm(torch.nn.Module):
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
super(LinearNorm, self).__init__()
self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
torch.nn.init.xavier_uniform_(
self.linear_layer.weight,
gain=torch.nn.init.calculate_gain(w_init_gain))
def forward(self, x):
return self.linear_layer(x)
class ConvNorm(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
padding=None, dilation=1, bias=True, w_init_gain='linear'):
super(ConvNorm, self).__init__()
if padding is None:
assert(kernel_size % 2 == 1)
padding = int(dilation * (kernel_size - 1) / 2)
self.conv = torch.nn.Conv1d(in_channels, out_channels,
kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation,
bias=bias)
torch.nn.init.xavier_uniform_(
self.conv.weight, gain=torch.nn.init.calculate_gain(w_init_gain))
def forward(self, signal):
conv_signal = self.conv(signal)
return conv_signal
class TacotronSTFT(torch.nn.Module):
def __init__(self, filter_length=1024, hop_length=256, win_length=1024,
n_mel_channels=80, sampling_rate=22050, mel_fmin=0.0,
mel_fmax=8000.0):
super(TacotronSTFT, self).__init__()
self.n_mel_channels = n_mel_channels
self.sampling_rate = sampling_rate
self.stft_fn = STFT(filter_length, hop_length, win_length)
mel_basis = librosa_mel_fn(
sampling_rate, filter_length, n_mel_channels, mel_fmin, mel_fmax)
mel_basis = torch.from_numpy(mel_basis).float()
self.register_buffer('mel_basis', mel_basis)
def spectral_normalize(self, magnitudes):
output = dynamic_range_compression(magnitudes)
return output
def spectral_de_normalize(self, magnitudes):
output = dynamic_range_decompression(magnitudes)
return output
def mel_spectrogram(self, y):
"""Computes mel-spectrograms from a batch of waves
PARAMS
------
y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1]
RETURNS
-------
mel_output: torch.FloatTensor of shape (B, n_mel_channels, T)
"""
assert(torch.min(y.data) >= -1)
assert(torch.max(y.data) <= 1)
magnitudes, phases = self.stft_fn.transform(y)
magnitudes = magnitudes.data
mel_output = torch.matmul(self.mel_basis, magnitudes)
mel_output = self.spectral_normalize(mel_output)
return mel_output
| tacotron2-master | layers.py |
import time
import torch
import sys
import subprocess
argslist = list(sys.argv)[1:]
num_gpus = torch.cuda.device_count()
argslist.append('--n_gpus={}'.format(num_gpus))
workers = []
job_id = time.strftime("%Y_%m_%d-%H%M%S")
argslist.append("--group_name=group_{}".format(job_id))
for i in range(num_gpus):
argslist.append('--rank={}'.format(i))
stdout = None if i == 0 else open("logs/{}_GPU_{}.log".format(job_id, i),
"w")
print(argslist)
p = subprocess.Popen([str(sys.executable)]+argslist, stdout=stdout)
workers.append(p)
argslist = argslist[:-1]
for p in workers:
p.wait()
| tacotron2-master | multiproc.py |
import torch
class LossScaler:
def __init__(self, scale=1):
self.cur_scale = scale
# `params` is a list / generator of torch.Variable
def has_overflow(self, params):
return False
# `x` is a torch.Tensor
def _has_inf_or_nan(x):
return False
# `overflow` is boolean indicating whether we overflowed in gradient
def update_scale(self, overflow):
pass
@property
def loss_scale(self):
return self.cur_scale
def scale_gradient(self, module, grad_in, grad_out):
return tuple(self.loss_scale * g for g in grad_in)
def backward(self, loss):
scaled_loss = loss*self.loss_scale
scaled_loss.backward()
class DynamicLossScaler:
def __init__(self,
init_scale=2**32,
scale_factor=2.,
scale_window=1000):
self.cur_scale = init_scale
self.cur_iter = 0
self.last_overflow_iter = -1
self.scale_factor = scale_factor
self.scale_window = scale_window
# `params` is a list / generator of torch.Variable
def has_overflow(self, params):
# return False
for p in params:
if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data):
return True
return False
# `x` is a torch.Tensor
def _has_inf_or_nan(x):
cpu_sum = float(x.float().sum())
if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum:
return True
return False
# `overflow` is boolean indicating whether we overflowed in gradient
def update_scale(self, overflow):
if overflow:
#self.cur_scale /= self.scale_factor
self.cur_scale = max(self.cur_scale/self.scale_factor, 1)
self.last_overflow_iter = self.cur_iter
else:
if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0:
self.cur_scale *= self.scale_factor
# self.cur_scale = 1
self.cur_iter += 1
@property
def loss_scale(self):
return self.cur_scale
def scale_gradient(self, module, grad_in, grad_out):
return tuple(self.loss_scale * g for g in grad_in)
def backward(self, loss):
scaled_loss = loss*self.loss_scale
scaled_loss.backward()
##############################################################
# Example usage below here -- assuming it's in a separate file
##############################################################
if __name__ == "__main__":
import torch
from torch.autograd import Variable
from dynamic_loss_scaler import DynamicLossScaler
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random Tensors to hold inputs and outputs, and wrap them in Variables.
x = Variable(torch.randn(N, D_in), requires_grad=False)
y = Variable(torch.randn(N, D_out), requires_grad=False)
w1 = Variable(torch.randn(D_in, H), requires_grad=True)
w2 = Variable(torch.randn(H, D_out), requires_grad=True)
parameters = [w1, w2]
learning_rate = 1e-6
optimizer = torch.optim.SGD(parameters, lr=learning_rate)
loss_scaler = DynamicLossScaler()
for t in range(500):
y_pred = x.mm(w1).clamp(min=0).mm(w2)
loss = (y_pred - y).pow(2).sum() * loss_scaler.loss_scale
print('Iter {} loss scale: {}'.format(t, loss_scaler.loss_scale))
print('Iter {} scaled loss: {}'.format(t, loss.data[0]))
print('Iter {} unscaled loss: {}'.format(t, loss.data[0] / loss_scaler.loss_scale))
# Run backprop
optimizer.zero_grad()
loss.backward()
# Check for overflow
has_overflow = DynamicLossScaler.has_overflow(parameters)
# If no overflow, unscale grad and update as usual
if not has_overflow:
for param in parameters:
param.grad.data.mul_(1. / loss_scaler.loss_scale)
optimizer.step()
# Otherwise, don't do anything -- ie, skip iteration
else:
print('OVERFLOW!')
# Update loss scale for next iteration
loss_scaler.update_scale(has_overflow)
| tacotron2-master | loss_scaler.py |
""" from https://github.com/keithito/tacotron """
import re
valid_symbols = [
'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2',
'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2',
'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'ER2', 'EY',
'EY0', 'EY1', 'EY2', 'F', 'G', 'HH', 'IH', 'IH0', 'IH1', 'IH2', 'IY', 'IY0', 'IY1',
'IY2', 'JH', 'K', 'L', 'M', 'N', 'NG', 'OW', 'OW0', 'OW1', 'OW2', 'OY', 'OY0',
'OY1', 'OY2', 'P', 'R', 'S', 'SH', 'T', 'TH', 'UH', 'UH0', 'UH1', 'UH2', 'UW',
'UW0', 'UW1', 'UW2', 'V', 'W', 'Y', 'Z', 'ZH'
]
_valid_symbol_set = set(valid_symbols)
class CMUDict:
'''Thin wrapper around CMUDict data. http://www.speech.cs.cmu.edu/cgi-bin/cmudict'''
def __init__(self, file_or_path, keep_ambiguous=True):
if isinstance(file_or_path, str):
with open(file_or_path, encoding='latin-1') as f:
entries = _parse_cmudict(f)
else:
entries = _parse_cmudict(file_or_path)
if not keep_ambiguous:
entries = {word: pron for word, pron in entries.items() if len(pron) == 1}
self._entries = entries
def __len__(self):
return len(self._entries)
def lookup(self, word):
'''Returns list of ARPAbet pronunciations of the given word.'''
return self._entries.get(word.upper())
_alt_re = re.compile(r'\([0-9]+\)')
def _parse_cmudict(file):
cmudict = {}
for line in file:
if len(line) and (line[0] >= 'A' and line[0] <= 'Z' or line[0] == "'"):
parts = line.split(' ')
word = re.sub(_alt_re, '', parts[0])
pronunciation = _get_pronunciation(parts[1])
if pronunciation:
if word in cmudict:
cmudict[word].append(pronunciation)
else:
cmudict[word] = [pronunciation]
return cmudict
def _get_pronunciation(s):
parts = s.strip().split(' ')
for part in parts:
if part not in _valid_symbol_set:
return None
return ' '.join(parts)
| tacotron2-master | text/cmudict.py |
""" from https://github.com/keithito/tacotron """
import re
from text import cleaners
from text.symbols import symbols
# Mappings from symbol to numeric ID and vice versa:
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
# Regular expression matching text enclosed in curly braces:
_curly_re = re.compile(r'(.*?)\{(.+?)\}(.*)')
def text_to_sequence(text, cleaner_names):
'''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
The text can optionally have ARPAbet sequences enclosed in curly braces embedded
in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street."
Args:
text: string to convert to a sequence
cleaner_names: names of the cleaner functions to run the text through
Returns:
List of integers corresponding to the symbols in the text
'''
sequence = []
# Check for curly braces and treat their contents as ARPAbet:
while len(text):
m = _curly_re.match(text)
if not m:
sequence += _symbols_to_sequence(_clean_text(text, cleaner_names))
break
sequence += _symbols_to_sequence(_clean_text(m.group(1), cleaner_names))
sequence += _arpabet_to_sequence(m.group(2))
text = m.group(3)
return sequence
def sequence_to_text(sequence):
'''Converts a sequence of IDs back to a string'''
result = ''
for symbol_id in sequence:
if symbol_id in _id_to_symbol:
s = _id_to_symbol[symbol_id]
# Enclose ARPAbet back in curly braces:
if len(s) > 1 and s[0] == '@':
s = '{%s}' % s[1:]
result += s
return result.replace('}{', ' ')
def _clean_text(text, cleaner_names):
for name in cleaner_names:
cleaner = getattr(cleaners, name)
if not cleaner:
raise Exception('Unknown cleaner: %s' % name)
text = cleaner(text)
return text
def _symbols_to_sequence(symbols):
return [_symbol_to_id[s] for s in symbols if _should_keep_symbol(s)]
def _arpabet_to_sequence(text):
return _symbols_to_sequence(['@' + s for s in text.split()])
def _should_keep_symbol(s):
return s in _symbol_to_id and s is not '_' and s is not '~'
| tacotron2-master | text/__init__.py |
""" from https://github.com/keithito/tacotron """
import inflect
import re
_inflect = inflect.engine()
_comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])')
_decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)')
_pounds_re = re.compile(r'£([0-9\,]*[0-9]+)')
_dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)')
_ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)')
_number_re = re.compile(r'[0-9]+')
def _remove_commas(m):
return m.group(1).replace(',', '')
def _expand_decimal_point(m):
return m.group(1).replace('.', ' point ')
def _expand_dollars(m):
match = m.group(1)
parts = match.split('.')
if len(parts) > 2:
return match + ' dollars' # Unexpected format
dollars = int(parts[0]) if parts[0] else 0
cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
if dollars and cents:
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
cent_unit = 'cent' if cents == 1 else 'cents'
return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit)
elif dollars:
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
return '%s %s' % (dollars, dollar_unit)
elif cents:
cent_unit = 'cent' if cents == 1 else 'cents'
return '%s %s' % (cents, cent_unit)
else:
return 'zero dollars'
def _expand_ordinal(m):
return _inflect.number_to_words(m.group(0))
def _expand_number(m):
num = int(m.group(0))
if num > 1000 and num < 3000:
if num == 2000:
return 'two thousand'
elif num > 2000 and num < 2010:
return 'two thousand ' + _inflect.number_to_words(num % 100)
elif num % 100 == 0:
return _inflect.number_to_words(num // 100) + ' hundred'
else:
return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ')
else:
return _inflect.number_to_words(num, andword='')
def normalize_numbers(text):
text = re.sub(_comma_number_re, _remove_commas, text)
text = re.sub(_pounds_re, r'\1 pounds', text)
text = re.sub(_dollars_re, _expand_dollars, text)
text = re.sub(_decimal_number_re, _expand_decimal_point, text)
text = re.sub(_ordinal_re, _expand_ordinal, text)
text = re.sub(_number_re, _expand_number, text)
return text
| tacotron2-master | text/numbers.py |
""" from https://github.com/keithito/tacotron """
'''
Defines the set of symbols used in text input to the model.
The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. '''
from text import cmudict
_pad = '_'
_punctuation = '!\'(),.:;? '
_special = '-'
_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
# Prepend "@" to ARPAbet symbols to ensure uniqueness (some are the same as uppercase letters):
_arpabet = ['@' + s for s in cmudict.valid_symbols]
# Export all symbols:
symbols = [_pad] + list(_special) + list(_punctuation) + list(_letters) + _arpabet
| tacotron2-master | text/symbols.py |
""" from https://github.com/keithito/tacotron """
'''
Cleaners are transformations that run over the input text at both training and eval time.
Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
hyperparameter. Some cleaners are English-specific. You'll typically want to use:
1. "english_cleaners" for English text
2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
the Unidecode library (https://pypi.python.org/pypi/Unidecode)
3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
the symbols in symbols.py to match your data).
'''
import re
from unidecode import unidecode
from .numbers import normalize_numbers
# Regular expression matching whitespace:
_whitespace_re = re.compile(r'\s+')
# List of (regular expression, replacement) pairs for abbreviations:
_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
('mrs', 'misess'),
('mr', 'mister'),
('dr', 'doctor'),
('st', 'saint'),
('co', 'company'),
('jr', 'junior'),
('maj', 'major'),
('gen', 'general'),
('drs', 'doctors'),
('rev', 'reverend'),
('lt', 'lieutenant'),
('hon', 'honorable'),
('sgt', 'sergeant'),
('capt', 'captain'),
('esq', 'esquire'),
('ltd', 'limited'),
('col', 'colonel'),
('ft', 'fort'),
]]
def expand_abbreviations(text):
for regex, replacement in _abbreviations:
text = re.sub(regex, replacement, text)
return text
def expand_numbers(text):
return normalize_numbers(text)
def lowercase(text):
return text.lower()
def collapse_whitespace(text):
return re.sub(_whitespace_re, ' ', text)
def convert_to_ascii(text):
return unidecode(text)
def basic_cleaners(text):
'''Basic pipeline that lowercases and collapses whitespace without transliteration.'''
text = lowercase(text)
text = collapse_whitespace(text)
return text
def transliteration_cleaners(text):
'''Pipeline for non-English text that transliterates to ASCII.'''
text = convert_to_ascii(text)
text = lowercase(text)
text = collapse_whitespace(text)
return text
def english_cleaners(text):
'''Pipeline for English text, including number and abbreviation expansion.'''
text = convert_to_ascii(text)
text = lowercase(text)
text = expand_numbers(text)
text = expand_abbreviations(text)
text = collapse_whitespace(text)
return text
| tacotron2-master | text/cleaners.py |
import warp as wp
# this script generates a header that can be used to bind
# builtins e.g.: quat_inverse(), etc to Python through
# ctypes, this could allow calling all builtins
# from Python
wp.init()
f = open("warp/native/exports.h", "w")
wp.export_builtins(f)
f.close()
print("Finished")
| warp-main | build_exports.py |
import os
import sys
import subprocess
import warp as wp
wp.init()
# docs
# disable sphinx color output
os.environ["NO_COLOR"] = "1"
with open("docs/modules/functions.rst", "w") as function_ref:
wp.print_builtins(function_ref)
# run Sphinx build
try:
if os.name == 'nt':
subprocess.check_output("make.bat html", cwd="docs", shell=True)
else:
subprocess.run("make clean", cwd="docs", shell=True)
subprocess.check_output("make html", cwd="docs", shell=True)
except subprocess.CalledProcessError as e:
print(e.output.decode())
raise e
# generate stubs for autocomplete
stub_file = open("warp/stubs.py", "w")
wp.export_stubs(stub_file)
stub_file.close()
# code formatting
subprocess.run([sys.executable, "-m", "black", "warp/stubs.py"])
print("Finished")
| warp-main | build_docs.py |
import argparse
import os
import shutil
from typing import NamedTuple
import setuptools
from wheel.bdist_wheel import bdist_wheel
# Parse --build-option arguments meant for the bdist_wheel command. We have to parse these
# ourselves because when bdist_wheel runs it's too late to select a subset of libraries for package_data.
parser = argparse.ArgumentParser()
parser.add_argument("command")
parser.add_argument("--platform", "-P", type=str, default="", help="Wheel platform: windows|linux|macos")
args = parser.parse_known_args()[0]
class Platform(NamedTuple):
name: str
fancy_name: str
extension: str
tag: str
platforms = [
Platform("windows", "Windows", ".dll", "win_amd64"),
Platform("linux", "Linux", ".so", "manylinux2014_x86_64"),
Platform("macos", "macOS", ".dylib", "macosx_10_13_x86_64"),
]
# Determine supported platforms of warp/bin libraries based on their extension
def detect_warp_platforms():
detected_platforms = set()
for filename in os.listdir("warp/bin"):
for p in platforms:
if os.path.splitext(filename)[1] == p.extension:
detected_platforms.add(p)
if len(detected_platforms) == 0:
raise Exception("No libraries found in warp/bin. Please run build_lib.py first.")
return detected_platforms
detected_platforms = detect_warp_platforms()
wheel_platform = None # The one platform for which we're building a wheel
if args.command == "bdist_wheel":
if args.platform != "":
for p in platforms:
if args.platform == p.name or args.platform == p.fancy_name:
wheel_platform = p
print(f"Platform argument specified for building {p.fancy_name} wheel")
break
if wheel_platform is None:
print(f"Platform argument '{args.platform}' not recognized")
elif wheel_platform not in detected_platforms:
print(f"No libraries found for {wheel_platform.fancy_name}")
print(f"Falling back to auto-detection")
wheel_platform = None
if wheel_platform is None:
if len(detected_platforms) > 1:
print("Libraries for multiple platforms were detected. Picking the first one.")
print("Run `python -m build --wheel -C--build-option=-P[windows|linux|macos]` to select a specific one.")
wheel_platform = next(iter(detected_platforms))
print("Creating Warp wheel for " + wheel_platform.fancy_name)
# Binary wheel distribution builds assume that the platform you're building on will be the platform
# of the package. This class overrides the platform tag.
# https://packaging.python.org/en/latest/specifications/platform-compatibility-tags
class WarpBDistWheel(bdist_wheel):
# Even though we parse the platform argument ourselves, we need to declare it here as well so
# setuptools.Command can validate the command line options.
user_options = bdist_wheel.user_options + [
("platform=", "P", "Wheel platform: windows|linux|macos"),
]
def initialize_options(self):
super().initialize_options()
self.platform = ""
def get_tag(self):
# The wheel's complete tag format is {python tag}-{abi tag}-{platform tag}.
return "py3", "none", wheel_platform.tag
def run(self):
super().run()
# Clean up so we can re-invoke `py -m build --wheel -C--build-option=--platform=...`
# See https://github.com/pypa/setuptools/issues/1871 for details.
shutil.rmtree("./build", ignore_errors=True)
shutil.rmtree("./warp_lang.egg-info", ignore_errors=True)
# Distributions are identified as non-pure (i.e. containing non-Python code, or binaries) if the
# setuptools.setup() `ext_modules` parameter is not empty, but this assumes building extension
# modules from source through the Python build. This class provides an override for prebuilt binaries:
class BinaryDistribution(setuptools.Distribution):
def has_ext_modules(self):
return True
def get_warp_libraries(extension):
libraries = []
for filename in os.listdir("warp/bin"):
if os.path.splitext(filename)[1] == extension:
libraries.append("bin/" + filename)
return libraries
if wheel_platform is not None:
warp_binary_libraries = get_warp_libraries(wheel_platform.extension)
else:
warp_binary_libraries = [] # Not needed during egg_info command
setuptools.setup(
package_data={
"": [
"native/*.cpp",
"native/*.cu",
"native/*.h",
"native/clang/*.cpp",
"native/nanovdb/*.h",
"tests/assets/*",
]
+ warp_binary_libraries,
},
distclass=BinaryDistribution,
cmdclass={
"bdist_wheel": WarpBDistWheel,
},
)
| warp-main | setup.py |
import os
import subprocess
import sys
import warp
from warp.build_dll import build_dll_for_arch, run_cmd
# set build output path off this file
base_path = os.path.dirname(os.path.realpath(__file__))
build_path = os.path.join(base_path, "warp")
llvm_project_dir = "external/llvm-project"
llvm_project_path = os.path.join(base_path, llvm_project_dir)
llvm_path = os.path.join(llvm_project_path, "llvm")
llvm_build_path = os.path.join(llvm_project_path, "out/build/")
llvm_install_path = os.path.join(llvm_project_path, "out/install/")
# Fetch prebuilt Clang/LLVM libraries
if os.name == "nt":
packman = "tools\\packman\\packman.cmd"
packages = {"x86_64": "15.0.7-windows-x86_64-ptx-vs142"}
else:
packman = "./tools/packman/packman"
if sys.platform == "darwin":
packages = {
"arm64": "15.0.7-darwin-aarch64-macos11",
"x86_64": "15.0.7-darwin-x86_64-macos11",
}
else:
packages = {"x86_64": "15.0.7-linux-x86_64-ptx-gcc7.5-cxx11abi0"}
for arch in packages:
subprocess.check_call(
[
packman,
"install",
"-l",
f"./_build/host-deps/llvm-project/release-{arch}",
"clang+llvm-warp",
packages[arch],
]
)
def build_from_source_for_arch(args, arch):
# Install dependencies
subprocess.check_call([sys.executable, "-m", "pip", "install", "gitpython"])
subprocess.check_call([sys.executable, "-m", "pip", "install", "cmake"])
subprocess.check_call([sys.executable, "-m", "pip", "install", "ninja"])
from git import Repo
repo_url = "https://github.com/llvm/llvm-project.git"
if not os.path.exists(llvm_project_path):
print("Cloning LLVM project...")
shallow_clone = True # https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/
if shallow_clone:
repo = Repo.clone_from(
repo_url, to_path=llvm_project_path, single_branch=True, branch="llvmorg-15.0.7", depth=1
)
else:
repo = Repo.clone_from(repo_url, to_path=llvm_project_path)
repo.git.checkout("tags/llvmorg-15.0.7", "-b", "llvm-15.0.7")
else:
print(f"Found existing {llvm_project_dir} directory")
repo = Repo(llvm_project_path)
# CMake supports Debug, Release, RelWithDebInfo, and MinSizeRel builds
if warp.config.mode == "release":
# prefer smaller size over aggressive speed
cmake_build_type = "MinSizeRel"
else:
# When warp.config.mode == "debug" we build a Debug version of warp.dll but
# we generally don't want warp-clang.dll to be a slow Debug version.
if args.debug_llvm:
cmake_build_type = "Debug"
else:
# The GDB/LLDB debugger observes the __jit_debug_register_code symbol
# defined by the LLVM JIT, for which it needs debug info.
cmake_build_type = "RelWithDebInfo"
# Location of cmake and ninja installed through pip (see build.bat / build.sh)
python_bin = "python/Scripts" if sys.platform == "win32" else "python/bin"
os.environ["PATH"] = os.path.join(base_path, "_build/target-deps/" + python_bin) + os.pathsep + os.environ["PATH"]
if arch == "arm64":
target_backend = "AArch64"
else:
target_backend = "X86"
if sys.platform == "darwin":
host_triple = f"{arch}-apple-macos11"
elif os.name == "nt":
host_triple = f"{arch}-pc-windows"
else:
host_triple = f"{arch}-pc-linux"
build_path = os.path.join(llvm_build_path, f"{warp.config.mode}-{ arch}")
install_path = os.path.join(llvm_install_path, f"{warp.config.mode}-{ arch}")
# Build LLVM and Clang
cmake_gen = [
# fmt: off
"cmake",
"-S", llvm_path,
"-B", build_path,
"-G", "Ninja",
"-D", f"CMAKE_BUILD_TYPE={cmake_build_type}",
"-D", "LLVM_USE_CRT_RELEASE=MT",
"-D", "LLVM_USE_CRT_MINSIZEREL=MT",
"-D", "LLVM_USE_CRT_DEBUG=MTd",
"-D", "LLVM_USE_CRT_RELWITHDEBINFO=MTd",
"-D", f"LLVM_TARGETS_TO_BUILD={target_backend};NVPTX",
"-D", "LLVM_ENABLE_PROJECTS=clang",
"-D", "LLVM_ENABLE_ZLIB=FALSE",
"-D", "LLVM_ENABLE_ZSTD=FALSE",
"-D", "LLVM_ENABLE_TERMINFO=FALSE",
"-D", "LLVM_BUILD_LLVM_C_DYLIB=FALSE",
"-D", "LLVM_BUILD_RUNTIME=FALSE",
"-D", "LLVM_BUILD_RUNTIMES=FALSE",
"-D", "LLVM_BUILD_TOOLS=FALSE",
"-D", "LLVM_BUILD_UTILS=FALSE",
"-D", "LLVM_INCLUDE_BENCHMARKS=FALSE",
"-D", "LLVM_INCLUDE_DOCS=FALSE",
"-D", "LLVM_INCLUDE_EXAMPLES=FALSE",
"-D", "LLVM_INCLUDE_RUNTIMES=FALSE",
"-D", "LLVM_INCLUDE_TESTS=FALSE",
"-D", "LLVM_INCLUDE_TOOLS=TRUE", # Needed by Clang
"-D", "LLVM_INCLUDE_UTILS=FALSE",
"-D", "CMAKE_CXX_FLAGS=-D_GLIBCXX_USE_CXX11_ABI=0", # The pre-C++11 ABI is still the default on the CentOS 7 toolchain
"-D", f"CMAKE_INSTALL_PREFIX={install_path}",
"-D", f"LLVM_HOST_TRIPLE={host_triple}",
"-D", f"CMAKE_OSX_ARCHITECTURES={ arch}",
# Disable unused tools and features
"-D", "CLANG_BUILD_TOOLS=FALSE",
"-D", "LLVM_ENABLE_PLUGINS=FALSE",
"-D", "CLANG_PLUGIN_SUPPORT=FALSE",
"-D", "CLANG_ENABLE_ARCMT=FALSE",
"-D", "CLANG_ENABLE_STATIC_ANALYZER=FALSE",
"-D", "CLANG_TOOLING_BUILD_AST_INTROSPECTION=FALSE",
"-D", "CLANG_TOOL_AMDGPU_ARCH_BUILD=FALSE",
"-D", "CLANG_TOOL_APINOTES_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_ARCMT_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_CHECK_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_DIFF_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_EXTDEF_MAPPING_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_FORMAT_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_FORMAT_VS_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_FUZZER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_IMPORT_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_LINKER_WRAPPER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_NVLINK_WRAPPER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_OFFLOAD_BUNDLER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_OFFLOAD_PACKAGER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_OFFLOAD_WRAPPER_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_REFACTOR_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_RENAME_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_REPL_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_SCAN_DEPS_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_SHLIB_BUILD=FALSE",
"-D", "CLANG_TOOL_C_ARCMT_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_C_INDEX_TEST_BUILD=FALSE",
"-D", "CLANG_TOOL_DIAGTOOL_BUILD=FALSE",
"-D", "CLANG_TOOL_DRIVER_BUILD=FALSE",
"-D", "CLANG_TOOL_LIBCLANG_BUILD=FALSE",
"-D", "CLANG_TOOL_SCAN_BUILD_BUILD=FALSE",
"-D", "CLANG_TOOL_SCAN_BUILD_PY_BUILD=FALSE",
"-D", "CLANG_TOOL_CLANG_OFFLOAD_BUNDLER_BUILD=FALSE",
"-D", "CLANG_TOOL_SCAN_VIEW_BUILD=FALSE",
"-D", "LLVM_ENABLE_BINDINGS=FALSE",
"-D", "LLVM_ENABLE_OCAMLDOC=FALSE",
"-D", "LLVM_TOOL_BUGPOINT_BUILD=FALSE",
"-D", "LLVM_TOOL_BUGPOINT_PASSES_BUILD=FALSE",
"-D", "LLVM_TOOL_CLANG_BUILD=FALSE",
"-D", "LLVM_TOOL_DSYMUTIL_BUILD=FALSE",
"-D", "LLVM_TOOL_DXIL_DIS_BUILD=FALSE",
"-D", "LLVM_TOOL_GOLD_BUILD=FALSE",
"-D", "LLVM_TOOL_LLC_BUILD=FALSE",
"-D", "LLVM_TOOL_LLDB_BUILD=FALSE",
"-D", "LLVM_TOOL_LLI_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_AR_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_AS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_AS_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_BCANALYZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CAT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CFI_VERIFY_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CONFIG_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_COV_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CVTRES_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CXXDUMP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CXXFILT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_CXXMAP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_C_TEST_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DEBUGINFOD_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DEBUGINFOD_FIND_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DIFF_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DIS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DIS_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DLANG_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DWARFDUMP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DWARFUTIL_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_DWP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_EXEGESIS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_EXTRACT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_GO_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_GSYMUTIL_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_IFS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_ISEL_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_ITANIUM_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_JITLINK_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_JITLISTENER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LIBTOOL_DARWIN_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LINK_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LIPO_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LTO2_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_LTO_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MCA_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MC_ASSEMBLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MC_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MC_DISASSEMBLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MICROSOFT_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_ML_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MODEXTRACT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_MT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_NM_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_OBJCOPY_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_OBJDUMP_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_OPT_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_OPT_REPORT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_PDBUTIL_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_PROFDATA_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_PROFGEN_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_RC_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_READOBJ_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_REDUCE_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_REMARK_SIZE_DIFF_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_RTDYLD_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_RUST_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SHLIB_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SIM_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SIZE_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SPECIAL_CASE_LIST_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SPLIT_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_STRESS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_STRINGS_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_SYMBOLIZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_TAPI_DIFF_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_TLI_CHECKER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_UNDNAME_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_XRAY_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_YAML_NUMERIC_PARSER_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LLVM_YAML_PARSER_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_LTO_BUILD=FALSE",
"-D", "LLVM_TOOL_OBJ2YAML_BUILD=FALSE",
"-D", "LLVM_TOOL_OPT_BUILD=FALSE",
"-D", "LLVM_TOOL_OPT_VIEWER_BUILD=FALSE",
"-D", "LLVM_TOOL_REMARKS_SHLIB_BUILD=FALSE",
"-D", "LLVM_TOOL_SANCOV_BUILD=FALSE",
"-D", "LLVM_TOOL_SANSTATS_BUILD=FALSE",
"-D", "LLVM_TOOL_SPLIT_FILE_BUILD=FALSE",
"-D", "LLVM_TOOL_VERIFY_USELISTORDER_BUILD=FALSE",
"-D", "LLVM_TOOL_VFABI_DEMANGLE_FUZZER_BUILD=FALSE",
"-D", "LLVM_TOOL_XCODE_TOOLCHAIN_BUILD=FALSE",
"-D", "LLVM_TOOL_YAML2OBJ_BUILD=FALSE",
# fmt: on
]
subprocess.check_call(cmake_gen, stderr=subprocess.STDOUT)
cmake_build = ["cmake", "--build", build_path]
subprocess.check_call(cmake_build, stderr=subprocess.STDOUT)
cmake_install = ["cmake", "--install", build_path]
subprocess.check_call(cmake_install, stderr=subprocess.STDOUT)
def build_from_source(args):
build_from_source_for_arch(args, "x86_64")
if sys.platform == "darwin":
build_from_source_for_arch(args, "arm64")
# build warp-clang.dll
def build_warp_clang_for_arch(args, lib_name, arch):
try:
cpp_sources = [
"native/clang/clang.cpp",
"native/crt.cpp",
]
clang_cpp_paths = [os.path.join(build_path, cpp) for cpp in cpp_sources]
clang_dll_path = os.path.join(build_path, f"bin/{lib_name}")
if args.build_llvm:
# obtain Clang and LLVM libraries from the local build
install_path = os.path.join(llvm_install_path, f"{warp.config.mode}-{arch}")
libpath = os.path.join(install_path, "lib")
else:
# obtain Clang and LLVM libraries from packman
assert os.path.exists("_build/host-deps/llvm-project"), "run build.bat / build.sh"
libpath = os.path.join(base_path, f"_build/host-deps/llvm-project/release-{arch}/lib")
for _, _, libs in os.walk(libpath):
break # just the top level contains library files
if os.name == "nt":
libs.append("Version.lib")
libs.append(f'/LIBPATH:"{libpath}"')
else:
libs = [f"-l{lib[3:-2]}" for lib in libs if os.path.splitext(lib)[1] == ".a"]
if sys.platform == "darwin":
libs += libs # prevents unresolved symbols due to link order
else:
libs.insert(0, "-Wl,--start-group")
libs.append("-Wl,--end-group")
libs.append(f"-L{libpath}")
libs.append("-lpthread")
libs.append("-ldl")
build_dll_for_arch(
dll_path=clang_dll_path,
cpp_paths=clang_cpp_paths,
cu_path=None,
libs=libs,
mode=warp.config.mode if args.build_llvm else "release",
arch=arch,
verify_fp=warp.config.verify_fp,
fast_math=warp.config.fast_math,
)
except Exception as e:
# output build error
print(f"Warp Clang/LLVM build error: {e}")
# report error
sys.exit(1)
def build_warp_clang(args, lib_name):
if sys.platform == "darwin":
# create a universal binary by combining x86-64 and AArch64 builds
build_warp_clang_for_arch(args, lib_name + "-x86_64", "x86_64")
build_warp_clang_for_arch(args, lib_name + "-arm64", "arm64")
dylib_path = os.path.join(build_path, f"bin/{lib_name}")
run_cmd(f"lipo -create -output {dylib_path} {dylib_path}-x86_64 {dylib_path}-arm64")
os.remove(f"{dylib_path}-x86_64")
os.remove(f"{dylib_path}-arm64")
else:
build_warp_clang_for_arch(args, lib_name, "x86_64")
| warp-main | build_llvm.py |
# This script is an 'offline' build of the core warp runtime libraries
# designed to be executed as part of CI / developer workflows, not
# as part of the user runtime (since it requires CUDA toolkit, etc)
import sys
if sys.version_info[0] < 3:
raise Exception("Warp requires Python 3.x minimum")
import argparse
import os
import warp.config
from warp.build_dll import build_dll, find_host_compiler, set_msvc_compiler
parser = argparse.ArgumentParser(description="Warp build script")
parser.add_argument("--msvc_path", type=str, help="Path to MSVC compiler (optional if already on PATH)")
parser.add_argument("--sdk_path", type=str, help="Path to WinSDK (optional if already on PATH)")
parser.add_argument("--cuda_path", type=str, help="Path to CUDA SDK")
parser.add_argument(
"--mode",
type=str,
default="release",
help="Build configuration, default 'release'",
choices=["release", "debug"],
)
# Note argparse.BooleanOptionalAction can be used here when Python 3.9+ becomes the minimum supported version
parser.add_argument("--verbose", action="store_true", help="Verbose building output, default enabled")
parser.add_argument("--no_verbose", dest="verbose", action="store_false")
parser.set_defaults(verbose=True)
parser.add_argument(
"--verify_fp",
action="store_true",
help="Verify kernel inputs and outputs are finite after each launch, default disabled",
)
parser.add_argument("--no_verify_fp", dest="verify_fp", action="store_false")
parser.set_defaults(verify_fp=False)
parser.add_argument("--fast_math", action="store_true", help="Enable fast math on library, default disabled")
parser.add_argument("--no_fast_math", dest="fast_math", action="store_false")
parser.set_defaults(fast_math=False)
parser.add_argument("--quick", action="store_true", help="Only generate PTX code, disable CUTLASS ops")
parser.add_argument("--build_llvm", action="store_true", help="Build Clang/LLVM compiler from source, default disabled")
parser.add_argument("--no_build_llvm", dest="build_llvm", action="store_false")
parser.set_defaults(build_llvm=False)
parser.add_argument("--debug_llvm", action="store_true", help="Enable LLVM compiler code debugging, default disabled")
parser.add_argument("--no_debug_llvm", dest="debug_llvm", action="store_false")
parser.set_defaults(debug_llvm=False)
parser.add_argument("--standalone", action="store_true", help="Use standalone LLVM-based JIT compiler, default enabled")
parser.add_argument("--no_standalone", dest="standalone", action="store_false")
parser.set_defaults(standalone=True)
args = parser.parse_args()
# set build output path off this file
base_path = os.path.dirname(os.path.realpath(__file__))
build_path = os.path.join(base_path, "warp")
print(args)
warp.config.verbose = args.verbose
warp.config.mode = args.mode
warp.config.verify_fp = args.verify_fp
warp.config.fast_math = args.fast_math
# See PyTorch for reference on how to find nvcc.exe more robustly
# https://pytorch.org/docs/stable/_modules/torch/utils/cpp_extension.html#CppExtension
def find_cuda():
# Guess #1
cuda_home = os.environ.get("CUDA_HOME") or os.environ.get("CUDA_PATH")
return cuda_home
# setup CUDA paths
if sys.platform == "darwin":
warp.config.cuda_path = None
else:
if args.cuda_path:
warp.config.cuda_path = args.cuda_path
else:
warp.config.cuda_path = find_cuda()
# setup MSVC and WinSDK paths
if os.name == "nt":
if args.sdk_path and args.msvc_path:
# user provided MSVC
set_msvc_compiler(msvc_path=args.msvc_path, sdk_path=args.sdk_path)
else:
# attempt to find MSVC in environment (will set vcvars)
warp.config.host_compiler = find_host_compiler()
if not warp.config.host_compiler:
print("Warp build error: Could not find MSVC compiler")
sys.exit(1)
# return platform specific shared library name
def lib_name(name):
if sys.platform == "win32":
return f"{name}.dll"
elif sys.platform == "darwin":
return f"lib{name}.dylib"
else:
return f"{name}.so"
try:
# build warp.dll
cpp_sources = [
"native/warp.cpp",
"native/crt.cpp",
"native/cuda_util.cpp",
"native/mesh.cpp",
"native/hashgrid.cpp",
"native/reduce.cpp",
"native/runlength_encode.cpp",
"native/sort.cpp",
"native/sparse.cpp",
"native/volume.cpp",
"native/marching.cpp",
"native/cutlass_gemm.cpp",
]
warp_cpp_paths = [os.path.join(build_path, cpp) for cpp in cpp_sources]
if warp.config.cuda_path is None:
print("Warning: CUDA toolchain not found, building without CUDA support")
warp_cu_path = None
else:
warp_cu_path = os.path.join(build_path, "native/warp.cu")
warp_dll_path = os.path.join(build_path, f"bin/{lib_name('warp')}")
build_dll(
dll_path=warp_dll_path,
cpp_paths=warp_cpp_paths,
cu_path=warp_cu_path,
mode=warp.config.mode,
verify_fp=warp.config.verify_fp,
fast_math=args.fast_math,
quick=args.quick,
)
# build warp-clang.dll
if args.standalone:
import build_llvm
if args.build_llvm:
build_llvm.build_from_source(args)
build_llvm.build_warp_clang(args, lib_name("warp-clang"))
except Exception as e:
# output build error
print(f"Warp build error: {e}")
# report error
sys.exit(1)
| warp-main | build_lib.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Public Python API exposed by the omni.warp.nodes package."""
__all__ = [
"AttrTracking",
"NodeTimer",
"basis_curves_copy_bundle",
"basis_curves_create_bundle",
"basis_curves_get_curve_count",
"basis_curves_get_curve_vertex_counts",
"basis_curves_get_display_color",
"basis_curves_get_local_extent",
"basis_curves_get_point_count",
"basis_curves_get_points",
"basis_curves_get_widths",
"basis_curves_get_world_extent",
"bundle_get_attr",
"bundle_get_child_count",
"bundle_get_prim_type",
"bundle_get_world_xform",
"bundle_has_changed",
"bundle_have_attrs_changed",
"bundle_set_prim_type",
"bundle_set_world_xform",
"from_omni_graph",
"mesh_create_bundle",
"mesh_copy_bundle",
"mesh_get_display_color",
"mesh_get_face_count",
"mesh_get_face_vertex_counts",
"mesh_get_face_vertex_indices",
"mesh_get_local_extent",
"mesh_get_normals",
"mesh_get_point_count",
"mesh_get_points",
"mesh_triangulate",
"mesh_get_uvs",
"mesh_get_velocities",
"mesh_get_vertex_count",
"mesh_get_world_extent",
"points_create_bundle",
"points_copy_bundle",
"points_get_display_color",
"points_get_local_extent",
"points_get_masses",
"points_get_point_count",
"points_get_points",
"points_get_velocities",
"points_get_widths",
"points_get_world_extent",
"type_convert_og_to_warp",
"type_convert_sdf_name_to_warp",
"type_convert_sdf_name_to_og",
]
from omni.warp.nodes._impl.attributes import (
AttrTracking,
from_omni_graph,
)
from omni.warp.nodes._impl.bundles import (
bundle_get_attr,
bundle_get_child_count,
bundle_get_prim_type,
bundle_get_world_xform,
bundle_has_changed,
bundle_have_attrs_changed,
)
from omni.warp.nodes._impl.common import (
NodeTimer,
type_convert_og_to_warp,
type_convert_sdf_name_to_warp,
type_convert_sdf_name_to_og,
)
from omni.warp.nodes._impl.basis_curves import (
basis_curves_copy_bundle,
basis_curves_create_bundle,
basis_curves_get_curve_count,
basis_curves_get_curve_vertex_counts,
basis_curves_get_display_color,
basis_curves_get_local_extent,
basis_curves_get_point_count,
basis_curves_get_points,
basis_curves_get_widths,
basis_curves_get_world_extent,
)
from omni.warp.nodes._impl.mesh import (
mesh_create_bundle,
mesh_copy_bundle,
mesh_get_display_color,
mesh_get_face_count,
mesh_get_face_vertex_counts,
mesh_get_face_vertex_indices,
mesh_get_local_extent,
mesh_get_normals,
mesh_get_point_count,
mesh_get_points,
mesh_triangulate,
mesh_get_uvs,
mesh_get_velocities,
mesh_get_vertex_count,
mesh_get_world_extent,
)
from omni.warp.nodes._impl.points import (
points_create_bundle,
points_copy_bundle,
points_get_display_color,
points_get_local_extent,
points_get_masses,
points_get_point_count,
points_get_points,
points_get_velocities,
points_get_widths,
points_get_world_extent,
)
| warp-main | exts/omni.warp/omni/warp/nodes/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node retrieving a time with a fixed time step."""
import omni.timeline
class OgnFixedTimeState:
def __init__(self):
self.time = 0.0
self.initialized = False
class OgnFixedTime:
"""Node."""
@staticmethod
def internal_state():
return OgnFixedTimeState()
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
timeline = omni.timeline.get_timeline_interface()
context = db.internal_state
if context.initialized == False:
context.time = db.inputs.start
context.initialized = True
db.outputs.time = context.time
if timeline.is_playing():
context.time += 1.0 / db.inputs.fps
return True
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnFixedTime.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Sample node that simulates flocking behaviors by animating prim attributes."""
import math
import traceback
import numpy as np
import carb.settings
import omni.kit.app
import omni.graph.core as og
import omni.usd
import usdrt
import warp as wp
import omni.warp.nodes
from omni.warp.nodes.ogn.OgnSamplePrimFlockingDatabase import OgnSamplePrimFlockingDatabase
# device used for flocking simulation
MAIN_DEVICE = "cuda:0"
# device used for updating colors
COLOR_DEVICE = "cpu"
# Kernels
# -----------------------------------------------------------------------------
@wp.struct
class Boid:
vel: wp.vec3f
wander_angles: wp.vec2f
mass: float
group: int
@wp.struct
class Obstacle:
pos: wp.vec3f
radius: float
@wp.struct
class World:
lower: wp.vec3f
upper: wp.vec3f
grid: wp.uint64
seed: int
biases: wp.mat33f
obstacles: wp.array(dtype=Obstacle)
@wp.kernel(enable_backward=False)
def copy_positions(dst: wp.array(dtype=wp.vec3f), src: wp.fabricarray(dtype=wp.vec3d)):
tid = wp.tid()
pos = src[tid]
dst[tid] = wp.vec3f(float(pos[0]), float(pos[1]), float(pos[2]))
@wp.kernel(enable_backward=False)
def assign_colors(
glows: wp.array(dtype=float),
groups: wp.array(dtype=int),
color_ramps: wp.array2d(dtype=wp.vec3f),
colors: wp.fabricarrayarray(dtype=wp.vec3f)
):
tid = wp.tid()
glow = glows[tid]
group = groups[tid]
if glow < 0.4:
alpha = glow / 0.4
colors[tid][0] = (1.0 - alpha) * color_ramps[group, 0] + alpha * color_ramps[group, 1]
elif glow < 0.8:
alpha = (glow - 0.4) / 0.4
colors[tid][0] = (1.0 - alpha) * color_ramps[group, 1] + alpha * color_ramps[group, 2]
else:
alpha = (glow - 0.8) / 0.2
colors[tid][0] = (1.0 - alpha) * color_ramps[group, 2] + alpha * color_ramps[group, 3]
@wp.func
def intersect_ray_sphere(origin: wp.vec3f, dir: wp.vec3f, center: wp.vec3f, radius: float):
to_sphere = center - origin
tc = wp.dot(to_sphere, dir)
if tc < 0.0:
return tc
d = wp.sqrt(wp.length_sq(to_sphere) - tc * tc)
if d < 0.0:
return -999999.0
ts = wp.sqrt(radius * radius - d * d)
return tc - ts
@wp.kernel(enable_backward=False)
def boids(
boids: wp.array(dtype=Boid),
world: World,
dt: float,
positions: wp.fabricarray(dtype=wp.vec3d),
orientations: wp.fabricarray(dtype=wp.quatf),
glows: wp.array(dtype=float),
):
tid = wp.tid()
boid = boids[tid]
old_pos = positions[tid]
old_rot = orientations[tid]
pos = wp.vec3(float(old_pos[0]), float(old_pos[1]), float(old_pos[2]))
vel = boid.vel
forward = wp.quat_rotate(old_rot, wp.vec3f(1.0, 0.0, 0.0))
force = wp.vec3f(0.0)
# obstacle avoidance
depenetration_force = 100.0
avoidance_dist = 20.0
avoidance_force = 20.0
obstacles = world.obstacles
num_obstacles = obstacles.shape[0]
for i in range(num_obstacles):
obstacle = obstacles[i]
to_obstacle = obstacle.pos - pos
# use padded radius
radius = obstacle.radius + 2.0
if wp.length(to_obstacle) < radius:
# depenetration
force += depenetration_force * wp.normalize(-to_obstacle)
else:
# avoidance
t = intersect_ray_sphere(pos, forward, obstacle.pos, radius)
if t > 0.0 and t < avoidance_dist:
intersection_point = pos + t * forward
out = intersection_point - obstacle.pos
force += avoidance_force * (1.0 - t / avoidance_dist) * wp.normalize(out)
# wander
r = 10.0
s0 = wp.sin(boid.wander_angles[0])
c0 = wp.cos(boid.wander_angles[0])
s1 = wp.sin(boid.wander_angles[1])
c1 = wp.cos(boid.wander_angles[1])
p = wp.vec3f(r * s0 * s1, r * s0 * c1, r * c0)
offset = r + 1.0
target = pos + wp.quat_rotate(old_rot, wp.vec3f(offset, 0.0, 0.0) + p)
wander_force = 7.0
force += wander_force * wp.normalize(target - pos)
state = wp.rand_init(world.seed, tid)
angle0 = boid.wander_angles[0] + wp.pi * (0.1 - 0.2 * wp.randf(state))
angle1 = boid.wander_angles[1] + wp.pi * (0.1 - 0.2 * wp.randf(state))
boid.wander_angles = wp.vec2f(angle0, angle1)
cohesion_radius = 15.0
cohesion_force = 20.0
separation_radius = 10.0
separation_force = 100.0
# flocking
query = wp.hash_grid_query(world.grid, pos, cohesion_radius)
num_neighbors = int(0)
num_align_neighbors = int(0)
num_cohesion_neighbors = float(0)
num_decohesion_neighbors = float(0)
cohesion_pos_sum = wp.vec3f(0.0)
decohesion_pos_sum = wp.vec3f(0.0)
vel_sum = wp.vec3f(0.0)
for index in query:
if index != tid:
other = boids[index]
other_pos64 = positions[index]
other_pos = wp.vec3f(float(other_pos64[0]), float(other_pos64[1]), float(other_pos64[2]))
dist = wp.length(pos - other_pos)
if dist < cohesion_radius:
to_other = wp.normalize(other_pos - pos)
# separation
if dist < separation_radius:
force -= separation_force * (1.0 - dist / separation_radius) * to_other
# cohesion
bias = world.biases[boid.group, other.group]
if bias > 0.0:
cohesion_pos_sum += bias * other_pos
num_cohesion_neighbors += bias
else:
decohesion_pos_sum -= bias * other_pos
num_decohesion_neighbors -= bias
# alignment
if other.group == boid.group:
vel_sum += bias * other.vel
num_align_neighbors += 1
num_neighbors += 1
# align
if num_align_neighbors > 0:
vel_avg = vel_sum / float(num_align_neighbors)
force += vel_avg - vel
# cohere
if num_cohesion_neighbors > 0.0:
cohesion_pos_avg = cohesion_pos_sum / float(num_cohesion_neighbors)
force += cohesion_force * wp.normalize(cohesion_pos_avg - pos)
# decohere (group separation)
if num_decohesion_neighbors > 0.0:
decohesion_pos_avg = decohesion_pos_sum / float(num_decohesion_neighbors)
force += cohesion_force * wp.normalize(pos - decohesion_pos_avg)
# boundaries
boundary_force = 20.0
if pos[0] >= world.upper[0]:
force += wp.vec3f(-boundary_force, 0.0, 0.0)
if pos[0] <= world.lower[0]:
force += wp.vec3f(boundary_force, 0.0, 0.0)
if pos[1] >= world.upper[1]:
force += wp.vec3f(0.0, -0.5 * boundary_force, 0.0)
if pos[1] <= world.lower[1]:
force += wp.vec3f(0.0, 5.0 * boundary_force, 0.0)
if pos[2] >= world.upper[2]:
force += wp.vec3f(0.0, 0.0, -boundary_force)
if pos[2] <= world.lower[2]:
force += wp.vec3f(0.0, 0.0, boundary_force)
vel += dt * force / boid.mass
# clamp speed
max_speed = 15.0
speed_sq = wp.length_sq(vel)
if speed_sq > max_speed * max_speed:
vel = max_speed * wp.normalize(vel)
# update position
pos += dt * vel
positions[tid] = wp.vec3d(wp.float64(pos[0]), wp.float64(pos[1]), wp.float64(pos[2]))
# update orientation
dq = wp.quat_between_vectors(forward, vel)
orientations[tid] = wp.normalize(dq * orientations[tid])
# save velocity
boid.vel = vel
boids[tid] = boid
# update glow as an exponentially weighted moving average to keep it smooth
glow = wp.min(1.0, float(num_neighbors) / 25.0)
glow_alpha = 0.25
glows[tid] = glow_alpha * glow + (1.0 - glow_alpha) * glows[tid]
# Internal State
# ------------------------------------------------------------------------------
class InternalState:
"""Internal state for the node."""
def __init__(self) -> None:
self.initialized = False
def initialize(self, device):
# requirement checks
ext_mgr = omni.kit.app.get_app().get_extension_manager()
# make sure USDRT is enabled
usdrt_ext_name = "usdrt.scenegraph"
if not ext_mgr.is_extension_enabled(usdrt_ext_name):
raise RuntimeError(f"This sample requires the '{usdrt_ext_name}' extension to be enabled")
# check USDRT version to make sure we have a working SelectPrims()
usdrt_ext_id = ext_mgr.get_enabled_extension_id(usdrt_ext_name)
usdrt_version_string = ext_mgr.get_extension_dict(usdrt_ext_id)["package"]["version"]
usdrt_version = tuple(int(v) for v in usdrt_version_string.split("."))
if usdrt_version < (7, 3, 0):
raise RuntimeError(f"USDRT version 7.3.0 is required, found {usdrt_version_string}. Please update to a newer version of Kit to run this sample.")
# check if FSD is enabled
settings = carb.settings.get_settings()
is_fsd_enabled = settings.get_as_bool("/app/useFabricSceneDelegate")
if not is_fsd_enabled:
print("***")
print("*** Flocking demo warning: The Fabric Scene Delegate is not enabled.")
print("*** Some features, like color animation, may not work.")
print("*** You can enable FSD in Preferences->Rendering.")
print("***")
stage_id = omni.usd.get_context().get_stage_id()
usdrt_stage = usdrt.Usd.Stage.Attach(stage_id)
# import to Fabric
for prim in usdrt_stage.Traverse():
pass
# set up for Fabric interop
boid_root = usdrt_stage.GetPrimAtPath(usdrt.Sdf.Path("/World/Boids"))
boid_prims = boid_root.GetChildren()
for prim in boid_prims:
pos = prim.GetAttribute("xformOp:translate").Get()
prim.CreateAttribute("_worldPosition", usdrt.Sdf.ValueTypeNames.Double3, True).Set(pos)
prim.CreateAttribute("_worldOrientation", usdrt.Sdf.ValueTypeNames.Quatf, True).Set(usdrt.Gf.Quatf(1, 0, 0, 0))
# create a custom tag for the boids (could use applied schema too)
prim.CreateAttribute("BoidTag", usdrt.Sdf.ValueTypeNames.AppliedSchemaTypeTag, True)
num_boids = len(boid_prims)
self.stage = usdrt_stage
self.require_schemas = ["BoidTag"]
self.transform_attrs = [
(usdrt.Sdf.ValueTypeNames.Double3, "_worldPosition", usdrt.Usd.Access.ReadWrite),
(usdrt.Sdf.ValueTypeNames.Quatf, "_worldOrientation", usdrt.Usd.Access.ReadWrite),
]
self.color_attrs = [
(usdrt.Sdf.ValueTypeNames.Float3Array, "primvars:_emissive", usdrt.Usd.Access.ReadWrite),
]
npboids = np.zeros(num_boids, dtype=Boid.numpy_dtype())
angles = math.pi - 2 * math.pi * np.random.rand(num_boids)
vx = 20 * np.sin(angles)
vz = 20 * np.cos(angles)
npboids["vel"][:, 0] = vx
npboids["vel"][:, 2] = vz
npboids["wander_angles"][:, 0] = math.pi * np.random.rand(num_boids)
npboids["wander_angles"][:, 1] = 2 * math.pi * np.random.rand(num_boids)
min_mass = 1.0
max_mass = 2.0
npboids["mass"][:] = min_mass + (max_mass - min_mass) * np.random.rand(num_boids)
# we can have up to 3 groups currently, but that can be easily extended
self.num_groups = 2
npboids["group"] = np.random.randint(self.num_groups, size=num_boids)
num_obstacles = 3
npobstacles = np.zeros(num_obstacles, dtype=Obstacle.numpy_dtype())
npobstacles["pos"][0] = (-20, 30, -40)
npobstacles["radius"][0] = 40
npobstacles["pos"][1] = (90, 30, 30)
npobstacles["radius"][1] = 30
npobstacles["pos"][2] = (-100, 30, 60)
npobstacles["radius"][2] = 25
self.grid = wp.HashGrid(dim_x=32, dim_y=32, dim_z=32, device=device)
biases = wp.mat33f(-1.0)
for i in range(self.num_groups):
biases[i, i] = 1.0
world = World()
world.lower = (-120, 20, -90)
world.upper = (120, 40, 90)
world.grid = self.grid.id
world.seed = 0
world.biases = biases
world.obstacles = wp.array(npobstacles, dtype=Obstacle, device=device)
self.world = world
self.num_boids = num_boids
self.boids = wp.array(npboids, dtype=Boid, device=device)
# color ramps per group
color_ramps = [
[[0.3, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.5, 0.0], [1.0, 1.0, 0.5]],
[[0.0, 0.0, 0.3], [0.0, 0.0, 1.0], [0.0, 0.5, 1.0], [0.5, 1.0, 1.0]],
[[0.0, 0.3, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.5], [0.8, 1.0, 0.8]],
]
# copy of positions used for updating the spatial grid
self.positions = wp.zeros(num_boids, dtype=wp.vec3f, device=device)
# color ramps are only used on the COLOR_DEVICE
self.color_ramps_c = wp.array(color_ramps, dtype=wp.vec3f, device=COLOR_DEVICE)
# keep a copy of group assignments on the COLOR_DEVICE
self.groups_c = wp.array(npboids["group"], device=COLOR_DEVICE)
# if we use different devices, the glow array must be copied on each update
if COLOR_DEVICE == device:
# use the same glow array on each device, no copying needed
self.glows_c = wp.zeros(num_boids, dtype=float, device=device)
self.glows_m = self.glows_c
elif COLOR_DEVICE == "cpu" or device == "cpu":
# use a pinned host array for async copying glows between devices
glows_h = wp.zeros(num_boids, dtype=float, device="cpu", pinned=True)
if COLOR_DEVICE == "cpu":
self.glows_c = glows_h
self.glows_m = wp.zeros_like(glows_h, device=device)
else:
self.glows_c = wp.zeros_like(glows_h, device=COLOR_DEVICE)
self.glows_m = glows_h
else:
# two different CUDA devices
self.glows_c = wp.zeros(num_boids, dtype=float, device=COLOR_DEVICE)
self.glows_m = wp.zeros(num_boids, dtype=float, device=device)
# ...but that's currently not supported in Kit
raise ValueError("Multiple GPUs not supported yet")
self.time = 0.0
self.min_group_think = 3.0
self.max_group_think = 10.0
self.next_group_think = self.min_group_think + (self.max_group_think - self.min_group_think) * np.random.rand()
self.frameno = 0
self.initialized = True
# Compute
# ------------------------------------------------------------------------------
def compute(db: OgnSamplePrimFlockingDatabase) -> None:
"""Evaluates the node."""
state = db.internal_state
device = wp.get_device()
if not state.initialized:
state.initialize(device)
state.frameno += 1
# get transform attributes
selection = state.stage.SelectPrims(
require_applied_schemas=state.require_schemas,
require_attrs=state.transform_attrs,
device=str(device)
)
fpos = wp.fabricarray(data=selection, attrib="_worldPosition")
frot = wp.fabricarray(data=selection, attrib="_worldOrientation")
# use fixed dt for stability
dt = 1.0 / 60.0
state.time += dt
# copy positions to a contiguous array and convert to vec3f so they can be used to update the spatial grid
wp.launch(copy_positions, dim=state.num_boids, inputs=[state.positions, fpos])
# grid cell radius should be a bit bigger than query radius
cell_radius = 20.0
state.grid.build(state.positions, cell_radius)
state.world.seed = state.frameno
# step the flocking simulation
wp.launch(boids, dim=state.num_boids, inputs=[state.boids, state.world, dt, fpos, frot, state.glows_m])
# async copy from main device and remember the stream so we can sync later
if COLOR_DEVICE != device:
if device.is_cuda:
work_stream = device.stream
else:
work_stream = wp.get_stream(COLOR_DEVICE)
wp.copy(state.glows_c, state.glows_m, stream=work_stream)
else:
work_stream = None
# get color attributes
color_selection = state.stage.SelectPrims(
require_applied_schemas=state.require_schemas,
require_attrs=state.color_attrs,
device=COLOR_DEVICE
)
fcolor = wp.fabricarray(data=color_selection, attrib="primvars:_emissive")
# occasionally update group biases (whether they are attracted or repelled from each other)
if state.num_groups > 1 and state.time >= state.next_group_think:
# pick two random groups
group0 = np.random.randint(state.num_groups)
group1 = np.random.randint(state.num_groups)
while group0 == group1:
group1 = np.random.randint(state.num_groups)
# bias towards intra-group separation, but also allow attraction
state.world.biases[group0, group1] = 1.0 - 5.0 * np.random.rand()
state.world.biases[group1, group0] = 1.0 - 5.0 * np.random.rand()
state.next_group_think += state.min_group_think + (state.max_group_think - state.min_group_think) * np.random.rand()
if work_stream is not None:
# wait for async GPU work to complete
wp.synchronize_stream(work_stream)
# update colors
wp.launch(assign_colors, dim=state.num_boids, inputs=[state.glows_c, state.groups_c, state.color_ramps_c, fcolor], device=COLOR_DEVICE)
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnSamplePrimFlocking:
"""Node."""
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db: OgnSamplePrimFlockingDatabase) -> None:
device = wp.get_device(MAIN_DEVICE)
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.log_error(traceback.format_exc())
return
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnSamplePrimFlocking.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Warp kernel exposed as an OmniGraph node."""
import traceback
from typing import Tuple
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
import omni.timeline
import warp as wp
from omni.warp.nodes._impl.kernel import (
EXPLICIT_SOURCE,
InternalStateBase,
UserAttributesEvent,
deserialize_user_attribute_descs,
gather_attribute_infos,
get_kernel_args,
initialize_kernel_module,
validate_input_arrays,
write_output_attrs,
)
from omni.warp.nodes._impl.attributes import attr_join_name
from omni.warp.nodes.ogn.OgnKernelDatabase import OgnKernelDatabase
QUIET_DEFAULT = wp.config.quiet
ATTR_PORT_TYPE_INPUT = og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT
ATTR_PORT_TYPE_OUTPUT = og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT
# Internal State
# ------------------------------------------------------------------------------
class InternalState(InternalStateBase):
"""Internal state for the node."""
def __init__(self) -> None:
super().__init__()
self.attr_tracking = omni.warp.nodes.AttrTracking(
(
"dimCount",
),
)
def needs_initialization(
self,
db: OgnKernelDatabase,
check_file_modified_time: bool,
) -> bool:
"""Checks if the internal state needs to be (re)initialized."""
if super().needs_initialization(
db,
check_file_modified_time=check_file_modified_time,
):
return True
if self.attr_tracking.have_attrs_changed(db):
return True
return False
def initialize(
self,
db: OgnKernelDatabase,
kernel_dim_count: int,
) -> bool:
"""Initializes the internal state and recompile the kernel."""
if not super().initialize(db):
return False
# Retrieve the user attribute descriptions, if any.
attr_descs = deserialize_user_attribute_descs(db.state.userAttrDescs)
# Gather the information about each attribute to pass to the kernel.
attr_infos = gather_attribute_infos(
db.node,
db.inputs,
db.outputs,
attr_descs,
kernel_dim_count,
)
try:
kernel_module = initialize_kernel_module(
attr_infos,
self._code_provider,
self._code_str,
self._code_file,
)
except Exception:
db.log_error(traceback.format_exc())
return False
# Define the base class members.
self.attr_infos = attr_infos
self.kernel_module = kernel_module
self.attr_tracking.update_state(db)
return True
# Compute
# ------------------------------------------------------------------------------
def infer_kernel_shape(
db: OgnKernelDatabase,
) -> Tuple[int, ...]:
"""Infers the shape of the kernel."""
source = db.inputs.dimSource
if source == EXPLICIT_SOURCE:
dim_count = min(max(db.inputs.dimCount, 0), wp.types.ARRAY_MAX_DIMS)
return tuple(max(getattr(db.inputs, "dim{}".format(i + 1)), 0) for i in range(dim_count))
try:
value = getattr(db.inputs, source)
except AttributeError:
raise RuntimeError(
"The attribute '{}' used to source the dimension doesn't exist.".format(
attr_join_name(ATTR_PORT_TYPE_INPUT, source)
)
)
try:
return (value.shape[0],)
except AttributeError:
raise RuntimeError(
"The attribute '{}' used to source the dimension isn't an array.".format(
attr_join_name(ATTR_PORT_TYPE_INPUT, source)
)
)
def compute(db: OgnKernelDatabase, device: wp.context.Device) -> None:
"""Evaluates the node."""
db.set_dynamic_attribute_memory_location(
on_gpu=device.is_cuda,
gpu_ptr_kind=og.PtrToPtrKind.CPU,
)
# Infer the kernels's shape.
kernel_shape = infer_kernel_shape(db)
# Ensure that our internal state is correctly initialized.
timeline = omni.timeline.get_timeline_interface()
if db.internal_state.needs_initialization(db, timeline.is_stopped()):
if not db.internal_state.initialize(db, len(kernel_shape)):
return
db.internal_state.is_valid = True
# Exit early if there are no outputs defined.
if not db.internal_state.attr_infos[ATTR_PORT_TYPE_OUTPUT]:
return
# Retrieve the inputs and outputs argument values to pass to the kernel.
inputs, outputs = get_kernel_args(
db.inputs,
db.outputs,
db.internal_state.attr_infos,
db.internal_state.kernel_module,
kernel_shape,
)
# Ensure that all array input values are valid.
validate_input_arrays(db.node, db.internal_state.attr_infos, inputs)
# Launch the kernel.
wp.launch(
db.internal_state.kernel_module.compute,
dim=kernel_shape,
inputs=[inputs],
outputs=[outputs],
)
# Write the output values to the node's attributes.
write_output_attrs(db.outputs, db.internal_state.attr_infos, outputs)
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnKernel:
"""Warp's kernel node."""
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def initialize(graph_context: og.GraphContext, node: og.Node) -> None:
# Populate the devices tokens.
attr = og.Controller.attribute("inputs:device", node)
if attr.get_metadata(ogn.MetadataKeys.ALLOWED_TOKENS) is None:
attr.set_metadata(ogn.MetadataKeys.ALLOWED_TOKENS, ",".join(["cpu", "cuda:0"]))
@staticmethod
def compute(db: OgnKernelDatabase) -> None:
try:
device = wp.get_device(db.inputs.device)
except Exception:
# Fallback to a default device.
# This can happen due to a scene being authored on a device
# (e.g.: `cuda:1`) that is not available to another user opening
# that same scene.
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db, device)
except Exception:
db.internal_state.is_valid = False
db.log_error(traceback.format_exc())
wp.config.quiet = True
return
else:
wp.config.quiet = QUIET_DEFAULT
# Reset the user attributes event since it has now been processed.
db.state.userAttrsEvent = UserAttributesEvent.NONE
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnKernel.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Helpers to author point cloud geometries represented as OmniGraph bundles."""
from math import inf
from typing import Optional
import numpy as np
import omni.graph.core as og
import warp as wp
from omni.warp.nodes._impl.attributes import (
attr_get,
attr_get_array_on_gpu,
attr_set,
)
from omni.warp.nodes._impl.bundles import (
bundle_copy_attr_value,
bundle_create_attr,
bundle_create_child,
bundle_create_metadata_attr,
bundle_get_attr,
bundle_get_world_xform,
bundle_set_prim_type,
bundle_set_world_xform,
)
# Public API
# ------------------------------------------------------------------------------
def points_create_bundle(
dst_bundle: og.BundleContents,
point_count: int,
xform: Optional[np.ndarray] = None,
create_display_color: bool = False,
create_masses: bool = False,
create_velocities: bool = False,
create_widths: bool = False,
child_idx: int = 0,
) -> None:
"""Creates and initializes point cloud attributes within a bundle."""
child_bundle = bundle_create_child(dst_bundle, child_idx)
bundle_create_attr(
child_bundle,
"points",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.POSITION,
),
size=point_count,
)
bundle_set_prim_type(dst_bundle, "Points", child_idx=child_idx)
if xform is not None:
bundle_set_world_xform(dst_bundle, xform, child_idx=child_idx)
if create_display_color:
bundle_create_attr(
child_bundle,
"primvars:displayColor",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.COLOR,
),
size=point_count,
)
interp_attr = bundle_create_metadata_attr(
child_bundle,
"primvars:displayColor",
"interpolation",
og.Type(
og.BaseDataType.TOKEN,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
),
)
attr_set(interp_attr, "vertex")
if create_masses:
bundle_create_attr(
child_bundle,
"masses",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=point_count,
)
if create_velocities:
bundle_create_attr(
child_bundle,
"velocities",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.VECTOR,
),
size=point_count,
)
if create_widths:
bundle_create_attr(
child_bundle,
"widths",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=point_count,
)
def points_copy_bundle(
dst_bundle: og.BundleContents,
src_bundle: og.BundleContents,
deep_copy: bool = False,
child_idx: int = 0,
) -> None:
"""Creates and initializes points attributes from an existing bundle."""
dst_child_bundle = bundle_create_child(dst_bundle, child_idx)
src_child_bundle = src_bundle.bundle.get_child_bundle(child_idx)
dst_child_bundle.copy_bundle(src_child_bundle)
if deep_copy:
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "points", wp.vec3)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "primvars:displayColor", wp.vec3)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "masses", float)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "velocities", wp.vec3)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "widths", float)
def points_get_point_count(
bundle: og.BundleContents,
child_idx: int = 0,
) -> int:
"""Retrieves the number of points."""
return bundle_get_attr(bundle, "points", child_idx).size()
def points_get_points(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec3):
"""Retrieves the bundle points attribute as a Warp array."""
attr = bundle_get_attr(bundle, "points", child_idx)
return attr_get_array_on_gpu(attr, wp.vec3, read_only=bundle.read_only)
def points_get_velocities(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec3):
"""Retrieves the bundle velocities attribute as a Warp array."""
attr = bundle_get_attr(bundle, "velocities", child_idx)
return attr_get_array_on_gpu(attr, wp.vec3, read_only=bundle.read_only)
def points_get_widths(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=float):
"""Retrieves the bundle widths attribute as a Warp array."""
attr = bundle_get_attr(bundle, "widths", child_idx)
return attr_get_array_on_gpu(attr, float, read_only=bundle.read_only)
def points_get_masses(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=float):
"""Retrieves the bundle masses attribute as a Warp array."""
attr = bundle_get_attr(bundle, "masses", child_idx)
return attr_get_array_on_gpu(attr, float, read_only=bundle.read_only)
def points_get_display_color(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec3):
"""Retrieves the bundle display color attribute as a Warp array."""
attr = bundle_get_attr(bundle, "primvars:displayColor", child_idx)
return attr_get_array_on_gpu(attr, wp.vec3, read_only=bundle.read_only)
def points_get_local_extent(
bundle: og.BundleContents,
child_idx: int = 0,
) -> np.ndarray:
"""Retrieves the local extent of the geometry points."""
# Some standard workflows include a single 'extent' attribute when defining
# geometry primitives on the stage.
attr = bundle_get_attr(bundle, "extent", child_idx)
if attr is not None:
return attr_get(attr)
# Alternatively, the ReadPrims node offers an option to compute the bounding
# box which results in a triple of 'bboxMinCorner', 'bboxMaxCorner',
# and 'bboxTransform' attributes.
min_attr = bundle_get_attr(bundle, "bboxMinCorner", child_idx)
max_attr = bundle_get_attr(bundle, "bboxMaxCorner", child_idx)
if min_attr is not None and max_attr is not None:
return np.stack(
(
attr_get(min_attr),
attr_get(max_attr),
),
)
# The last resort is to compute the extent ourselves from
# the point positions.
points = points_get_points(bundle, child_idx=child_idx)
min_extent = wp.array((+inf, +inf, +inf), dtype=wp.vec3)
max_extent = wp.array((-inf, -inf, -inf), dtype=wp.vec3)
wp.launch(
_compute_extent_kernel,
dim=len(points),
inputs=[points],
outputs=[min_extent, max_extent],
)
return np.concatenate((min_extent.numpy(), max_extent.numpy()))
def points_get_world_extent(
bundle: og.BundleContents,
axis_aligned: bool = False,
child_idx: int = 0,
) -> np.ndarray:
"""Retrieves the world extent of the geometry points."""
extent = points_get_local_extent(bundle, child_idx=child_idx)
xform = bundle_get_world_xform(bundle, child_idx=child_idx)
if axis_aligned:
points = np.array(
(
(extent[0][0], extent[0][1], extent[0][2]),
(extent[0][0], extent[0][1], extent[1][2]),
(extent[0][0], extent[1][1], extent[0][2]),
(extent[0][0], extent[1][1], extent[1][2]),
(extent[1][0], extent[1][1], extent[1][2]),
(extent[1][0], extent[0][1], extent[1][2]),
(extent[1][0], extent[1][1], extent[0][2]),
(extent[1][0], extent[0][1], extent[0][2]),
),
)
else:
points = extent
points = np.pad(points, ((0, 0), (0, 1)), constant_values=1)
points = np.dot(xform.T, points[:, :, None]).squeeze()[:-1, :].T
return np.array(
(
np.amin(points, axis=0),
np.amax(points, axis=0),
)
)
# Private Helpers
# ------------------------------------------------------------------------------
@wp.kernel(enable_backward=False)
def _compute_extent_kernel(
points: wp.array(dtype=wp.vec3),
out_min_extent: wp.array(dtype=wp.vec3),
out_max_extent: wp.array(dtype=wp.vec3),
):
"""Computes the extent of a point cloud."""
tid = wp.tid()
wp.atomic_min(out_min_extent, 0, points[tid])
wp.atomic_max(out_max_extent, 0, points[tid])
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/points.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Backend implementation for kernel node(s)."""
from __future__ import annotations
from enum import IntFlag
import functools
import hashlib
import importlib.util
import json
import operator
import os
import tempfile
from typing import (
Any,
Callable,
Mapping,
NamedTuple,
Optional,
Sequence,
Tuple,
Union,
)
import omni.graph.core as og
import warp as wp
from omni.warp.nodes._impl.common import (
IntEnum,
get_warp_type_from_data_type_name,
type_convert_og_to_warp,
)
from omni.warp.nodes._impl.attributes import (
ATTR_BUNDLE_TYPE,
attr_cast_array_to_warp,
attr_get_base_name,
attr_get_name,
attr_join_name,
)
_ATTR_PORT_TYPE_INPUT = og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT
_ATTR_PORT_TYPE_OUTPUT = og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT
EXPLICIT_SOURCE = "explicit"
# Enumerators
# ------------------------------------------------------------------------------
class UserAttributesEvent(IntFlag):
"""User attributes event."""
NONE = 0
CREATED = 1 << 0
REMOVED = 1 << 1
class OutputArrayShapeSource(IntEnum):
"""Method to infer the shape of output attribute arrays."""
AS_INPUT_OR_AS_KERNEL = (0, "as input if any, or as kernel")
AS_KERNEL = (1, "as kernel")
class OutputBundleTypeSource(IntEnum):
"""Method to infer the type of output attribute bundles."""
AS_INPUT = (0, "as input if any")
AS_INPUT_OR_EXPLICIT = (1, "as input if any, or explicit")
EXPLICIT = (2, "explicit")
class ArrayAttributeFormat(IntEnum):
"""Format describing how attribute arrays are defined on the node."""
RAW = (0, "raw")
BUNDLE = (1, "bundle")
# User Attributes Description
# ------------------------------------------------------------------------------
class UserAttributeDesc(NamedTuple):
"""Description of an attribute added dynamically by users through the UI.
This struct is what the Attribute Editor UI passes to the node in order to
communicate any attribute metadata.
"""
port_type: og.AttributePortType
base_name: str
data_type_name: str
is_array: bool
array_format: ArrayAttributeFormat
array_shape_source: Union[None, OutputArrayShapeSource]
optional: bool
@classmethod
def deserialize(
cls,
data: Mapping[str:Any],
) -> Optional[UserAttributeDesc]:
"""Creates a new instance based on a serialized representation."""
# Retrieve the port type. It's invalid not to have any set.
port_type = data.get("port_type")
if port_type is None:
return None
port_type = og.AttributePortType(port_type)
# Define sensible default values.
# Although this class requires all of its member values to be explicitly
# defined upon initialization, it's possible that the incoming data was
# serialized with an older version of this class, in which case we might
# want to try filling any gap.
values = {
"array_format": ArrayAttributeFormat.RAW,
"array_shape_source": (
OutputArrayShapeSource.AS_INPUT_OR_AS_KERNEL if port_type == _ATTR_PORT_TYPE_OUTPUT else None
),
"optional": False,
}
# Override the default values with the incoming data.
values.update({k: v for k, v in data.items() if k in cls._fields})
# Ensure that the member values are set using their rightful types.
values.update(
{
"port_type": port_type,
"array_format": ArrayAttributeFormat(values["array_format"]),
"array_shape_source": (
None
if values["array_shape_source"] is None
else OutputArrayShapeSource(values["array_shape_source"])
),
}
)
try:
# This might error in case some members are still missing.
return cls(**values)
except TypeError:
return None
@property
def name(self) -> str:
"""Retrieves the attribute's name prefixed with its port type."""
return attr_join_name(self.port_type, self.base_name)
@property
def type(self) -> og.Attribute:
"""Retrieves OmniGraph's attribute type."""
return og.AttributeType.type_from_sdf_type_name(self.type_name)
@property
def type_name(self) -> str:
"""Retrieves OmniGraph's attribute type name."""
if self.is_array:
return "{}[]".format(self.data_type_name)
return self.data_type_name
def serialize(self) -> Mapping[str:Any]:
"""Converts this instance into a serialized representation."""
return self._replace(
port_type=int(self.port_type),
)._asdict()
def deserialize_user_attribute_descs(
data: str,
) -> Mapping[str, UserAttributeDesc]:
"""Deserializes a string into a mapping of (name, desc)."""
descs = {attr_join_name(x["port_type"], x["base_name"]): UserAttributeDesc.deserialize(x) for x in json.loads(data)}
# Filter out any invalid description.
return {k: v for k, v in descs.items() if v is not None}
def serialize_user_attribute_descs(
descs: Mapping[str, UserAttributeDesc],
) -> str:
"""Serializes a mapping of (name, desc) into a string."""
return json.dumps(tuple(x.serialize() for x in descs.values()))
# User Attributes Information
# ------------------------------------------------------------------------------
class OutputAttributeInfo(NamedTuple):
"""Information relating to an output node attribute."""
array_shape_source: Optional[OutputArrayShapeSource]
bundle_type_source: Optional[OutputBundleTypeSource]
bundle_type_explicit: Optional[str] = None
class AttributeInfo(NamedTuple):
"""Information relating to a node attribute.
This struct contains all the metadata required by the node to initialize
and evaluate. This includes compiling the kernel and initializing the Inputs
and Outputs structs that are then passed to the kernel as parameters.
We don't directly store the array shape, if any, since it is possible that
it might vary between each evaluation of the node's compute. Instead,
we store which method to use to infer the array's shape and let the node
determine the actual shape during each compute step.
Note
----
The `warp_type` member represents the type of the kernel parameter
corresdonding to that attribute. If the attribute is a bundle, then it is
expected to be a `wp.struct` holding the values of the bundle, unless
the bundle is of type :class:`Array`, in which case `warp_type` should be
a standard `wp.array`.
"""
port_type: og.AttributePortType
base_name: str
og_type: og.Type
warp_type: type
output: Optional[OutputAttributeInfo] = None
@property
def name(self) -> str:
return attr_join_name(self.port_type, self.base_name)
@property
def og_data_type(self) -> og.Type:
return og.Type(
self.og_type.base_type,
tuple_count=self.og_type.tuple_count,
array_depth=0,
role=self.og_type.role,
)
@property
def is_array(self) -> bool:
return self.og_type.array_depth > 0
@property
def is_bundle(self) -> bool:
return self.og_type == ATTR_BUNDLE_TYPE
@property
def dim_count(self) -> int:
if self.is_array:
return self.warp_type.ndim
return 0
@property
def warp_data_type(self) -> type:
if self.is_array:
return self.warp_type.dtype
return self.warp_type
@property
def warp_type_name(self) -> str:
if self.is_bundle:
return self.warp_type.cls.__name__
return get_warp_type_from_data_type_name(
self.warp_data_type.__name__,
dim_count=self.dim_count,
as_str=True,
)
@property
def warp_data_type_name(self) -> str:
if self.is_bundle:
return self.warp_type.cls.__name__
return get_warp_type_from_data_type_name(
self.warp_data_type.__name__,
dim_count=0,
as_str=True,
)
def gather_attribute_infos(
node: og.Node,
db_inputs: Any,
db_outputs: Any,
attr_descs: Mapping[str, UserAttributeDesc],
kernel_dim_count: int,
) -> Mapping[og.AttributePortType, Tuple[AttributeInfo, ...]]:
"""Gathers the information for each user attribute.
See also: :class:`AttributeInfo`.
"""
def extract_partial_info_from_attr(attr: og.Attribute) -> Tuple[Any, ...]:
"""Extract a partial information set from an attribute."""
name = attr_get_name(attr)
base_name = attr_get_base_name(attr)
og_type = attr.get_resolved_type()
is_array = og_type.array_depth > 0
return (name, base_name, og_type, is_array)
# Retrieve the user attributes defined on the node.
attrs = tuple(x for x in node.get_attributes() if x.is_dynamic())
# Gather the information for the input attributes.
input_attr_infos = []
for attr in attrs:
if attr.get_port_type() != _ATTR_PORT_TYPE_INPUT:
continue
(name, base_name, og_type, is_array) = extract_partial_info_from_attr(attr)
og_data_type = og.Type(
og_type.base_type,
tuple_count=og_type.tuple_count,
array_depth=0,
role=og_type.role,
)
input_attr_infos.append(
AttributeInfo(
port_type=_ATTR_PORT_TYPE_INPUT,
base_name=base_name,
og_type=og_type,
warp_type=type_convert_og_to_warp(
og_data_type,
dim_count=int(is_array),
),
)
)
# Gather the information for the output attributes.
output_attr_infos = []
for attr in attrs:
if attr.get_port_type() != _ATTR_PORT_TYPE_OUTPUT:
continue
(name, base_name, og_type, is_array) = extract_partial_info_from_attr(attr)
desc = attr_descs.get(name)
if desc is None:
# Fallback for nodes created before the attribute description
# feature was implemented.
array_shape_source = OutputArrayShapeSource.AS_INPUT_OR_AS_KERNEL
else:
array_shape_source = desc.array_shape_source
if array_shape_source == OutputArrayShapeSource.AS_INPUT_OR_AS_KERNEL:
# Check if we have an input attribute with a matching name,
# in which case we use its array dimension count.
try:
dim_count = next(x.dim_count for x in input_attr_infos if x.base_name == base_name)
except StopIteration:
# Fallback to using the kernel's dimension count.
dim_count = kernel_dim_count
elif array_shape_source == OutputArrayShapeSource.AS_KERNEL:
dim_count = kernel_dim_count
else:
assert False, "Unexpected array shape source method '{}'.".format(array_shape_source)
og_data_type = og.Type(
og_type.base_type,
tuple_count=og_type.tuple_count,
array_depth=0,
role=og_type.role,
)
output_attr_infos.append(
AttributeInfo(
port_type=_ATTR_PORT_TYPE_OUTPUT,
base_name=base_name,
og_type=og_type,
warp_type=type_convert_og_to_warp(
og_data_type,
dim_count=dim_count,
),
output=OutputAttributeInfo(
array_shape_source=array_shape_source,
bundle_type_source=OutputBundleTypeSource.AS_INPUT,
),
)
)
return {
_ATTR_PORT_TYPE_INPUT: tuple(input_attr_infos),
_ATTR_PORT_TYPE_OUTPUT: tuple(output_attr_infos),
}
# Kernel Code
# ------------------------------------------------------------------------------
_STRUCT_DECLARATION_CODE_TEMPLATE = """@wp.struct
class {name}:
{members}
"""
def _generate_struct_declaration_code(warp_struct: wp.struct) -> str:
"""Generates the code declaring a Warp struct."""
lines = []
for label, var in warp_struct.vars.items():
warp_type = var.type
if isinstance(warp_type, wp.array):
warp_data_type = warp_type.dtype
dim_count = warp_type.ndim
else:
warp_data_type = warp_type
dim_count = 0
warp_type_name = get_warp_type_from_data_type_name(
warp_data_type.__name__,
dim_count=dim_count,
as_str=True,
)
lines.append(" {}: {}".format(label, warp_type_name))
return _STRUCT_DECLARATION_CODE_TEMPLATE.format(
name=warp_struct.cls.__name__,
members="\n".join(lines),
)
_HEADER_CODE_TEMPLATE = """import warp as wp
{declarations}
@wp.struct
class Inputs:
{inputs}
pass
@wp.struct
class Outputs:
{outputs}
pass
"""
def _generate_header_code(
attr_infos: Mapping[og.AttributePortType, Tuple[AttributeInfo, ...]],
) -> str:
"""Generates the code header based on the node's attributes."""
# Retrieve all the Warp struct types corresponding to bundle attributes.
struct_types = {x.warp_type_name: x.warp_type for _, v in attr_infos.items() for x in v if x.is_bundle}
# Generate the code that declares the Warp structs found.
declarations = [""]
declarations.extend(_generate_struct_declaration_code(x) for _, x in struct_types.items())
# Generate the lines of code declaring the members for each port type.
lines = {k: tuple(" {}: {}".format(x.base_name, x.warp_type_name) for x in v) for k, v in attr_infos.items()}
# Return the template code populated with the members.
return _HEADER_CODE_TEMPLATE.format(
declarations="\n".join(declarations),
inputs="\n".join(lines.get(_ATTR_PORT_TYPE_INPUT, ())),
outputs="\n".join(lines.get(_ATTR_PORT_TYPE_OUTPUT, ())),
)
def _get_user_code(code_provider: str, code_str: str, code_file: str) -> str:
"""Retrieves the code provided by the user."""
if code_provider == "embedded":
return code_str
if code_provider == "file":
with open(code_file, "r") as f:
return f.read()
assert False, "Unexpected code provider '{}'.".format(code_provider)
# Kernel Module
# ------------------------------------------------------------------------------
def _load_code_as_module(code: str, name: str) -> Any:
"""Loads a Python module from the given source code."""
# It's possible to use the `exec()` built-in function to create and
# populate a Python module with the source code defined in a string,
# however warp requires access to the source code of the kernel's
# function, which is only available when the original source file
# pointed by the function attribute `__code__.co_filename` can
# be opened to read the lines corresponding to that function.
# As such, we must write the source code into a temporary file
# on disk before importing it as a module and having the function
# turned into a kernel by warp's mechanism.
# Create a temporary file.
file, file_path = tempfile.mkstemp(suffix=".py")
try:
# Save the embedded code into the temporary file.
with os.fdopen(file, "w") as f:
f.write(code)
# Import the temporary file as a Python module.
spec = importlib.util.spec_from_file_location(name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
finally:
# The resulting Python module is stored into memory as a bytcode
# object and the kernel function has already been parsed by warp
# as long as it was correctly decorated, so it's now safe to
# clean-up the temporary file.
os.remove(file_path)
return module
def initialize_kernel_module(
attr_infos: Mapping[og.AttributePortType, Tuple[AttributeInfo, ...]],
code_provider: str,
code_str: str,
code_file: str,
) -> wp.context.Module:
# Ensure that all output parameters are arrays. Writing to non-array
# types is not supported as per CUDA's design.
invalid_attrs = tuple(x.name for x in attr_infos[_ATTR_PORT_TYPE_OUTPUT] if not x.is_array and not x.is_bundle)
if invalid_attrs:
raise RuntimeError(
"Output attributes are required to be arrays or bundles but "
"the following attributes are not: {}.".format(", ".join(invalid_attrs))
)
# Retrieve the kernel code to evaluate.
code_header = _generate_header_code(attr_infos)
user_code = _get_user_code(code_provider, code_str, code_file)
code = "{}\n{}".format(code_header, user_code)
# Create a Python module made of the kernel code.
# We try to keep its name unique to ensure that it's not clashing with
# other kernel modules from the same session.
uid = hashlib.blake2b(bytes(code, encoding="utf-8"), digest_size=8)
module_name = "warp-kernelnode-{}".format(uid.hexdigest())
kernel_module = _load_code_as_module(code, module_name)
# Validate the module's contents.
if not hasattr(kernel_module, "compute"):
raise RuntimeError("The code must define a kernel function named 'compute'.")
if not isinstance(kernel_module.compute, wp.context.Kernel):
raise RuntimeError("The 'compute' function must be decorated with '@wp.kernel'.")
# Configure warp to only compute the forward pass.
wp.set_module_options({"enable_backward": False}, module=kernel_module)
return kernel_module
# Data I/O
# ------------------------------------------------------------------------------
def _infer_output_array_shape(
attr_info: AttributeInfo,
input_attr_infos: Tuple[AttributeInfo, ...],
kernel_inputs: Any,
kernel_shape: Sequence[int],
) -> Tuple[int, ...]:
if attr_info.output.array_shape_source == OutputArrayShapeSource.AS_INPUT_OR_AS_KERNEL:
# Check if we have an input attribute with a matching name,
# in which case we use its array shape.
try:
ref_attr_base_name = next(
x.base_name
for x in input_attr_infos
if (x.base_name == attr_info.base_name and x.is_array and x.dim_count == attr_info.dim_count)
)
return getattr(kernel_inputs, ref_attr_base_name).shape
except StopIteration:
# Fallback to using the kernel's shape.
return tuple(kernel_shape)
if attr_info.output.array_shape_source == OutputArrayShapeSource.AS_KERNEL:
return tuple(kernel_shape)
assert False, "Unexpected array shape source method '{}'.".format(attr_info.output.array_shape_source)
class KernelArgsConfig(NamedTuple):
"""Configuration for resolving kernel arguments."""
input_bundle_handlers: Optional[Mapping[str, Callable]] = None
output_bundle_handlers: Optional[Mapping[str, Callable]] = None
def get_kernel_args(
db_inputs: Any,
db_outputs: Any,
attr_infos: Mapping[og.AttributePortType, Tuple[AttributeInfo, ...]],
kernel_module: Any,
kernel_shape: Sequence[int],
device: Optional[wp.context.Device] = None,
config: Optional[KernelArgsConfig] = None,
) -> Tuple[Any, Any]:
"""Retrieves the in/out argument values to pass to the kernel."""
if device is None:
device = wp.get_device()
if config is None:
config = KernelArgsConfig()
# Initialize the kernel's input data.
inputs = kernel_module.Inputs()
for info in attr_infos[_ATTR_PORT_TYPE_INPUT]:
# Retrieve the input attribute value and cast it to
# the corresponding warp type.
if info.is_array:
value = getattr(db_inputs, info.base_name)
# The array value might define 2 dimensions when tuples such as
# wp.vec3 are used as data type, so we preserve only the first
# dimension to retrieve the actual shape since OmniGraph only
# supports 1D arrays anyways.
shape = value.shape[:1]
value = attr_cast_array_to_warp(
value,
info.warp_data_type,
shape,
device,
)
elif info.is_bundle:
raise NotImplementedError("Bundle attributes are not yet supported.")
else:
value = getattr(db_inputs, info.base_name)
# Store the result in the inputs struct.
setattr(inputs, info.base_name, value)
# Initialize the kernel's output data.
outputs = kernel_module.Outputs()
for info in attr_infos[_ATTR_PORT_TYPE_OUTPUT]:
# Retrieve the output attribute value and cast it to the corresponding
# warp type.
if info.is_array:
shape = _infer_output_array_shape(
info,
attr_infos[_ATTR_PORT_TYPE_INPUT],
inputs,
kernel_shape,
)
# Allocate a buffer for the array.
size = functools.reduce(operator.mul, shape)
setattr(db_outputs, "{}_size".format(info.base_name), size)
value = getattr(db_outputs, info.base_name)
value = attr_cast_array_to_warp(
value,
info.warp_data_type,
shape,
device,
)
elif info.is_bundle:
raise NotImplementedError("Bundle attributes are not yet supported.")
else:
assert False, "Output attributes are expected to be arrays or bundles."
# Store the result in the outputs struct.
setattr(outputs, info.base_name, value)
return (inputs, outputs)
def write_output_attrs(
db_outputs: Any,
attr_infos: Mapping[og.AttributePortType, Tuple[AttributeInfo, ...]],
kernel_outputs: Any,
device: Optional[wp.context.Device] = None,
) -> None:
"""Writes the output values to the node's attributes."""
if device is None:
device = wp.get_device()
if device.is_cuda:
# CUDA attribute arrays are directly being written to by Warp.
return
for info in attr_infos[_ATTR_PORT_TYPE_OUTPUT]:
value = getattr(kernel_outputs, info.base_name)
setattr(db_outputs, info.base_name, value)
# Validation
# ------------------------------------------------------------------------------
def validate_input_arrays(
node: og.Node,
attr_infos: Mapping[og.AttributePortType, Tuple[AttributeInfo, ...]],
kernel_inputs: Any,
) -> None:
"""Validates array input attributes."""
for info in attr_infos[_ATTR_PORT_TYPE_INPUT]:
value = getattr(kernel_inputs, info.base_name)
if not isinstance(value, wp.array):
continue
# Ensure that all array input attributes are not NULL,
# unless they are set as being optional.
attr = og.Controller.attribute(info.name, node)
if not attr.is_optional_for_compute and not value.ptr:
raise RuntimeError("Empty value for non-optional attribute '{}'.".format(info.name))
# Node's Internal State
# ------------------------------------------------------------------------------
class InternalStateBase:
"""Base class for the node's internal state."""
def __init__(self) -> None:
self._code_provider = None
self._code_str = None
self._code_file = None
self._code_file_timestamp = None
self.attr_infos = None
self.kernel_module = None
self.is_valid = False
def needs_initialization(
self,
db: Any,
check_file_modified_time: bool,
) -> bool:
"""Checks if the internal state needs to be (re)initialized."""
if self.is_valid:
# If everything is in order, we only need to recompile the kernel
# when attributes are removed, since adding new attributes is not
# a breaking change.
if self.kernel_module is None or UserAttributesEvent.REMOVED & db.state.userAttrsEvent:
return True
else:
# If something previously went wrong, we always recompile the kernel
# when attributes are edited, in case it might fix code that
# errored out due to referencing a non-existing attribute.
if db.state.userAttrsEvent != UserAttributesEvent.NONE:
return True
if self.attr_infos is None:
return True
if self._code_provider != db.inputs.codeProvider:
return True
if self._code_provider == "embedded":
if self._code_str != db.inputs.codeStr:
return True
elif self._code_provider == "file":
if self._code_file != db.inputs.codeFile or (
check_file_modified_time and (self._code_file_timestamp != os.path.getmtime(self._code_file))
):
return True
else:
assert False, ("Unexpected code provider '{}'.".format(self._code_provider),)
return False
def initialize(self, db: Any) -> bool:
"""Initialize the internal state and recompile the kernel."""
# Cache the node attribute values relevant to this internal state.
# They're the ones used to check whether this state is outdated or not.
self._code_provider = db.inputs.codeProvider
self._code_str = db.inputs.codeStr
self._code_file = db.inputs.codeFile
return True
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/kernel.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Helpers to author OmniGraph attributes."""
import functools
import inspect
import math
import operator
from typing import (
Any,
Optional,
Union,
Sequence,
)
import numpy as np
import omni.graph.core as og
import warp as wp
from omni.warp.nodes._impl.common import type_convert_og_to_warp
ATTR_BUNDLE_TYPE = og.Type(
og.BaseDataType.RELATIONSHIP,
1,
0,
og.AttributeRole.BUNDLE,
)
# Names
# ------------------------------------------------------------------------------
_ATTR_PORT_TYPES = (
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE,
)
_ATTR_NAME_FMTS = {x: "{}:{{}}".format(og.get_port_type_namespace(x)) for x in _ATTR_PORT_TYPES}
def attr_join_name(
port_type: og.AttributePortType,
base_name: str,
) -> str:
"""Build an attribute name by prefixing it with its port type."""
return _ATTR_NAME_FMTS[port_type].format(base_name)
def attr_get_base_name(
attr: og.Attribute,
) -> str:
"""Retrieves an attribute base name."""
name = attr.get_name()
if (
attr.get_type_name() == "bundle"
and (attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
and name.startswith("outputs_")
):
# Output bundles are a bit special because they are in fact implemented
# as USD primitives, and USD doesn't support the colon symbol `:` in
# primitive names, thus output bundles are prefixed with `outputs_` in
# OmniGraph instead of `outputs:` like everything else.
return name[8:]
return name.split(":")[-1]
def attr_get_name(
attr: og.Attribute,
) -> str:
"""Retrieves an attribute name."""
name = attr.get_name()
if (
attr.get_type_name() == "bundle"
and (attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
and name.startswith("outputs_")
):
# Output bundles are a bit special because they are in fact implemented
# as USD primitives, and USD doesn't support the colon symbol `:` in
# primitive names, thus output bundles are prefixed with `outputs_` in
# OmniGraph instead of `outputs:` like everything else.
return attr_join_name(
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
name[8:],
)
return name
# Values
# ------------------------------------------------------------------------------
def attr_get(
attr: og.AttributeData,
) -> Any:
"""Retrieves the value from an attribute living on the CPU."""
return attr.get(on_gpu=False)
def attr_set(
attr: og.AttributeData,
value: Any,
) -> None:
"""Sets the given value onto an array attribute living on the CPU."""
attr.set(value, on_gpu=False)
def attr_get_array_on_gpu(
attr: og.AttributeData,
dtype: type,
read_only: bool = True,
) -> wp.array:
"""Retrieves the value of an array attribute living on the GPU."""
attr.gpu_ptr_kind = og.PtrToPtrKind.CPU
(ptr, _) = attr.get_array(
on_gpu=True,
get_for_write=not read_only,
reserved_element_count=0 if read_only else attr.size(),
)
return wp.from_ptr(ptr, attr.size(), dtype=dtype)
def attr_cast_array_to_warp(
value: Union[np.array, og.DataWrapper],
dtype: type,
shape: Sequence[int],
device: wp.context.Device,
) -> wp.array:
"""Casts an attribute array value to its corresponding warp type."""
if device.is_cpu:
return wp.array(
value,
dtype=dtype,
shape=shape,
owner=False,
device=device,
)
elif device.is_cuda:
size = functools.reduce(operator.mul, shape)
return wp.types.from_ptr(
value.memory,
size,
dtype=dtype,
shape=shape,
device=device,
)
assert False, "Unexpected device '{}'.".format(device.alias)
# Tracking
# ------------------------------------------------------------------------------
class AttrTracking:
"""Attributes state for tracking changes."""
def __init__(self, names: Sequence[str]) -> None:
self._names = names
self._state = [None] * len(names)
def have_attrs_changed(self, db: og.Database) -> bool:
"""Compare the current attribute values with the internal state."""
for i, name in enumerate(self._names):
cached_value = self._state[i]
current_value = getattr(db.inputs, name)
if isinstance(current_value, np.ndarray):
if not np.array_equal(current_value, cached_value):
return True
elif current_value != cached_value:
return True
return False
def update_state(self, db: og.Database) -> None:
"""Updates the internal state with the current attribute values."""
for i, name in enumerate(self._names):
current_value = getattr(db.inputs, name)
if isinstance(current_value, np.ndarray):
self._state[i] = current_value.copy()
else:
self._state[i] = current_value
# High-level Helper
# ------------------------------------------------------------------------------
def from_omni_graph(
value: Union[np.ndarray, og.DataWrapper, og.AttributeData, og.DynamicAttributeAccess],
dtype: Optional[type] = None,
shape: Optional[Sequence[int]] = None,
device: Optional[wp.context.Device] = None,
) -> wp.array:
"""Casts an OmniGraph array data to its corresponding Warp type."""
def from_data_wrapper(
data: og.DataWrapper,
dtype: Optional[type],
shape: Optional[Sequence[int]],
device: Optional[wp.context.Device],
) -> wp.array:
if data.gpu_ptr_kind != og.PtrToPtrKind.CPU:
raise RuntimeError("All pointers must live on the CPU, make sure to set 'cudaPointers' to 'cpu'.")
elif not data.is_array:
raise RuntimeError("The attribute data isn't an array.")
if dtype is None:
base_type = type_convert_og_to_warp(
og.Type(
data.dtype.base_type,
tuple_count=data.dtype.tuple_count,
array_depth=0,
role=og.AttributeRole.MATRIX if data.dtype.is_matrix_type() else og.AttributeRole.NONE,
),
)
dim_count = len(data.shape)
if dim_count == 1:
dtype = base_type
elif dim_count == 2:
dtype = wp.types.vector(length=data.shape[1], dtype=base_type)
elif dim_count == 3:
dtype = wp.types.matrix(shape=(data.shape[1], data.shape[2]), dtype=base_type)
else:
raise RuntimeError("Arrays with more than 3 dimensions are not supported.")
arr_size = data.shape[0] * data.dtype.size
element_size = wp.types.type_size_in_bytes(dtype)
if shape is None:
# Infer a shape compatible with the dtype.
for i in range(len(data.shape)):
if functools.reduce(operator.mul, data.shape[: i + 1]) * element_size == arr_size:
shape = data.shape[: i + 1]
break
if shape is None:
if arr_size % element_size != 0:
raise RuntimeError(
"Cannot infer a size matching the Warp data type '{}' with "
"an array size of '{}' bytes.".format(dtype.__name__, arr_size)
)
size = arr_size // element_size
else:
size = functools.reduce(operator.mul, shape)
src_device = wp.get_device(str(data.device))
dst_device = device
return wp.from_ptr(
data.memory,
size,
dtype=dtype,
shape=shape,
device=src_device,
).to(dst_device)
def from_attr_data(
data: og.AttributeData,
dtype: Optional[type],
shape: Optional[Sequence[int]],
device: Optional[wp.context.Device],
) -> wp.array:
if data.gpu_valid():
on_gpu = True
elif data.cpu_valid():
on_gpu = False
else:
raise RuntimeError("The attribute data isn't valid.")
if on_gpu:
data_type = data.get_type()
base_type = type_convert_og_to_warp(
og.Type(
data_type.base_type,
tuple_count=data_type.tuple_count,
array_depth=0,
role=data_type.role,
),
)
if dtype is None:
dtype = base_type
arr_size = data.size() * wp.types.type_size_in_bytes(base_type)
element_size = wp.types.type_size_in_bytes(dtype)
if shape is None:
# Infer a shape compatible with the dtype.
if data_type.is_matrix_type():
dim = math.isqrt(data_type.tuple_count)
arr_shape = (data.size(), dim, dim)
else:
arr_shape = (data.size(), data_type.tuple_count)
for i in range(len(arr_shape)):
if functools.reduce(operator.mul, arr_shape[: i + 1]) * element_size == arr_size:
shape = arr_shape[: i + 1]
break
if shape is None:
if arr_size % element_size != 0:
raise RuntimeError(
"Cannot infer a size matching the Warp data type '{}' with "
"an array size of '{}' bytes.".format(dtype.__name__, arr_size)
)
size = arr_size // element_size
else:
size = functools.reduce(operator.mul, shape)
data.gpu_ptr_kind = og.PtrToPtrKind.CPU
(ptr, _) = data.get_array(
on_gpu=True,
get_for_write=not data.is_read_only(),
reserved_element_count=0 if data.is_read_only() else data.size(),
)
src_device = wp.get_device("cuda")
dst_device = device
return wp.from_ptr(
ptr,
size,
dtype=dtype,
shape=shape,
device=src_device,
).to(dst_device)
else:
arr = data.get_array(
on_gpu=False,
get_for_write=not data.is_read_only(),
reserved_element_count=0 if data.is_read_only() else data.size(),
)
return wp.from_numpy(arr, dtype=dtype, shape=shape, device=device)
if isinstance(value, np.ndarray):
return wp.from_numpy(value, dtype=dtype, shape=shape, device=device)
elif isinstance(value, og.DataWrapper):
return from_data_wrapper(value, dtype, shape, device)
elif isinstance(value, og.AttributeData):
return from_attr_data(value, dtype, shape, device)
elif og.DynamicAttributeAccess in inspect.getmro(type(getattr(value, "_parent", None))):
if device is None:
device = wp.get_device()
if device.is_cpu:
return wp.from_numpy(value.cpu, dtype=dtype, shape=shape, device=device)
elif device.is_cuda:
return from_data_wrapper(value.gpu, dtype, shape, device)
else:
assert False, "Unexpected device '{}'.".format(device.alias)
return None
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/attributes.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Helpers to author OmniGraph bundles."""
from typing import (
Optional,
Sequence,
)
import numpy as np
import omni.graph.core as og
import warp as wp
from omni.warp.nodes._impl.attributes import (
attr_get,
attr_get_array_on_gpu,
attr_set,
)
# High-level Bundle API (og.BundleContents)
# ------------------------------------------------------------------------------
def bundle_get_child_count(
bundle: og.BundleContents,
) -> int:
"""Retrieves the number of children defined for a bundle."""
return bundle.bundle.get_child_bundle_count()
def bundle_get_prim_type(
bundle: og.BundleContents,
child_idx: int = 0,
) -> str:
"""Retrieves the primitive type."""
attr = bundle_get_attr(bundle, "sourcePrimType", child_idx)
return attr_get(attr)
def bundle_set_prim_type(
bundle: og.BundleContents,
prim_type: str,
child_idx: int = 0,
) -> None:
"""Sets the primitive type."""
child_bundle = bundle_create_child(bundle, child_idx)
attr = bundle_create_attr(
child_bundle,
"sourcePrimType",
og.Type(
og.BaseDataType.TOKEN,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
),
)
attr_set(attr, prim_type)
def bundle_get_world_xform(
bundle: og.BundleContents,
child_idx: int = 0,
) -> np.ndarray:
"""Retrieves the world transformation matrix."""
attr = bundle_get_attr(bundle, "worldMatrix", child_idx)
if attr is None:
return np.identity(4)
return attr_get(attr).reshape(4, 4)
def bundle_set_world_xform(
bundle: og.BundleContents,
xform: np.ndarray,
child_idx: int = 0,
) -> None:
"""Sets the bundle's world transformation matrix."""
child_bundle = bundle_create_child(bundle, child_idx)
attr = bundle_create_attr(
child_bundle,
"worldMatrix",
og.Type(
og.BaseDataType.DOUBLE,
tuple_count=16,
array_depth=0,
role=og.AttributeRole.MATRIX,
),
)
attr_set(attr, xform)
def bundle_create_child(
bundle: og.BundleContents,
child_idx: int = 0,
) -> og.IBundle2:
"""Creates a single child bundle if it doesn't already exist."""
if child_idx < bundle.bundle.get_child_bundle_count():
return bundle.bundle.get_child_bundle(child_idx)
return bundle.bundle.create_child_bundle("prim{}".format(child_idx))
def bundle_get_attr(
bundle: og.BundleContents,
name: str,
child_idx: int = 0,
) -> Optional[og.AttributeData]:
"""Retrieves a bundle attribute from its name."""
if bundle.bundle.get_child_bundle_count():
attr = bundle.bundle.get_child_bundle(child_idx).get_attribute_by_name(name)
else:
attr = bundle.bundle.get_attribute_by_name(name)
if not attr.is_valid():
return None
return attr
def bundle_has_changed(
bundle: og.BundleContents,
child_idx: int = 0,
) -> bool:
"""Checks whether the contents of the bundle has changed."""
with bundle.changes() as bundle_changes:
child_bundle = bundle.bundle.get_child_bundle(child_idx)
return bundle_changes.get_change(child_bundle) != og.BundleChangeType.NONE
def bundle_have_attrs_changed(
bundle: og.BundleContents,
attr_names: Sequence[str],
child_idx: int = 0,
) -> bool:
"""Checks whether the contents of a bundle's attributes have changed."""
with bundle.changes() as bundle_changes:
child_bundle = bundle.bundle.get_child_bundle(child_idx)
for attr_name in attr_names:
attr = child_bundle.get_attribute_by_name(attr_name)
if bundle_changes.get_change(attr) != og.BundleChangeType.NONE:
return True
return False
# Low-level Bundle API (og.IBundle2)
# ------------------------------------------------------------------------------
def bundle_create_attr(
bundle: og.IBundle2,
name: str,
og_type: og.Type,
size: int = 0,
) -> og.AttributeData:
"""Creates a bundle attribute if it doesn't already exist."""
attr = bundle.get_attribute_by_name(name)
if attr.is_valid() and attr.get_type() == og_type and attr.size() == size:
return attr
return bundle.create_attribute(name, og_type, element_count=size)
def bundle_create_metadata_attr(
bundle: og.IBundle2,
name: str,
field_name: str,
og_type: og.Type,
) -> og.AttributeData:
"""Creates a bundle metadata attribute if it doesn't already exist."""
attr = bundle.get_attribute_metadata_by_name(name, field_name)
if attr.is_valid() and attr.get_type() == og_type:
return attr
return bundle.create_attribute_metadata(name, field_name, og_type)
def bundle_copy_attr_value(
dst_bundle: og.IBundle2,
src_bundle: og.IBundle2,
name: str,
dtype: og.Type,
) -> None:
"""Copies an attribute value from one bundle to another."""
dst_attr = dst_bundle.get_attribute_by_name(name)
src_attr = src_bundle.get_attribute_by_name(name)
if not dst_attr.is_valid() or not src_attr.is_valid():
return
wp.copy(
attr_get_array_on_gpu(dst_attr, dtype, read_only=False),
attr_get_array_on_gpu(src_attr, dtype, read_only=True),
)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/bundles.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node inspecting the changes made to an attribute."""
import traceback
from typing import Union
import numpy as np
import omni.graph.core as og
import warp as wp
from omni.warp.nodes.ogn.OgnBundleInspectChangesDatabase import OgnBundleInspectChangesDatabase
_ATTR_NAMES_PER_PRIM_TYPE = {
"Mesh": (
"points",
"faceVertexCounts",
"faceVertexIndices",
"primvars:normals",
"primvars:st",
),
"Points": (
"points",
"widths",
),
}
# Helpers
# ------------------------------------------------------------------------------
def get_cpu_array(
attr: og.AttributeData,
read_only: bool = True,
) -> Union[np.ndarray, str]:
"""Retrieves the value of an array attribute living on the CPU."""
return attr.get_array(
on_gpu=False,
get_for_write=not read_only,
reserved_element_count=0 if read_only else attr.size(),
)
# Compute
# ------------------------------------------------------------------------------
def compute(db: OgnBundleInspectChangesDatabase) -> None:
"""Evaluates the node."""
if not db.inputs.bundle.valid or not db.outputs.bundle.valid:
return
db.outputs.bundle = db.inputs.bundle
attrs_changed = []
with db.inputs.bundle.changes() as bundle_changes:
for bundle in db.inputs.bundle.bundle.get_child_bundles():
attr = bundle.get_attribute_by_name("sourcePrimType")
prim_type = get_cpu_array(attr)
attr_names = _ATTR_NAMES_PER_PRIM_TYPE.get(prim_type)
for attr_name in attr_names:
if attr_name in attrs_changed:
continue
attr = bundle.get_attribute_by_name(attr_name)
changes = bundle_changes.get_change(attr)
if changes == og.BundleChangeType.NONE:
continue
attrs_changed.append(attr_name)
db.outputs.attrsChanged = " ".join(attrs_changed)
db.outputs.topologyChanged = db.outputs.attrsChanged != "points"
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnBundleInspectChanges:
"""Node."""
@staticmethod
def compute(db: OgnBundleInspectChangesDatabase) -> None:
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.log_error(traceback.format_exc())
return
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnBundleInspectChanges.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node simulating particles."""
from math import inf
import traceback
import numpy as np
import omni.graph.core as og
import omni.timeline
import warp as wp
import omni.warp.nodes
from omni.warp.nodes.ogn.OgnParticlesSimulateDatabase import OgnParticlesSimulateDatabase
USE_GRAPH = True
PROFILING = False
# Kernels
# ------------------------------------------------------------------------------
@wp.kernel(enable_backward=False)
def query_max_value_kernel(
values: wp.array(dtype=float),
out_max: wp.array(dtype=float),
):
wp.atomic_max(out_max, 0, values[wp.tid()])
@wp.kernel(enable_backward=False)
def compute_particles_inv_mass_kernel(
masses: wp.array(dtype=float),
out_inv_masses: wp.array(dtype=float),
):
tid = wp.tid()
out_inv_masses[tid] = 1.0 / masses[tid]
@wp.kernel(enable_backward=False)
def compute_particles_radius_kernel(
widths: wp.array(dtype=float),
out_radii: wp.array(dtype=float),
):
tid = wp.tid()
out_radii[tid] = widths[tid] * 0.5
@wp.kernel(enable_backward=False)
def transform_points_kernel(
points: wp.array(dtype=wp.vec3),
xform: wp.mat44,
out_points: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
out_points[tid] = wp.transform_point(xform, points[tid])
@wp.kernel(enable_backward=False)
def update_collider_kernel(
points_0: wp.array(dtype=wp.vec3),
points_1: wp.array(dtype=wp.vec3),
xform_0: wp.mat44,
xform_1: wp.mat44,
sim_dt: float,
out_points: wp.array(dtype=wp.vec3),
out_velocities: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
point_0 = wp.transform_point(xform_0, points_0[tid])
point_1 = wp.transform_point(xform_1, points_1[tid])
out_points[tid] = point_0
out_velocities[tid] = (point_1 - point_0) / sim_dt
@wp.kernel(enable_backward=False)
def update_particles_kernel(
points_0: wp.array(dtype=wp.vec3),
xform: wp.mat44,
out_points: wp.array(dtype=wp.vec3),
out_velocities: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
point = wp.transform_point(xform, points_0[tid])
diff = point - points_0[tid]
out_points[tid] = point
out_velocities[tid] = out_velocities[tid] + diff
# Internal State
# ------------------------------------------------------------------------------
class InternalState:
"""Internal state for the node."""
def __init__(self) -> None:
self.sim_dt = None
self.sim_tick = None
self.model = None
self.integrator = None
self.state_0 = None
self.state_1 = None
self.xform = None
self.collider_xform = None
self.collider_mesh = None
self.collider_points_0 = None
self.collider_points_1 = None
self.graph = None
self.sim_enabled = True
self.time = 0.0
self.is_valid = False
self.attr_tracking = omni.warp.nodes.AttrTracking(
(
"substepCount",
"gravity",
"globalScale",
"contactElasticStiffness",
"contactFrictionStiffness",
"contactFrictionCoeff",
"contactDampingStiffness",
"particlesQueryRange",
"particlesContactAdhesion",
"particlesContactCohesion",
"colliderContactDistance",
"colliderContactQueryRange",
"groundEnabled",
"groundAltitude",
),
)
def needs_initialization(self, db: OgnParticlesSimulateDatabase) -> bool:
"""Checks if the internal state needs to be (re)initialized."""
if not self.is_valid or not db.inputs.enabled or not self.sim_enabled:
return True
if self.attr_tracking.have_attrs_changed(db):
return True
if db.inputs.time < self.time:
# Reset the simulation when we're rewinding.
return True
return False
def initialize(
self,
db: OgnParticlesSimulateDatabase,
device: wp.context.Device,
) -> bool:
"""Initializes the internal state."""
# Lazy load warp.sim here to not slow down extension loading.
import warp.sim
# Compute the simulation time step.
timeline = omni.timeline.get_timeline_interface()
sim_rate = timeline.get_ticks_per_second()
sim_dt = 1.0 / sim_rate
# Initialize Warp's simulation model builder.
builder = wp.sim.ModelBuilder()
# Retrieve some data from the particles points.
points = omni.warp.nodes.points_get_points(db.inputs.particles)
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.particles)
# Transform the particles point positions into world space.
world_points = wp.empty(len(points), dtype=wp.vec3)
wp.launch(
kernel=transform_points_kernel,
dim=len(points),
inputs=[
points,
xform.T,
],
outputs=[
world_points,
],
)
if db.inputs.collider.valid:
# Retrieve some data from the collider mesh.
collider_points = omni.warp.nodes.mesh_get_points(db.inputs.collider)
collider_xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.collider)
# Transform the collider point positions into world space.
collider_world_points = wp.empty(
len(collider_points),
dtype=wp.vec3,
)
wp.launch(
kernel=transform_points_kernel,
dim=len(collider_points),
inputs=[
collider_points,
collider_xform.T,
],
outputs=[
collider_world_points,
],
)
# Initialize Warp's mesh instance, which requires
# triangulated meshes.
collider_face_vertex_indices = omni.warp.nodes.mesh_triangulate(
db.inputs.collider,
)
collider_mesh = wp.sim.Mesh(
collider_world_points.numpy(),
collider_face_vertex_indices.numpy(),
compute_inertia=False,
)
# Register the collider geometry mesh into Warp's simulation model
# builder.
builder.add_shape_mesh(
body=-1,
mesh=collider_mesh,
pos=(0.0, 0.0, 0.0),
rot=(0.0, 0.0, 0.0, 1.0),
scale=(1.0, 1.0, 1.0),
)
# Store the collider's point positions as internal state.
collider_points_0 = wp.empty_like(collider_points)
collider_points_1 = wp.empty_like(collider_points)
wp.copy(collider_points_0, collider_points)
wp.copy(collider_points_1, collider_points)
# Store the class members.
self.collider_xform = collider_xform.copy()
self.collider_mesh = collider_mesh
self.collider_points_0 = collider_points_0
self.collider_points_1 = collider_points_1
else:
self.collider_mesh = None
# Register the ground.
builder.set_ground_plane(
offset=-db.inputs.groundAltitude,
ke=db.inputs.contactElasticStiffness * db.inputs.globalScale,
kd=db.inputs.contactDampingStiffness * db.inputs.globalScale,
kf=db.inputs.contactFrictionStiffness * db.inputs.globalScale,
mu=db.inputs.contactFrictionCoeff,
)
# Build the simulation model.
model = builder.finalize()
# Register the input particles into the system.
model.particle_count = omni.warp.nodes.points_get_point_count(db.inputs.particles)
model.particle_q = world_points
model.particle_qd = omni.warp.nodes.points_get_velocities(db.inputs.particles)
model.particle_mass = omni.warp.nodes.points_get_masses(db.inputs.particles)
model.particle_inv_mass = wp.empty_like(model.particle_mass)
wp.launch(
compute_particles_inv_mass_kernel,
dim=model.particle_count,
inputs=[model.particle_mass],
outputs=[model.particle_inv_mass],
)
widths = omni.warp.nodes.points_get_widths(db.inputs.particles)
model._particle_radius = wp.empty_like(widths)
wp.launch(
compute_particles_radius_kernel,
dim=model.particle_count,
inputs=[widths],
outputs=[model._particle_radius],
)
model.particle_flags = wp.empty(model.particle_count, dtype=wp.uint32)
model.particle_flags.fill_(warp.sim.model.PARTICLE_FLAG_ACTIVE.value)
max_width = wp.array((-inf,), dtype=float)
wp.launch(
query_max_value_kernel,
dim=model.particle_count,
inputs=[widths],
outputs=[max_width],
)
model.particle_max_radius = float(max_width.numpy()[0]) * 0.5
# Allocate a single contact per particle.
model.allocate_soft_contacts(model.particle_count)
# Initialize the integrator.
integrator = wp.sim.SemiImplicitIntegrator()
# Set the model properties.
model.ground = db.inputs.groundEnabled
model.gravity = db.inputs.gravity
model.particle_adhesion = db.inputs.particlesContactAdhesion
model.particle_cohesion = db.inputs.particlesContactCohesion
model.particle_ke = db.inputs.contactElasticStiffness * db.inputs.globalScale
model.particle_kf = db.inputs.contactFrictionStiffness * db.inputs.globalScale
model.particle_mu = db.inputs.contactFrictionCoeff
model.particle_kd = db.inputs.contactDampingStiffness * db.inputs.globalScale
model.soft_contact_ke = db.inputs.contactElasticStiffness * db.inputs.globalScale
model.soft_contact_kf = db.inputs.contactFrictionStiffness * db.inputs.globalScale
model.soft_contact_mu = db.inputs.contactFrictionCoeff
model.soft_contact_kd = db.inputs.contactDampingStiffness * db.inputs.globalScale
model.soft_contact_margin = db.inputs.colliderContactDistance * db.inputs.colliderContactQueryRange
# Store the class members.
self.sim_dt = sim_dt
self.sim_tick = 0
self.model = model
self.integrator = integrator
self.state_0 = model.state()
self.state_1 = model.state()
self.xform = xform.copy()
if USE_GRAPH:
# Create the CUDA graph. We first manually load the necessary
# modules to avoid the capture to load all the modules that are
# registered and possibly not relevant.
wp.load_module(device=device)
wp.load_module(module=warp.sim, device=device, recursive=True)
wp.capture_begin(force_module_load=False)
step(db)
self.graph = wp.capture_end()
else:
self.graph = None
self.attr_tracking.update_state(db)
return True
# Compute
# ------------------------------------------------------------------------------
def update_collider(
db: OgnParticlesSimulateDatabase,
) -> None:
"""Updates the collider state."""
state = db.internal_state
points = omni.warp.nodes.mesh_get_points(db.inputs.collider)
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.collider)
# Swap the previous and current collider point positions.
(state.collider_points_0, state.collider_points_1) = (
state.collider_points_1,
state.collider_points_0,
)
# Store the current point positions.
wp.copy(state.collider_points_1, points)
# Retrieve the previous and current world transformations.
xform_0 = state.collider_xform
xform_1 = xform
# Update the internal point positions and velocities.
wp.launch(
kernel=update_collider_kernel,
dim=len(state.collider_mesh.vertices),
inputs=[
state.collider_points_0,
state.collider_points_1,
xform_0.T,
xform_1.T,
state.sim_dt,
],
outputs=[
state.collider_mesh.mesh.points,
state.collider_mesh.mesh.velocities,
],
)
# Refit the BVH.
state.collider_mesh.mesh.refit()
# Update the state members.
state.collider_xform = xform.copy()
def update_particles(
db: OgnParticlesSimulateDatabase,
) -> None:
"""Updates the particles state."""
state = db.internal_state
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.particles)
# Retrieve the previous and current world transformations.
xform_0 = state.xform
xform_1 = xform
# Update the internal point positions and velocities.
wp.launch(
kernel=update_particles_kernel,
dim=len(state.state_0.particle_q),
inputs=[
state.state_0.particle_q,
np.matmul(np.linalg.inv(xform_0), xform_1).T,
],
outputs=[
state.state_0.particle_q,
state.state_0.particle_qd,
],
)
# Update the state members.
state.xform = xform.copy()
def step(db: OgnParticlesSimulateDatabase) -> None:
"""Steps through the simulation."""
state = db.internal_state
sim_dt = state.sim_dt / db.inputs.substepCount
# Run the collision detection once per frame.
wp.sim.collide(state.model, state.state_0)
for _ in range(db.inputs.substepCount):
state.state_0.clear_forces()
state.integrator.simulate(
state.model,
state.state_0,
state.state_1,
sim_dt,
)
# Swap the previous and current states.
(state.state_0, state.state_1) = (state.state_1, state.state_0)
def simulate(db: OgnParticlesSimulateDatabase) -> None:
"""Simulates the particles at the current time."""
state = db.internal_state
state.model.particle_grid.build(
state.state_0.particle_q,
state.model.particle_max_radius * db.inputs.particlesQueryRange,
)
if USE_GRAPH:
wp.capture_launch(state.graph)
else:
step(db)
def compute(db: OgnParticlesSimulateDatabase, device: wp.context.Device) -> None:
"""Evaluates the node."""
if not db.inputs.particles.valid or not db.outputs.particles.valid:
return
state = db.internal_state
if not db.inputs.enabled:
# Pass through the data.
db.outputs.particles = db.inputs.particles
# Store whether the simulation was last enabled.
state.sim_enabled = False
return
if state.needs_initialization(db):
# Initialize the internal state if it hasn't been already.
# We want to use the input particles geometry as the initial state
# of the simulation so we copy its bundle to the output one.
db.outputs.particles = db.inputs.particles
if not state.initialize(db, device):
return
else:
# We skip the simulation if it has just been initialized.
if state.sim_tick == 0 and omni.warp.nodes.bundle_has_changed(db.inputs.particles):
if not state.initialize(db, device):
return
if (
db.inputs.collider.valid
and state.collider_mesh is not None
and omni.warp.nodes.bundle_has_changed(db.inputs.collider)
):
# The collider might be animated so we need to update its state.
update_collider(db)
if omni.warp.nodes.bundle_have_attrs_changed(db.inputs.particles, ("worldMatrix",)):
update_particles(db)
with omni.warp.nodes.NodeTimer("simulate", db, active=PROFILING):
# Run the particles simulation at the current time.
simulate(db)
with omni.warp.nodes.NodeTimer("transform_points_to_local_space", db, active=PROFILING):
# Retrieve some data from the particles points.
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.particles)
# Transform the particles point positions back into local space
# and store them into the bundle.
out_points = omni.warp.nodes.points_get_points(db.outputs.particles)
wp.launch(
kernel=transform_points_kernel,
dim=len(out_points),
inputs=[
state.state_0.particle_q,
np.linalg.inv(xform).T,
],
outputs=[
out_points,
],
)
# Increment the simulation tick.
state.sim_tick += 1
# Store whether the simulation was last enabled.
state.sim_enabled = True
# Store the current time.
state.time = db.inputs.time
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnParticlesSimulate:
"""Node."""
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db: OgnParticlesSimulateDatabase) -> None:
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db, device)
except Exception:
db.log_error(traceback.format_exc())
db.internal_state.is_valid = False
return
db.internal_state.is_valid = True
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnParticlesSimulate.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node converting a volume into a geometry mesh."""
import traceback
import omni.graph.core as og
import warp as wp
import omni.warp.nodes
from omni.warp.nodes.ogn.OgnMeshFromVolumeDatabase import OgnMeshFromVolumeDatabase
PROFILING = False
# Kernels
# ------------------------------------------------------------------------------
@wp.kernel(enable_backward=False)
def transform_points_kernel(
points: wp.array(dtype=wp.vec3),
center: wp.vec3,
scale: wp.vec3,
out_points: wp.array(dtype=wp.vec3),
):
"""Transform the points with the given offset and scale values."""
tid = wp.tid()
pos = points[tid]
pos = pos - center
pos = wp.cw_mul(pos, scale)
out_points[tid] = pos
# Internal State
# ------------------------------------------------------------------------------
class InternalState:
"""Internal state for the node."""
def __init__(self) -> None:
self.mc = None
self.is_valid = False
self.attr_tracking = omni.warp.nodes.AttrTracking(
(
"dim1",
"dim2",
"dim3",
"maxPoints",
"maxTriangles",
),
)
def needs_initialization(self, db: OgnMeshFromVolumeDatabase) -> bool:
"""Checks if the internal state needs to be (re)initialized."""
if not self.is_valid:
return True
if self.attr_tracking.have_attrs_changed(db):
return True
return False
def initialize(self, db: OgnMeshFromVolumeDatabase) -> bool:
"""Initializes the internal state."""
# Initialize Warp's marching cubes helper.
mc = wp.MarchingCubes(
int(db.inputs.dim1),
int(db.inputs.dim2),
int(db.inputs.dim3),
db.inputs.maxPoints,
db.inputs.maxTriangles,
)
# Store the class members.
self.mc = mc
self.attr_tracking.update_state(db)
return True
# Compute
# ------------------------------------------------------------------------------
def compute(db: OgnMeshFromVolumeDatabase) -> None:
"""Evaluates the node."""
db.outputs.mesh.changes().activate()
if not db.inputs.data.memory or db.inputs.data.shape[0] == 0:
return
state = db.internal_state
# Initialize the internal state if it hasn't been already.
if state.needs_initialization(db):
if not state.initialize(db):
return
dims = (db.inputs.dim1, db.inputs.dim2, db.inputs.dim3)
size = dims[0] * dims[1] * dims[2]
if db.inputs.data.shape[0] != size:
raise RuntimeError(
"The length of the input array data doesn't match with "
"the given size: `{} != {}`.".format(db.inputs.data.shape[0], size)
)
# Alias the incoming memory to a Warp array.
data = wp.from_ptr(
db.inputs.data.memory,
size,
dtype=float,
shape=dims,
)
with omni.warp.nodes.NodeTimer("surface_mesh", db, active=PROFILING):
# Let Warp's marching cubes helper generate the mesh surface at
# the given ISO threshold value.
state.mc.surface(data, db.inputs.threshold)
# The generated surface is triangulated, so we have 3 vertices per face.
face_count = int(len(state.mc.indices) / 3)
vertex_count = len(state.mc.indices)
point_count = len(state.mc.verts)
if not point_count or not vertex_count or not face_count:
return
# Warp's marching cubes helper allocates its own arrays to store
# the resulting mesh geometry but, eventually, we need to write that data
# to OmniGraph, so we create a new geometry mesh within the output bundle.
omni.warp.nodes.mesh_create_bundle(
db.outputs.mesh,
point_count,
vertex_count,
face_count,
xform=db.inputs.transform,
)
out_points = omni.warp.nodes.mesh_get_points(db.outputs.mesh)
out_face_vertex_counts = omni.warp.nodes.mesh_get_face_vertex_counts(
db.outputs.mesh,
)
out_face_vertex_indices = omni.warp.nodes.mesh_get_face_vertex_indices(
db.outputs.mesh,
)
# Copy the data to the output geometry mesh bundle.
wp.copy(out_points, state.mc.verts)
wp.copy(out_face_vertex_indices, state.mc.indices)
# Set all faces to be triangles.
out_face_vertex_counts.fill_(3)
# Transform the mesh to fit the given center and size values.
center = (
dims[0] * 0.5,
dims[1] * 0.5,
dims[2] * 0.5,
)
scale = (
db.inputs.size[0] / dims[0],
db.inputs.size[1] / dims[1],
db.inputs.size[2] / dims[2],
)
with omni.warp.nodes.NodeTimer("transform_points", db, active=PROFILING):
wp.launch(
transform_points_kernel,
dim=point_count,
inputs=[
state.mc.verts,
center,
scale,
],
outputs=[
out_points,
],
)
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnMeshFromVolume:
"""Node."""
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db: OgnMeshFromVolumeDatabase) -> None:
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.log_error(traceback.format_exc())
db.internal_state.is_valid = False
return
db.internal_state.is_valid = True
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnMeshFromVolume.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node collection and private implementation for the corresponding API."""
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node writing a dynamic texture."""
import ctypes
import traceback
import omni.graph.core as og
import omni.warp.nodes
import warp as wp
from omni.warp.nodes.ogn.OgnTextureWriteDatabase import OgnTextureWriteDatabase
try:
import omni.ui as ui
except ImportError:
ui = None
# Internal State
# ------------------------------------------------------------------------------
class InternalState:
"""Internal state for the node."""
def __init__(self) -> None:
self.texture_provider = None
self.is_valid = False
self.attr_tracking = omni.warp.nodes.AttrTracking(
(
"uri",
),
)
def needs_initialization(self, db: OgnTextureWriteDatabase) -> bool:
"""Checks if the internal state needs to be (re)initialized."""
if not self.is_valid:
return True
if self.attr_tracking.have_attrs_changed(db):
return True
return False
def initialize(
self,
db: OgnTextureWriteDatabase,
) -> bool:
"""Initializes the internal state."""
uri = db.inputs.uri
if not uri.startswith("dynamic://"):
return False
texture_provider = ui.DynamicTextureProvider(uri[10:])
# Store the class members.
self.texture_provider = texture_provider
self.attr_tracking.update_state(db)
return True
# Compute
# ------------------------------------------------------------------------------
def compute(db: OgnTextureWriteDatabase) -> None:
"""Evaluates the node."""
if ui is None:
db.log_warning("Cannot write dynamic textures in headless mode.")
return
if not db.inputs.data.memory or db.inputs.data.shape[0] == 0:
return
state = db.internal_state
if state.needs_initialization(db):
# Initialize the internal state if it hasn't been already.
if not state.initialize(db):
return
dim_count = min(max(db.inputs.dimCount, 0), wp.types.ARRAY_MAX_DIMS)
resolution = tuple(max(getattr(db.inputs, "dim{}".format(i + 1)), 0) for i in range(dim_count))
# We need to dereference OG's attribute pointer to get the actual pointer
# to the data.
data_ptr = ctypes.cast(db.inputs.data.memory, ctypes.POINTER(ctypes.c_size_t)).contents.value
# Write the texture to the provider.
state.texture_provider.set_bytes_data_from_gpu(
data_ptr,
resolution,
format=ui.TextureFormat.RGBA32_SFLOAT,
)
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnTextureWrite:
"""Dynamic texture write node."""
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db: OgnTextureWriteDatabase) -> None:
try:
compute(db)
except Exception:
db.log_error(traceback.format_exc())
db.internal_state.is_valid = False
return
db.internal_state.is_valid = True
# Trigger the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnTextureWrite.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Helpers to author mesh geometries represented as OmniGraph bundles."""
from typing import Optional
import numpy as np
import omni.graph.core as og
import warp as wp
from omni.warp.nodes._impl.attributes import (
attr_get,
attr_get_array_on_gpu,
attr_set,
)
from omni.warp.nodes._impl.bundles import (
bundle_copy_attr_value,
bundle_create_attr,
bundle_create_child,
bundle_create_metadata_attr,
bundle_get_attr,
bundle_set_prim_type,
bundle_set_world_xform,
)
from omni.warp.nodes._impl.points import (
points_get_display_color,
points_get_points,
points_get_velocities,
points_get_local_extent,
points_get_world_extent,
)
def mesh_create_bundle(
dst_bundle: og.BundleContents,
point_count: int,
vertex_count: int,
face_count: int,
xform: Optional[np.ndarray] = None,
create_display_color: bool = False,
create_normals: bool = False,
create_uvs: bool = False,
child_idx: int = 0,
) -> None:
"""Creates and initializes mesh attributes within a bundle."""
child_bundle = bundle_create_child(dst_bundle, child_idx)
bundle_create_attr(
child_bundle,
"points",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.POSITION,
),
size=point_count,
)
bundle_create_attr(
child_bundle,
"faceVertexCounts",
og.Type(
og.BaseDataType.INT,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=face_count,
)
bundle_create_attr(
child_bundle,
"faceVertexIndices",
og.Type(
og.BaseDataType.INT,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=vertex_count,
)
bundle_set_prim_type(dst_bundle, "Mesh", child_idx=child_idx)
if xform is not None:
bundle_set_world_xform(dst_bundle, xform, child_idx=child_idx)
if create_display_color:
bundle_create_attr(
child_bundle,
"primvars:displayColor",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.COLOR,
),
size=point_count,
)
interp_attr = bundle_create_metadata_attr(
child_bundle,
"primvars:displayColor",
"interpolation",
og.Type(
og.BaseDataType.TOKEN,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
),
)
attr_set(interp_attr, "vertex")
if create_normals:
bundle_create_attr(
child_bundle,
"normals",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.NORMAL,
),
size=vertex_count,
)
if create_uvs:
bundle_create_attr(
child_bundle,
"primvars:st",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=2,
array_depth=1,
role=og.AttributeRole.TEXCOORD,
),
size=vertex_count,
)
def mesh_copy_bundle(
dst_bundle: og.BundleContents,
src_bundle: og.BundleContents,
deep_copy: bool = False,
child_idx: int = 0,
) -> None:
"""Creates and initializes mesh attributes from an existing bundle."""
dst_child_bundle = bundle_create_child(dst_bundle, child_idx)
src_child_bundle = src_bundle.bundle.get_child_bundle(child_idx)
dst_child_bundle.copy_bundle(src_child_bundle)
if deep_copy:
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "points", wp.vec3)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "faceVertexCounts", int)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "faceVertexIndices", int)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "primvars:displayColor", wp.vec3)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "normals", wp.vec3)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "primvars:st", wp.vec2)
def mesh_get_point_count(
bundle: og.BundleContents,
child_idx: int = 0,
) -> int:
"""Retrieves the number of points."""
return bundle_get_attr(bundle, "points", child_idx).size()
def mesh_get_vertex_count(
bundle: og.BundleContents,
child_idx: int = 0,
) -> int:
"""Retrieves the number of vertices."""
attr = bundle_get_attr(bundle, "faceVertexCounts", child_idx)
return int(np.sum(attr_get(attr)))
def mesh_get_face_count(
bundle: og.BundleContents,
child_idx: int = 0,
) -> int:
"""Retrieves the number of faces."""
return bundle_get_attr(bundle, "faceVertexCounts", child_idx).size()
def mesh_get_points(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec3):
"""Retrieves the bundle points attribute as a Warp array."""
return points_get_points(bundle, child_idx=child_idx)
def mesh_get_velocities(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec3):
"""Retrieves the bundle velocities attribute as a Warp array."""
return points_get_velocities(bundle, child_idx=child_idx)
def mesh_get_normals(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec3):
"""Retrieves the bundle normals attribute as a Warp array."""
attr = bundle_get_attr(bundle, "normals", child_idx)
return attr_get_array_on_gpu(attr, wp.vec3, read_only=bundle.read_only)
def mesh_get_uvs(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec2):
"""Retrieves the bundle UVs attribute as a Warp array."""
attr = bundle_get_attr(bundle, "primvars:st", child_idx)
return attr_get_array_on_gpu(attr, wp.vec2, read_only=bundle.read_only)
def mesh_get_display_color(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec3):
"""Retrieves the bundle display color attribute as a Warp array."""
return points_get_display_color(bundle, child_idx=child_idx)
def mesh_get_face_vertex_counts(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=int):
"""Retrieves the bundle face vertex counts attribute as a Warp array."""
attr = bundle_get_attr(bundle, "faceVertexCounts", child_idx)
return attr_get_array_on_gpu(attr, int, read_only=bundle.read_only)
def mesh_get_face_vertex_indices(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=int):
"""Retrieves the bundle face vertex indices attribute as a Warp array."""
attr = bundle_get_attr(bundle, "faceVertexIndices", child_idx)
return attr_get_array_on_gpu(attr, int, read_only=bundle.read_only)
def mesh_get_local_extent(
bundle: og.BundleContents,
child_idx: int = 0,
) -> np.ndarray:
"""Retrieves the local extent of the geometry mesh."""
return points_get_local_extent(bundle, child_idx=child_idx)
def mesh_get_world_extent(
bundle: og.BundleContents,
axis_aligned: bool = False,
child_idx: int = 0,
) -> np.ndarray:
"""Retrieves the world extent of the geometry mesh."""
return points_get_world_extent(
bundle,
axis_aligned=axis_aligned,
child_idx=child_idx,
)
def mesh_triangulate(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=int):
"""Computes a triangulated version of the face vertex indices."""
counts = mesh_get_face_vertex_counts(bundle, child_idx=child_idx).numpy()
if np.all(counts == 3):
return mesh_get_face_vertex_indices(bundle, child_idx=child_idx)
indices = mesh_get_face_vertex_indices(bundle, child_idx=child_idx).numpy()
tri_face_count = np.sum(np.subtract(counts, 2))
out = np.empty(tri_face_count * 3, dtype=int)
dst_offset = 0
src_offset = 0
for count in counts:
for i in range(count - 2):
out[dst_offset] = indices[src_offset]
out[dst_offset + 1] = indices[src_offset + i + 1]
out[dst_offset + 2] = indices[src_offset + i + 2]
dst_offset += 3
src_offset += count
return wp.array(out, dtype=int, copy=True)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/mesh.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node generating particles inside a mesh."""
import traceback
from typing import Tuple
import numpy as np
import omni.graph.core as og
import warp as wp
import omni.warp.nodes
from omni.warp.nodes.ogn.OgnParticlesFromMeshDatabase import OgnParticlesFromMeshDatabase
PROFILING = False
# Kernels
# ------------------------------------------------------------------------------
@wp.kernel(enable_backward=False)
def transform_points_kernel(
points: wp.array(dtype=wp.vec3),
xform: wp.mat44,
out_points: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
out_points[tid] = wp.transform_point(xform, points[tid])
@wp.kernel(enable_backward=False)
def sample_mesh_kernel(
mesh: wp.uint64,
grid_lower_bound: wp.vec3,
max_points: int,
min_sdf: float,
max_sdf: float,
spacing: float,
spacing_jitter: float,
seed: int,
out_point_count: wp.array(dtype=int),
out_points: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
x, y, z = wp.tid()
# Retrieve the cell's center position.
cell_pos = (
grid_lower_bound
+ wp.vec3(
float(x) + 0.5,
float(y) + 0.5,
float(z) + 0.5,
)
* spacing
)
# Query the closest location on the mesh.
max_dist = 1000.0
sign = float(0.0)
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
if not wp.mesh_query_point(
mesh,
cell_pos,
max_dist,
sign,
face_index,
face_u,
face_v,
):
return
# Evaluates the position of the closest mesh location found.
mesh_pos = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
# Check that the cell's distance to the mesh location is within
# the desired range.
dist = wp.length(cell_pos - mesh_pos) * sign
if dist < min_sdf or dist > max_sdf:
return
# Increment the counter of valid point locations found.
point_index = wp.atomic_add(out_point_count, 0, 1)
if point_index > max_points:
return
# Compute the spacing jitter value while making sure it's normalized
# in a range [-1, 1].
rng = wp.rand_init(seed, tid)
jitter = wp.vec3(
wp.randf(rng) * 2.0 - 1.0,
wp.randf(rng) * 2.0 - 1.0,
wp.randf(rng) * 2.0 - 1.0,
)
# Store the point position.
out_points[point_index] = cell_pos + jitter * spacing_jitter
# Internal State
# ------------------------------------------------------------------------------
class InternalState:
"""Internal state for the node."""
def __init__(self) -> None:
self.mesh = None
self.is_valid = False
self.attr_tracking = omni.warp.nodes.AttrTracking(
(
"transform",
"seed",
"minSdf",
"maxSdf",
"radius",
"spacing",
"spacingJitter",
"mass",
"velocityDir",
"velocityAmount",
"maxPoints",
),
)
def needs_initialization(self, db: OgnParticlesFromMeshDatabase) -> bool:
"""Checks if the internal state needs to be (re)initialized."""
if not self.is_valid:
return True
if omni.warp.nodes.bundle_has_changed(db.inputs.mesh):
return True
return False
def initialize(self, db: OgnParticlesFromMeshDatabase) -> bool:
"""Initializes the internal state."""
point_count = omni.warp.nodes.mesh_get_point_count(db.inputs.mesh)
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.mesh)
# Transform the mesh's point positions into world space.
world_point_positions = wp.empty(point_count, dtype=wp.vec3)
wp.launch(
kernel=transform_points_kernel,
dim=point_count,
inputs=[
omni.warp.nodes.mesh_get_points(db.inputs.mesh),
xform.T,
],
outputs=[
world_point_positions,
],
)
# Initialize Warp's mesh instance, which requires
# a triangulated topology.
face_vertex_indices = omni.warp.nodes.mesh_triangulate(db.inputs.mesh)
mesh = wp.Mesh(
points=world_point_positions,
velocities=wp.zeros(point_count, dtype=wp.vec3),
indices=face_vertex_indices,
)
# Store the class members.
self.mesh = mesh
return True
# Compute
# ------------------------------------------------------------------------------
def spawn_particles(db: OgnParticlesFromMeshDatabase) -> Tuple[wp.array, int]:
"""Spawns the particles by filling the given point positions array."""
# Initialize an empty array that will hold the particle positions.
points = wp.empty(db.inputs.maxPoints, dtype=wp.vec3)
# Retrieve the mesh's aligned bounding box.
extent = omni.warp.nodes.mesh_get_world_extent(
db.inputs.mesh,
axis_aligned=True,
)
# Compute the emitter's bounding box size.
extent_size = extent[1] - extent[0]
# Infer the emitter's grid dimensions from its bounding box size and
# the requested spacing.
spacing = max(db.inputs.spacing, 1e-6)
dims = (extent_size / spacing).astype(int) + 1
dims = np.maximum(dims, 1)
# Add one particle per grid cell located within the mesh geometry.
point_count = wp.zeros(1, dtype=int)
wp.launch(
kernel=sample_mesh_kernel,
dim=dims,
inputs=[
db.internal_state.mesh.id,
extent[0],
db.inputs.maxPoints,
db.inputs.minSdf,
db.inputs.maxSdf,
spacing,
db.inputs.spacingJitter,
db.inputs.seed,
],
outputs=[
point_count,
points,
],
)
# Retrieve the actual number of particles created.
point_count = min(int(point_count.numpy()[0]), db.inputs.maxPoints)
return (points, point_count)
def compute(db: OgnParticlesFromMeshDatabase) -> None:
"""Evaluates the node."""
db.outputs.particles.changes().activate()
if not db.inputs.mesh.valid or not db.outputs.particles.valid:
return
state = db.internal_state
# Initialize the internal state if it hasn't been already.
if state.needs_initialization(db):
if not state.initialize(db):
return
elif not state.attr_tracking.have_attrs_changed(db):
return
with omni.warp.nodes.NodeTimer("spawn_particles", db, active=PROFILING):
# Spawn new particles inside the mesh.
(points, point_count) = spawn_particles(db)
# Create a new geometry points within the output bundle.
omni.warp.nodes.points_create_bundle(
db.outputs.particles,
point_count,
xform=db.inputs.transform,
create_masses=True,
create_velocities=True,
create_widths=True,
)
# Copy the point positions onto the output bundle.
wp.copy(
omni.warp.nodes.points_get_points(db.outputs.particles),
points,
count=point_count,
)
if point_count:
velocities = omni.warp.nodes.points_get_velocities(db.outputs.particles)
if db.inputs.velocityAmount < 1e-6:
velocities.fill_(0.0)
else:
# Retrieve the mesh's world transformation.
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.mesh)
# Retrieve the normalized velocity direction.
vel = db.inputs.velocityDir
vel /= np.linalg.norm(vel)
# Transform the velocity local direction with the mesh's world
# rotation matrix to get the velocity direction in world space.
vel = np.dot(xform[:3, :3].T, vel)
# Scale the result to get the velocity's magnitude.
vel *= db.inputs.velocityAmount
# Store the velocities in the output bundle.
velocities.fill_(wp.vec3(vel))
# Store the radius in the output bundle.
widths = omni.warp.nodes.points_get_widths(db.outputs.particles)
widths.fill_(db.inputs.radius * 2.0)
# Store the mass in the output bundle.
masses = omni.warp.nodes.points_get_masses(db.outputs.particles)
masses.fill_(db.inputs.mass)
state.attr_tracking.update_state(db)
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnParticlesFromMesh:
"""Node."""
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db: OgnParticlesFromMeshDatabase) -> None:
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.log_error(traceback.format_exc())
db.internal_state.is_valid = False
return
db.internal_state.is_valid = True
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnParticlesFromMesh.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node creating a geometry mesh grid."""
import traceback
import numpy as np
import omni.graph.core as og
import warp as wp
import omni.warp.nodes
from omni.warp.nodes._impl.kernels.grid_create import grid_create_launch_kernel
from omni.warp.nodes.ogn.OgnGridCreateDatabase import OgnGridCreateDatabase
PROFILING = False
# Internal State
# ------------------------------------------------------------------------------
class InternalState:
"""Internal state for the node."""
def __init__(self) -> None:
self.is_valid = False
self.attr_tracking = omni.warp.nodes.AttrTracking(
(
"transform",
"size",
"dims",
),
)
# Compute
# ------------------------------------------------------------------------------
def compute(db: OgnGridCreateDatabase) -> None:
"""Evaluates the node."""
db.outputs.mesh.changes().activate()
if not db.outputs.mesh.valid:
return
state = db.internal_state
if state.is_valid and not state.attr_tracking.have_attrs_changed(db):
return
# Compute the mesh's topology counts.
face_count = db.inputs.dims[0] * db.inputs.dims[1]
vertex_count = face_count * 4
point_count = (db.inputs.dims[0] + 1) * (db.inputs.dims[1] + 1)
# Create a new geometry mesh within the output bundle.
omni.warp.nodes.mesh_create_bundle(
db.outputs.mesh,
point_count,
vertex_count,
face_count,
xform=db.inputs.transform,
create_normals=True,
create_uvs=True,
)
with omni.warp.nodes.NodeTimer("grid_create", db, active=PROFILING):
# Evaluate the kernel.
grid_create_launch_kernel(
omni.warp.nodes.mesh_get_points(db.outputs.mesh),
omni.warp.nodes.mesh_get_face_vertex_counts(db.outputs.mesh),
omni.warp.nodes.mesh_get_face_vertex_indices(db.outputs.mesh),
omni.warp.nodes.mesh_get_normals(db.outputs.mesh),
omni.warp.nodes.mesh_get_uvs(db.outputs.mesh),
db.inputs.size.tolist(),
db.inputs.dims.tolist(),
)
state.attr_tracking.update_state(db)
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnGridCreate:
"""Node."""
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db: OgnGridCreateDatabase) -> None:
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.log_error(traceback.format_exc())
db.internal_state.is_valid = False
return
db.internal_state.is_valid = True
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnGridCreate.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""General helpers for this extension."""
from enum import Enum
from typing import (
Any,
Optional,
Union,
)
import omni.graph.core as og
import warp as wp
# General
# ------------------------------------------------------------------------------
class IntEnum(int, Enum):
"""Base class for integer enumerators with labels."""
def __new__(cls, value, label):
obj = int.__new__(cls, value)
obj._value_ = value
obj.label = label
return obj
# Timer
# ------------------------------------------------------------------------------
class NodeTimer(object):
"""Context wrapping Warp's scoped timer for use with nodes."""
def __init__(self, name: str, db: Any, active: bool = False) -> None:
name = "{}:{}".format(db.node.get_prim_path(), name)
self.timer = wp.ScopedTimer(name, active=active, synchronize=True)
def __enter__(self) -> None:
self.timer.__enter__()
return self
def __exit__(self, type: Any, value: Any, traceback: Any) -> None:
self.timer.__exit__(type, value, traceback)
# Types
# ------------------------------------------------------------------------------
_BaseDType = og.BaseDataType
_AttrRole = og.AttributeRole
# fmt: off
_DATA_TYPES_MAPPING = (
("bool" , (_BaseDType.BOOL , 1, _AttrRole.NONE ), "int8" ),
("color3f" , (_BaseDType.FLOAT , 3, _AttrRole.COLOR ), "vec3" ),
("color4f" , (_BaseDType.FLOAT , 4, _AttrRole.COLOR ), "vec4" ),
("double" , (_BaseDType.DOUBLE, 1, _AttrRole.NONE ), "float64"),
("float" , (_BaseDType.FLOAT , 1, _AttrRole.NONE ), "float32"),
("float2" , (_BaseDType.FLOAT , 2, _AttrRole.NONE ), "vec2" ),
("float3" , (_BaseDType.FLOAT , 3, _AttrRole.NONE ), "vec3" ),
("float4" , (_BaseDType.FLOAT , 4, _AttrRole.NONE ), "vec4" ),
("int" , (_BaseDType.INT , 1, _AttrRole.NONE ), "int32" ),
("int64" , (_BaseDType.INT64 , 1, _AttrRole.NONE ), "int64" ),
("matrix2d" , (_BaseDType.DOUBLE, 4, _AttrRole.MATRIX ), "mat22d" ),
("matrix3d" , (_BaseDType.DOUBLE, 9, _AttrRole.MATRIX ), "mat33d" ),
("matrix4d" , (_BaseDType.DOUBLE, 16, _AttrRole.MATRIX ), "mat44d" ),
("normal3f" , (_BaseDType.FLOAT , 3, _AttrRole.NORMAL ), "vec3" ),
("point3f" , (_BaseDType.FLOAT , 3, _AttrRole.POSITION ), "vec3" ),
("quatf" , (_BaseDType.FLOAT , 4, _AttrRole.QUATERNION), "quat" ),
("texCoord2f", (_BaseDType.FLOAT , 2, _AttrRole.TEXCOORD ), "vec2" ),
("texCoord3f", (_BaseDType.FLOAT , 3, _AttrRole.TEXCOORD ), "vec3" ),
("timecode" , (_BaseDType.DOUBLE, 1, _AttrRole.TIMECODE ), "float64"),
("token" , (_BaseDType.TOKEN , 1, _AttrRole.NONE ), "uint64" ),
("uchar" , (_BaseDType.UCHAR , 1, _AttrRole.NONE ), "uint8" ),
("uint" , (_BaseDType.UINT , 1, _AttrRole.NONE ), "uint32" ),
("uint64" , (_BaseDType.UINT64, 1, _AttrRole.NONE ), "uint64" ),
("vector3f" , (_BaseDType.FLOAT , 3, _AttrRole.VECTOR ), "vec3" ),
)
_SDF_DATA_TYPE_TO_OG = {k: v for (k, v, _) in _DATA_TYPES_MAPPING}
_SDF_DATA_TYPE_NAME_TO_WARP = {k: v for (k, _, v) in _DATA_TYPES_MAPPING}
_OG_DATA_TYPE_TO_WARP = {k: v for (_, k, v) in _DATA_TYPES_MAPPING}
# fmt: on
SUPPORTED_OG_DATA_TYPES = tuple(
og.Type(base_data_type, tuple_count=tuple_count, array_depth=0, role=role)
for base_data_type, tuple_count, role in _OG_DATA_TYPE_TO_WARP.keys()
)
SUPPORTED_OG_ARRAY_TYPES = tuple(
og.Type(base_data_type, tuple_count=tuple_count, array_depth=1, role=role)
for base_data_type, tuple_count, role in _OG_DATA_TYPE_TO_WARP.keys()
)
SUPPORTED_OG_TYPES = SUPPORTED_OG_DATA_TYPES + SUPPORTED_OG_ARRAY_TYPES
SUPPORTED_SDF_DATA_TYPE_NAMES = tuple(_SDF_DATA_TYPE_NAME_TO_WARP.keys())
def get_warp_type_from_data_type_name(
data_type_name: str,
dim_count: int = 0,
as_str: bool = False,
str_namespace: Optional[str] = "wp",
):
if as_str:
prefix = "" if str_namespace is None else "{}.".format(str_namespace)
if dim_count == 0:
return "{prefix}{dtype}".format(prefix=prefix, dtype=data_type_name)
if dim_count == 1:
return "{prefix}array(dtype={prefix}{dtype})".format(
prefix=prefix,
dtype=data_type_name,
)
return "{prefix}array(dtype={prefix}{dtype}, ndim={ndim})".format(
prefix=prefix,
dtype=data_type_name,
ndim=dim_count,
)
dtype = getattr(wp.types, data_type_name)
if dim_count == 0:
return dtype
if dim_count == 1:
return wp.array(dtype=dtype)
return wp.array(dtype=dtype, ndim=dim_count)
def type_convert_og_to_warp(
og_type: og.Type,
dim_count: Optional[int] = None,
as_str: bool = False,
str_namespace: Optional[str] = "wp",
) -> Union[Any, str]:
"""Converts an OmniGraph type into a compatible Warp type."""
data_type_name = _OG_DATA_TYPE_TO_WARP.get(
(og_type.base_type, og_type.tuple_count, og_type.role),
)
if data_type_name is None:
raise RuntimeError("Unsupported attribute type '{}'.".format(og_type))
if dim_count is None:
dim_count = og_type.array_depth
return get_warp_type_from_data_type_name(
data_type_name,
dim_count=dim_count,
as_str=as_str,
str_namespace=str_namespace,
)
def type_convert_sdf_name_to_warp(
sdf_type_name: str,
dim_count: Optional[int] = None,
as_str: bool = False,
str_namespace: Optional[str] = "wp",
) -> Union[Any, str]:
"""Converts a Sdf type name into a compatible Warp type."""
if sdf_type_name.endswith("[]"):
sdf_type_name = sdf_type_name[:-2]
if dim_count is None:
dim_count = 1
elif dim_count is None:
dim_count = 0
data_type_name = _SDF_DATA_TYPE_NAME_TO_WARP.get(sdf_type_name)
if data_type_name is None:
raise RuntimeError("Unsupported attribute type '{}'.".format(sdf_type_name))
return get_warp_type_from_data_type_name(
data_type_name,
dim_count=dim_count,
as_str=as_str,
str_namespace=str_namespace,
)
def type_convert_sdf_name_to_og(
sdf_type_name: str,
is_array: Optional[bool] = None,
) -> og.Type:
"""Converts a Sdf type name into its corresponding OmniGraph type."""
if sdf_type_name.endswith("[]"):
sdf_type_name = sdf_type_name[:-2]
if is_array is None:
is_array = True
elif is_array is None:
is_array = False
data_type = _SDF_DATA_TYPE_TO_OG.get(sdf_type_name)
if data_type is None:
raise RuntimeError("Unsupported attribute type '{}'.".format(sdf_type_name))
base_data_type, tuple_count, role = data_type
return og.Type(
base_data_type,
tuple_count=tuple_count,
array_depth=int(is_array),
role=role,
)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/common.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node creating a grid geometry simulated with a wave equation solver."""
from math import sqrt
import traceback
import numpy as np
import omni.graph.core as og
import omni.timeline
import warp as wp
import omni.warp.nodes
from omni.warp.nodes._impl.kernels.grid_create import grid_create_launch_kernel
from omni.warp.nodes.ogn.OgnWaveSolveDatabase import OgnWaveSolveDatabase
PROFILING = False
# Kernels
# -----------------------------------------------------------------------------
@wp.func
def sample_height(
height_map: wp.array(dtype=float),
x: int,
z: int,
point_count_x: int,
point_count_z: int,
):
# Clamp to the grid's bounds.
x = wp.clamp(x, 0, point_count_x - 1)
z = wp.clamp(z, 0, point_count_z - 1)
return height_map[z * point_count_x + x]
@wp.func
def laplacian(
height_map: wp.array(dtype=float),
x: int,
z: int,
point_count_x: int,
point_count_z: int,
):
# See https://en.wikipedia.org/wiki/Wave_equation.
ddx = (
sample_height(height_map, x + 1, z, point_count_x, point_count_z)
- sample_height(height_map, x, z, point_count_x, point_count_z) * 2.0
+ sample_height(height_map, x - 1, z, point_count_x, point_count_z)
)
ddz = (
sample_height(height_map, x, z + 1, point_count_x, point_count_z)
- sample_height(height_map, x, z, point_count_x, point_count_z) * 2.0
+ sample_height(height_map, x, z - 1, point_count_x, point_count_z)
)
return ddx + ddz
@wp.kernel(enable_backward=False)
def displace_kernel(
point_count_x: int,
center_x: float,
center_z: float,
radius: float,
amplitude: float,
time: float,
out_height_map_0: wp.array(dtype=float),
out_height_map_1: wp.array(dtype=float),
):
tid = wp.tid()
x = tid % point_count_x
z = tid // point_count_x
dx = float(x) - center_x
dz = float(z) - center_z
dist_sq = float(dx * dx + dz * dz)
if dist_sq < radius * radius:
height = amplitude * wp.sin(time)
out_height_map_0[tid] = height
out_height_map_1[tid] = height
@wp.kernel(enable_backward=False)
def simulate_kernel(
point_count_x: int,
point_count_z: int,
inv_cell_size: float,
speed: float,
damping: float,
dt: float,
height_map_1: wp.array(dtype=float),
out_height_map_0: wp.array(dtype=float),
):
tid = wp.tid()
x = tid % point_count_x
z = tid // point_count_x
d = laplacian(height_map_1, x, z, point_count_x, point_count_z)
d *= inv_cell_size * inv_cell_size
# Integrate and write the result in the 'previous' height map buffer since
# it will be then swapped to become the 'current' one.
h0 = out_height_map_0[tid]
h1 = height_map_1[tid]
out_height_map_0[tid] = h1 * 2.0 - h0 + (d * speed - (h1 - h0) * damping) * dt * dt
@wp.kernel(enable_backward=False)
def update_mesh_kernel(
height_map: wp.array(dtype=float),
out_points: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
height = height_map[tid]
pos = out_points[tid]
out_points[tid] = wp.vec3(pos[0], height, pos[2])
# Internal State
# ------------------------------------------------------------------------------
class InternalState:
"""Internal state for the node."""
def __init__(self) -> None:
self.height_map_0 = None
self.height_map_1 = None
self.time = 0.0
self.is_valid = False
self.attr_tracking = omni.warp.nodes.AttrTracking(
(
"size",
"cellSize",
),
)
def needs_initialization(self, db: OgnWaveSolveDatabase) -> bool:
"""Checks if the internal state needs to be (re)initialized."""
if not self.is_valid:
return True
if self.attr_tracking.have_attrs_changed(db):
return True
if db.inputs.time < self.time:
# Reset the simulation when we're rewinding.
return True
return False
def initialize(
self,
db: OgnWaveSolveDatabase,
dims: np.ndarray,
) -> bool:
"""Initializes the internal state."""
point_count = omni.warp.nodes.mesh_get_point_count(db.outputs.mesh)
# Initialize a double buffering for the height map.
height_map_0 = wp.zeros(point_count, dtype=float)
height_map_1 = wp.zeros(point_count, dtype=float)
# Build the grid mesh.
grid_create_launch_kernel(
omni.warp.nodes.mesh_get_points(db.outputs.mesh),
omni.warp.nodes.mesh_get_face_vertex_counts(db.outputs.mesh),
omni.warp.nodes.mesh_get_face_vertex_indices(db.outputs.mesh),
omni.warp.nodes.mesh_get_normals(db.outputs.mesh),
omni.warp.nodes.mesh_get_uvs(db.outputs.mesh),
db.inputs.size.tolist(),
dims.tolist(),
update_topology=True,
)
# Store the class members.
self.height_map_0 = height_map_0
self.height_map_1 = height_map_1
self.attr_tracking.update_state(db)
return True
# Compute
# ------------------------------------------------------------------------------
def displace(
db: OgnWaveSolveDatabase,
dims: np.ndarray,
cell_size: np.ndarray,
) -> None:
"""Displaces the height map with the collider."""
state = db.internal_state
# Retrieve some data from the grid mesh.
xform = omni.warp.nodes.bundle_get_world_xform(db.outputs.mesh)
# Retrieve some data from the collider mesh.
collider_xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.collider)
collider_extent = omni.warp.nodes.mesh_get_world_extent(
db.inputs.collider,
axis_aligned=True,
)
# Retrieve the collider's position in the grid's object space.
collider_pos = np.pad(collider_xform[3][:3], (0, 1), constant_values=1)
collider_pos = np.dot(np.linalg.inv(xform).T, collider_pos)
# Compute the collider's radius.
collider_radius = np.amax(collider_extent[1] - collider_extent[0]) * 0.5
# Determine the point around which the grid will be displaced.
center_x = (dims[0] + 1) * 0.5 - float(collider_pos[0]) / cell_size[0]
center_z = (dims[1] + 1) * 0.5 - float(collider_pos[2]) / cell_size[1]
# Clamp the deformation center to the grid's bounds.
center_x = max(0, min(dims[0], center_x))
center_z = max(0, min(dims[1], center_z))
# Apply the displacement if the collider is in contact with the grid.
contact_radius_sq = (collider_radius**2) - (abs(collider_pos[1]) ** 2)
if contact_radius_sq > 0:
cell_size_uniform = (cell_size[0] + cell_size[1]) * 0.5
center_radius = sqrt(contact_radius_sq) / cell_size_uniform
wp.launch(
kernel=displace_kernel,
dim=omni.warp.nodes.mesh_get_point_count(db.outputs.mesh),
inputs=[
dims[0] + 1,
center_x,
center_z,
center_radius,
db.inputs.amplitude,
db.inputs.time,
],
outputs=[
state.height_map_0,
state.height_map_1,
],
)
def simulate(
db: OgnWaveSolveDatabase,
dims: np.ndarray,
cell_size: np.ndarray,
sim_dt: bool,
) -> None:
"""Solves the wave simulation."""
state = db.internal_state
cell_size_uniform = (cell_size[0] + cell_size[1]) * 0.5
wp.launch(
kernel=simulate_kernel,
dim=omni.warp.nodes.mesh_get_point_count(db.outputs.mesh),
inputs=[
dims[0] + 1,
dims[1] + 1,
1.0 / cell_size_uniform,
db.inputs.speed,
db.inputs.damping,
sim_dt,
state.height_map_1,
],
outputs=[
state.height_map_0,
],
)
# Swap the height map buffers
state.height_map_0, state.height_map_1 = (
state.height_map_1,
state.height_map_0,
)
def update_mesh(db: OgnWaveSolveDatabase) -> None:
"""Updates the output grid mesh."""
state = db.internal_state
wp.launch(
kernel=update_mesh_kernel,
dim=omni.warp.nodes.mesh_get_point_count(db.outputs.mesh),
inputs=[
state.height_map_1,
],
outputs=[
omni.warp.nodes.mesh_get_points(db.outputs.mesh),
],
)
def compute(db: OgnWaveSolveDatabase) -> None:
"""Evaluates the node."""
db.outputs.mesh.changes().activate()
if not db.outputs.mesh.valid:
return
state = db.internal_state
# Compute the number of divisions.
dims = (db.inputs.size / db.inputs.cellSize).astype(int)
# Compute the mesh's topology counts.
face_count = dims[0] * dims[1]
vertex_count = face_count * 4
point_count = (dims[0] + 1) * (dims[1] + 1)
# Create a new geometry mesh within the output bundle.
omni.warp.nodes.mesh_create_bundle(
db.outputs.mesh,
point_count,
vertex_count,
face_count,
xform=db.inputs.transform,
create_normals=True,
create_uvs=True,
)
if state.needs_initialization(db):
# Initialize the internal state if it hasn't been already.
if not state.initialize(db, dims):
return
else:
# We skip the simulation if it has just been initialized.
# Retrieve the simulation's delta time.
timeline = omni.timeline.get_timeline_interface()
sim_rate = timeline.get_ticks_per_second()
sim_dt = 1.0 / sim_rate
# Infer the size of each cell from the overall grid size and the number
# of dimensions.
cell_size = db.inputs.size / dims
if db.inputs.collider.valid:
with omni.warp.nodes.NodeTimer("displace", db, active=PROFILING):
# Deform the grid with a displacement value if the collider
# is in contact with it.
displace(db, dims, cell_size)
with omni.warp.nodes.NodeTimer("simulate", db, active=PROFILING):
# Simulate the ripples using the wave equation.
simulate(db, dims, cell_size, sim_dt)
with omni.warp.nodes.NodeTimer("update_mesh", db, active=PROFILING):
# Update the mesh points with the height map resulting from
# the displacement and simulation steps.
update_mesh(db)
# Store the current time.
state.time = db.inputs.time
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnWaveSolve:
"""Node."""
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db: OgnWaveSolveDatabase) -> None:
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.log_error(traceback.format_exc())
db.internal_state.is_valid = False
return
db.internal_state.is_valid = True
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnWaveSolve.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Node simulating cloth."""
import traceback
import numpy as np
import omni.graph.core as og
import omni.timeline
import warp as wp
import omni.warp.nodes
from omni.warp.nodes.ogn.OgnClothSimulateDatabase import OgnClothSimulateDatabase
USE_GRAPH = True
PROFILING = False
# Kernels
# ------------------------------------------------------------------------------
@wp.kernel(enable_backward=False)
def transform_points_kernel(
points: wp.array(dtype=wp.vec3),
xform: wp.mat44,
out_points: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
out_points[tid] = wp.transform_point(xform, points[tid])
@wp.kernel(enable_backward=False)
def update_collider_kernel(
points_0: wp.array(dtype=wp.vec3),
points_1: wp.array(dtype=wp.vec3),
xform_0: wp.mat44,
xform_1: wp.mat44,
sim_dt: float,
out_points: wp.array(dtype=wp.vec3),
out_velocities: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
point_0 = wp.transform_point(xform_0, points_0[tid])
point_1 = wp.transform_point(xform_1, points_1[tid])
out_points[tid] = point_0
out_velocities[tid] = (point_1 - point_0) / sim_dt
@wp.kernel(enable_backward=False)
def update_cloth_kernel(
points_0: wp.array(dtype=wp.vec3),
xform: wp.mat44,
out_points: wp.array(dtype=wp.vec3),
out_velocities: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
point = wp.transform_point(xform, points_0[tid])
diff = point - points_0[tid]
out_points[tid] = point
out_velocities[tid] = out_velocities[tid] + diff
@wp.kernel
def update_contacts_kernel(
points: wp.array(dtype=wp.vec3),
velocities: wp.array(dtype=wp.vec3),
sim_dt: float,
out_points: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
out_points[tid] = points[tid] + velocities[tid] * sim_dt
# Internal State
# ------------------------------------------------------------------------------
class InternalState:
"""Internal state for the node."""
def __init__(self) -> None:
self.sim_dt = None
self.sim_tick = None
self.model = None
self.integrator = None
self.state_0 = None
self.state_1 = None
self.xform = None
self.collider_xform = None
self.collider_mesh = None
self.collider_points_0 = None
self.collider_points_1 = None
self.graph = None
self.sim_enabled = True
self.time = 0.0
self.is_valid = False
self.attr_tracking = omni.warp.nodes.AttrTracking(
(
"substepCount",
"gravity",
"globalScale",
"contactElasticStiffness",
"contactFrictionStiffness",
"contactFrictionCoeff",
"contactDampingStiffness",
"clothDensity",
"clothTriElasticStiffness",
"clothTriAreaStiffness",
"clothTriDampingStiffness",
"clothEdgeBendingStiffness",
"clothEdgeDampingStiffness",
"colliderContactDistance",
"colliderContactQueryRange",
"groundEnabled",
"groundAltitude",
),
)
def needs_initialization(self, db: OgnClothSimulateDatabase) -> bool:
"""Checks if the internal state needs to be (re)initialized."""
if not self.is_valid or not db.inputs.enabled or not self.sim_enabled:
return True
if self.attr_tracking.have_attrs_changed(db):
return True
if db.inputs.time < self.time:
# Reset the simulation when we're rewinding.
return True
return False
def initialize(
self,
db: OgnClothSimulateDatabase,
device: wp.context.Device,
) -> bool:
"""Initializes the internal state."""
# Lazy load warp.sim here to not slow down extension loading.
import warp.sim
# Compute the simulation time step.
timeline = omni.timeline.get_timeline_interface()
sim_rate = timeline.get_ticks_per_second()
sim_dt = 1.0 / sim_rate
# Initialize Warp's simulation model builder.
builder = wp.sim.ModelBuilder()
# Retrieve some data from the cloth mesh.
points = omni.warp.nodes.mesh_get_points(db.inputs.cloth)
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.cloth)
# Transform the cloth point positions into world space.
world_points = wp.empty(len(points), dtype=wp.vec3)
wp.launch(
kernel=transform_points_kernel,
dim=len(points),
inputs=[
points,
xform.T,
],
outputs=[
world_points,
],
)
# Register the cloth geometry mesh into Warp's simulation model builder,
# which requires triangulated meshes.
face_vertex_indices = omni.warp.nodes.mesh_triangulate(db.inputs.cloth)
builder.add_cloth_mesh(
pos=(0.0, 0.0, 0.0),
rot=(0.0, 0.0, 0.0, 1.0),
scale=1.0,
vel=(0.0, 0.0, 0.0),
vertices=world_points.numpy(),
indices=face_vertex_indices.numpy(),
density=db.inputs.clothDensity,
tri_ke=db.inputs.clothTriElasticStiffness * db.inputs.globalScale,
tri_ka=db.inputs.clothTriAreaStiffness * db.inputs.globalScale,
tri_kd=db.inputs.clothTriDampingStiffness * db.inputs.globalScale,
edge_ke=db.inputs.clothEdgeBendingStiffness * db.inputs.globalScale,
edge_kd=db.inputs.clothEdgeDampingStiffness * db.inputs.globalScale,
)
# Set a uniform mass to avoid large discrepencies.
avg_mass = np.mean(builder.particle_mass)
builder.particle_mass = np.full(
(len(builder.particle_mass),),
avg_mass,
)
if db.inputs.collider.valid:
# Retrieve some data from the collider mesh.
collider_points = omni.warp.nodes.mesh_get_points(db.inputs.collider)
collider_xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.collider)
# Transform the collider point position into world space.
collider_world_points = wp.empty(
len(collider_points),
dtype=wp.vec3,
)
wp.launch(
kernel=transform_points_kernel,
dim=len(collider_points),
inputs=[
collider_points,
collider_xform.T,
],
outputs=[
collider_world_points,
],
)
# Initialize Warp's mesh instance, which requires
# triangulated meshes.
collider_face_vertex_indices = omni.warp.nodes.mesh_triangulate(
db.inputs.collider,
)
collider_mesh = wp.sim.Mesh(
collider_world_points.numpy(),
collider_face_vertex_indices.numpy(),
compute_inertia=False,
)
# Register the collider geometry mesh into Warp's simulation model
# builder.
builder.add_shape_mesh(
body=-1,
mesh=collider_mesh,
pos=(0.0, 0.0, 0.0),
rot=(0.0, 0.0, 0.0, 1.0),
scale=(1.0, 1.0, 1.0),
density=0.0,
ke=0.0,
kd=0.0,
kf=0.0,
mu=0.0,
)
# Store the collider's point positions as internal state.
collider_points_0 = wp.empty_like(collider_points)
collider_points_1 = wp.empty_like(collider_points)
wp.copy(collider_points_0, collider_points)
wp.copy(collider_points_1, collider_points)
# Store the class members.
self.collider_xform = collider_xform.copy()
self.collider_mesh = collider_mesh
self.collider_points_0 = collider_points_0
self.collider_points_1 = collider_points_1
else:
self.collider_mesh = None
# Register the ground.
builder.set_ground_plane(
offset=-db.inputs.groundAltitude + db.inputs.colliderContactDistance,
ke=db.inputs.contactElasticStiffness * db.inputs.globalScale,
kd=db.inputs.contactDampingStiffness * db.inputs.globalScale,
kf=db.inputs.contactFrictionStiffness * db.inputs.globalScale,
mu=db.inputs.contactFrictionCoeff,
)
# Build the simulation model.
model = builder.finalize()
# Allocate a single contact per particle.
model.allocate_soft_contacts(model.particle_count)
# Initialize the integrator.
integrator = wp.sim.SemiImplicitIntegrator()
# Set the model properties.
model.ground = db.inputs.groundEnabled
model.gravity = db.inputs.gravity
model.soft_contact_ke = db.inputs.contactElasticStiffness * db.inputs.globalScale
model.soft_contact_kf = db.inputs.contactFrictionStiffness * db.inputs.globalScale
model.soft_contact_mu = db.inputs.contactFrictionCoeff
model.soft_contact_kd = db.inputs.contactDampingStiffness * db.inputs.globalScale
model.soft_contact_margin = db.inputs.colliderContactDistance * db.inputs.colliderContactQueryRange
model.particle_radius.fill_(db.inputs.colliderContactDistance)
# Store the class members.
self.sim_dt = sim_dt
self.sim_tick = 0
self.model = model
self.integrator = integrator
self.state_0 = model.state()
self.state_1 = model.state()
self.xform = xform.copy()
if USE_GRAPH:
# Create the CUDA graph. We first manually load the necessary
# modules to avoid the capture to load all the modules that are
# registered and possibly not relevant.
wp.load_module(device=device)
wp.load_module(module=warp.sim, device=device, recursive=True)
wp.capture_begin(force_module_load=False)
step(db)
self.graph = wp.capture_end()
else:
self.graph = None
self.attr_tracking.update_state(db)
return True
# Compute
# ------------------------------------------------------------------------------
def update_collider(
db: OgnClothSimulateDatabase,
) -> None:
"""Updates the collider state."""
state = db.internal_state
points = omni.warp.nodes.mesh_get_points(db.inputs.collider)
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.collider)
# Swap the previous and current collider point positions.
(state.collider_points_0, state.collider_points_1) = (
state.collider_points_1,
state.collider_points_0,
)
# Store the current point positions.
wp.copy(state.collider_points_1, points)
# Retrieve the previous and current world transformations.
xform_0 = state.collider_xform
xform_1 = xform
# Update the internal point positions and velocities.
wp.launch(
kernel=update_collider_kernel,
dim=len(state.collider_mesh.vertices),
inputs=[
state.collider_points_0,
state.collider_points_1,
xform_0.T,
xform_1.T,
state.sim_dt,
],
outputs=[
state.collider_mesh.mesh.points,
state.collider_mesh.mesh.velocities,
],
)
# Refit the BVH.
state.collider_mesh.mesh.refit()
# Update the state members.
state.collider_xform = xform.copy()
def update_cloth(
db: OgnClothSimulateDatabase,
) -> None:
"""Updates the cloth state."""
state = db.internal_state
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.cloth)
# Retrieve the previous and current world transformations.
xform_0 = state.xform
xform_1 = xform
# Update the internal point positions and velocities.
wp.launch(
kernel=update_cloth_kernel,
dim=len(state.state_0.particle_q),
inputs=[
state.state_0.particle_q,
np.matmul(np.linalg.inv(xform_0), xform_1).T,
],
outputs=[
state.state_0.particle_q,
state.state_0.particle_qd,
],
)
# Update the state members.
state.xform = xform.copy()
def step(db: OgnClothSimulateDatabase) -> None:
"""Steps through the simulation."""
state = db.internal_state
sim_dt = state.sim_dt / db.inputs.substepCount
# Run the collision detection once per frame.
wp.sim.collide(state.model, state.state_0)
for _ in range(db.inputs.substepCount):
state.state_0.clear_forces()
wp.launch(
update_contacts_kernel,
state.model.soft_contact_max,
inputs=[
state.model.soft_contact_body_pos,
state.model.soft_contact_body_vel,
sim_dt,
],
outputs=[
state.model.soft_contact_body_pos,
],
)
state.integrator.simulate(
state.model,
state.state_0,
state.state_1,
sim_dt,
)
# Swap the previous and current states.
(state.state_0, state.state_1) = (state.state_1, state.state_0)
def simulate(db: OgnClothSimulateDatabase) -> None:
"""Simulates the cloth at the current time."""
state = db.internal_state
if USE_GRAPH:
wp.capture_launch(state.graph)
else:
step(db)
def compute(db: OgnClothSimulateDatabase, device: wp.context.Device) -> None:
"""Evaluates the node."""
if not db.inputs.cloth.valid or not db.outputs.cloth.valid:
return
state = db.internal_state
if not db.inputs.enabled:
# Pass through the data.
db.outputs.cloth = db.inputs.cloth
# Store whether the simulation was last enabled.
state.sim_enabled = False
return
if state.needs_initialization(db):
# Initialize the internal state if it hasn't been already.
# We want to use the input cloth geometry as the initial state
# of the simulation so we copy its bundle to the output one.
db.outputs.cloth = db.inputs.cloth
if not state.initialize(db, device):
return
else:
# We skip the simulation if it has just been initialized.
if state.sim_tick == 0 and omni.warp.nodes.bundle_has_changed(db.inputs.cloth):
if not state.initialize(db, device):
return
if (
db.inputs.collider.valid
and state.collider_mesh is not None
and omni.warp.nodes.bundle_has_changed(db.inputs.collider)
):
# The collider might be animated so we need to update its state.
update_collider(db)
if omni.warp.nodes.bundle_have_attrs_changed(db.inputs.cloth, ("worldMatrix",)):
update_cloth(db)
with omni.warp.nodes.NodeTimer("simulate", db, active=PROFILING):
# Run the cloth simulation at the current time.
simulate(db)
with omni.warp.nodes.NodeTimer("transform_points_to_local_space", db, active=PROFILING):
# Retrieve some data from the cloth mesh.
xform = omni.warp.nodes.bundle_get_world_xform(db.inputs.cloth)
# Transform the cloth point positions back into local space
# and store them into the bundle.
out_points = omni.warp.nodes.points_get_points(db.outputs.cloth)
wp.launch(
kernel=transform_points_kernel,
dim=len(out_points),
inputs=[
state.state_0.particle_q,
np.linalg.inv(xform).T,
],
outputs=[
out_points,
],
)
# Increment the simulation tick.
state.sim_tick += 1
# Store whether the simulation was last enabled.
state.sim_enabled = True
# Store the current time.
state.time = db.inputs.time
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnClothSimulate:
"""Node."""
@staticmethod
def internal_state() -> InternalState:
return InternalState()
@staticmethod
def compute(db: OgnClothSimulateDatabase) -> None:
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db, device)
except Exception:
db.log_error(traceback.format_exc())
db.internal_state.is_valid = False
return
db.internal_state.is_valid = True
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnClothSimulate.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Helpers to author basis curves geometries represented as OmniGraph bundles."""
from typing import Optional
import numpy as np
import omni.graph.core as og
import warp as wp
from omni.warp.nodes._impl.attributes import (
attr_get_array_on_gpu,
attr_set,
)
from omni.warp.nodes._impl.bundles import (
bundle_copy_attr_value,
bundle_create_attr,
bundle_create_child,
bundle_create_metadata_attr,
bundle_get_attr,
bundle_set_prim_type,
bundle_set_world_xform,
)
from omni.warp.nodes._impl.points import (
points_get_display_color,
points_get_points,
points_get_widths,
points_get_local_extent,
points_get_world_extent,
)
# Public API
# ------------------------------------------------------------------------------
def basis_curves_create_bundle(
dst_bundle: og.BundleContents,
point_count: int,
curve_count: int,
type: Optional[str] = None,
basis: Optional[str] = None,
wrap: Optional[str] = None,
xform: Optional[np.ndarray] = None,
create_display_color: bool = False,
create_widths: bool = False,
child_idx: int = 0,
) -> None:
"""Creates and initializes point cloud attributes within a bundle."""
child_bundle = bundle_create_child(dst_bundle, child_idx)
bundle_create_attr(
child_bundle,
"points",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.POSITION,
),
size=point_count,
)
bundle_create_attr(
child_bundle,
"curveVertexCounts",
og.Type(
og.BaseDataType.INT,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=curve_count,
)
if type is not None:
attr = bundle_create_attr(
child_bundle,
"type",
og.Type(
og.BaseDataType.TOKEN,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
),
)
attr_set(attr, type)
if basis is not None:
attr = bundle_create_attr(
child_bundle,
"basis",
og.Type(
og.BaseDataType.TOKEN,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
),
)
attr_set(attr, basis)
if wrap is not None:
attr = bundle_create_attr(
child_bundle,
"warp",
og.Type(
og.BaseDataType.TOKEN,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
),
)
attr_set(attr, wrap)
bundle_set_prim_type(dst_bundle, "BasisCurves", child_idx=child_idx)
if xform is not None:
bundle_set_world_xform(dst_bundle, xform, child_idx=child_idx)
if create_display_color:
bundle_create_attr(
child_bundle,
"primvars:displayColor",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.COLOR,
),
size=point_count,
)
interp_attr = bundle_create_metadata_attr(
child_bundle,
"primvars:displayColor",
"interpolation",
og.Type(
og.BaseDataType.TOKEN,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
),
)
attr_set(interp_attr, "vertex")
if create_widths:
bundle_create_attr(
child_bundle,
"widths",
og.Type(
og.BaseDataType.FLOAT,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=point_count,
)
def basis_curves_copy_bundle(
dst_bundle: og.BundleContents,
src_bundle: og.BundleContents,
deep_copy: bool = False,
child_idx: int = 0,
) -> None:
"""Creates and initializes points attributes from an existing bundle."""
dst_child_bundle = bundle_create_child(dst_bundle, child_idx)
src_child_bundle = src_bundle.bundle.get_child_bundle(child_idx)
dst_child_bundle.copy_bundle(src_child_bundle)
if deep_copy:
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "points", wp.vec3)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "curveVertexCounts", int)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "primvars:displayColor", wp.vec3)
bundle_copy_attr_value(dst_child_bundle, src_child_bundle, "widths", float)
def basis_curves_get_point_count(
bundle: og.BundleContents,
child_idx: int = 0,
) -> int:
"""Retrieves the number of points."""
return bundle_get_attr(bundle, "points", child_idx).size()
def basis_curves_get_curve_count(
bundle: og.BundleContents,
child_idx: int = 0,
) -> int:
"""Retrieves the number of curves."""
return bundle_get_attr(bundle, "curveVertexCounts", child_idx).size()
def basis_curves_get_points(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec3):
"""Retrieves the bundle points attribute as a Warp array."""
return points_get_points(bundle, child_idx=child_idx)
def basis_curves_get_widths(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=float):
"""Retrieves the bundle widths attribute as a Warp array."""
return points_get_widths(bundle, child_idx=child_idx)
def basis_curves_get_display_color(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=wp.vec3):
"""Retrieves the bundle display color attribute as a Warp array."""
return points_get_display_color(bundle, child_idx=child_idx)
def basis_curves_get_curve_vertex_counts(
bundle: og.BundleContents,
child_idx: int = 0,
) -> wp.array(dtype=int):
"""Retrieves the bundle curve vertex counts attribute as a Warp array."""
attr = bundle_get_attr(bundle, "curveVertexCounts", child_idx)
return attr_get_array_on_gpu(attr, int, read_only=bundle.read_only)
def basis_curves_get_local_extent(
bundle: og.BundleContents,
child_idx: int = 0,
) -> np.ndarray:
"""Retrieves the local extent of the geometry points."""
return points_get_local_extent(bundle, child_idx=child_idx)
def basis_curves_get_world_extent(
bundle: og.BundleContents,
axis_aligned: bool = False,
child_idx: int = 0,
) -> np.ndarray:
"""Retrieves the world extent of the geometry points."""
return points_get_world_extent(
bundle,
axis_aligned=axis_aligned,
child_idx=child_idx,
)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/basis_curves.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Sample node deforming a geometry mesh."""
import traceback
import omni.graph.core as og
import warp as wp
import omni.warp.nodes
from omni.warp.nodes.ogn.OgnSampleMeshDeformDatabase import OgnSampleMeshDeformDatabase
PROFILING = False
# Kernels
# -----------------------------------------------------------------------------
@wp.kernel(enable_backward=False)
def deform_mesh_kernel(
points: wp.array(dtype=wp.vec3),
time: float,
out_points: wp.array(dtype=wp.vec3),
):
"""Kernel to deform a geometry mesh."""
tid = wp.tid()
pos = points[tid]
displacement = wp.vec3(0.0, wp.sin(time + pos[0] * 0.1) * 10.0, 0.0)
out_points[tid] = pos + displacement
# Compute
# ------------------------------------------------------------------------------
def compute(db: OgnSampleMeshDeformDatabase) -> None:
"""Evaluates the node."""
if not db.inputs.mesh.valid or not db.outputs.mesh.valid:
return
# Copy the input geometry mesh bundle and read its contents.
db.outputs.mesh = db.inputs.mesh
# Retrieve the input and output point data.
points = omni.warp.nodes.mesh_get_points(db.inputs.mesh)
out_points = omni.warp.nodes.mesh_get_points(db.outputs.mesh)
with omni.warp.nodes.NodeTimer("deform_mesh", db, active=PROFILING):
# Evaluate the kernel once per point.
wp.launch(
kernel=deform_mesh_kernel,
dim=len(points),
inputs=[
points,
db.inputs.time,
],
outputs=[
out_points,
],
)
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnSampleMeshDeform:
"""Node."""
@staticmethod
def compute(db: OgnSampleMeshDeformDatabase) -> None:
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.log_error(traceback.format_exc())
return
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnSampleMeshDeform.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Sample node generating a procedural volume."""
import traceback
import omni.graph.core as og
import warp as wp
import omni.warp.nodes
from omni.warp.nodes.ogn.OgnSampleProceduralVolumeDatabase import OgnSampleProceduralVolumeDatabase
MIN_RES = 8
PROFILING = False
# Kernels
# ------------------------------------------------------------------------------
@wp.func
def sdf_create_box(pos: wp.vec3, size: wp.vec3):
"""Creates a SDF box primitive."""
# https://iquilezles.org/articles/distfunctions
q = wp.vec3(
wp.abs(pos[0]) - size[0],
wp.abs(pos[1]) - size[1],
wp.abs(pos[2]) - size[2],
)
qp = wp.vec3(wp.max(q[0], 0.0), wp.max(q[1], 0.0), wp.max(q[2], 0.0))
return wp.length(qp) + wp.min(wp.max(q[0], wp.max(q[1], q[2])), 0.0)
@wp.func
def sdf_create_torus(pos: wp.vec3, major_radius: float, minor_radius: float):
"""Creates a SDF torus primitive."""
# https://iquilezles.org/articles/distfunctions
q = wp.vec2(wp.length(wp.vec2(pos[0], pos[2])) - major_radius, pos[1])
return wp.length(q) - minor_radius
@wp.func
def sdf_translate(pos: wp.vec3, offset: wp.vec3):
"""Translates a SDF position vector with an offset."""
return pos - offset
@wp.func
def sdf_rotate(pos: wp.vec3, angles: wp.vec3):
"""Rotates a SDF position vector using Euler angles."""
rot = wp.quat_rpy(
wp.radians(angles[0]),
wp.radians(angles[1]),
wp.radians(angles[2]),
)
return wp.quat_rotate_inv(rot, pos)
@wp.func
def sdf_smooth_min(a: float, b: float, radius: float):
"""Creates a SDF torus primitive."""
# https://iquilezles.org/articles/smin
h = wp.max(radius - wp.abs(a - b), 0.0) / radius
return wp.min(a, b) - h * h * h * radius * (1.0 / 6.0)
@wp.kernel(enable_backward=False)
def generate_volume_kernel(
torus_altitude: float,
torus_major_radius: float,
torus_minor_radius: float,
smooth_min_radius: float,
dim: int,
time: float,
out_data: wp.array3d(dtype=float),
):
"""Kernel to generate a SDF volume based on primitives."""
i, j, k = wp.tid()
# Retrieve the position of the current cell in a normalized [-1, 1] range
# for each dimension.
pos = wp.vec3(
2.0 * ((float(i) + 0.5) / float(dim)) - 1.0,
2.0 * ((float(j) + 0.5) / float(dim)) - 1.0,
2.0 * ((float(k) + 0.5) / float(dim)) - 1.0,
)
box = sdf_create_box(
sdf_translate(pos, wp.vec3(0.0, -0.7, 0.0)),
wp.vec3(0.9, 0.3, 0.9),
)
torus = sdf_create_torus(
sdf_rotate(
sdf_translate(pos, wp.vec3(0.0, torus_altitude, 0.0)),
wp.vec3(wp.sin(time) * 90.0, wp.cos(time) * 45.0, 0.0),
),
torus_major_radius,
torus_minor_radius,
)
out_data[i, j, k] = sdf_smooth_min(box, torus, smooth_min_radius)
# Compute
# ------------------------------------------------------------------------------
def compute(db: OgnSampleProceduralVolumeDatabase) -> None:
"""Evaluates the node."""
# Enforce a minimum dimension or else nothing's left to draw.
dim = max(db.inputs.dim, MIN_RES)
db.outputs.data_size = dim * dim * dim
data = omni.warp.nodes.from_omni_graph(
db.outputs.data,
dtype=float,
shape=(dim, dim, dim),
)
with omni.warp.nodes.NodeTimer("generate_volume", db, active=PROFILING):
wp.launch(
kernel=generate_volume_kernel,
dim=data.shape,
inputs=[
db.inputs.torusAltitude,
db.inputs.torusMajorRadius,
db.inputs.torusMinorRadius,
db.inputs.smoothMinRadius,
dim,
db.inputs.time,
],
outputs=[
data,
],
)
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnSampleProceduralVolume:
"""Node."""
@staticmethod
def compute(db: OgnSampleProceduralVolumeDatabase) -> None:
device = wp.get_device("cuda:0")
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.log_error(traceback.format_exc())
return
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/OgnSampleProceduralVolume.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Warp kernel creating a grid mesh geometry."""
from typing import Tuple
import warp as wp
# Helpers
# -----------------------------------------------------------------------------
@wp.func
def _define_face(
face: int,
vertex_1: int,
vertex_2: int,
vertex_3: int,
vertex_4: int,
out_face_vertex_indices: wp.array(dtype=int),
):
out_face_vertex_indices[face * 4 + 0] = vertex_1
out_face_vertex_indices[face * 4 + 1] = vertex_2
out_face_vertex_indices[face * 4 + 2] = vertex_3
out_face_vertex_indices[face * 4 + 3] = vertex_4
@wp.func
def _set_face_normals(
face: int,
normal: wp.vec3,
out_normals: wp.array(dtype=wp.vec3),
):
out_normals[face * 4 + 0] = normal
out_normals[face * 4 + 1] = normal
out_normals[face * 4 + 2] = normal
out_normals[face * 4 + 3] = normal
@wp.func
def _set_face_uvs(
face: int,
uv_1: wp.vec2,
uv_2: wp.vec2,
uv_3: wp.vec2,
uv_4: wp.vec2,
out_uvs: wp.array(dtype=wp.vec2),
):
out_uvs[face * 4 + 0] = uv_1
out_uvs[face * 4 + 1] = uv_2
out_uvs[face * 4 + 2] = uv_3
out_uvs[face * 4 + 3] = uv_4
# Kernel
# -----------------------------------------------------------------------------
@wp.kernel(enable_backward=False)
def _kernel(
half_size: wp.vec2,
res: wp.vec2i,
update_topology: int,
dt_pos: wp.vec2,
dt_uv: wp.vec2,
out_points: wp.array(dtype=wp.vec3),
out_face_vertex_indices: wp.array(dtype=int),
out_normals: wp.array(dtype=wp.vec3),
out_uvs: wp.array(dtype=wp.vec2),
):
"""Kernel to create a geometry mesh grid."""
tid = wp.tid()
i = int(tid % res[0])
j = int(tid / res[0])
if i == 0 and j == 0:
point = 0
out_points[point] = wp.vec3(
half_size[0],
0.0,
half_size[1],
)
if i == 0:
point = (j + 1) * (res[0] + 1)
out_points[point] = wp.vec3(
half_size[0],
0.0,
half_size[1] - dt_pos[1] * float(j + 1),
)
if j == 0:
point = i + 1
out_points[point] = wp.vec3(
half_size[0] - dt_pos[0] * float(i + 1),
0.0,
half_size[1],
)
point = (j + 1) * (res[0] + 1) + i + 1
out_points[point] = wp.vec3(
half_size[0] - dt_pos[0] * float(i + 1),
0.0,
half_size[1] - dt_pos[1] * float(j + 1),
)
if update_topology:
face = tid
# Face vertex indices.
vertex_4 = point
vertex_3 = vertex_4 - 1
vertex_1 = vertex_3 - res[0]
vertex_2 = vertex_1 - 1
_define_face(face, vertex_1, vertex_2, vertex_3, vertex_4, out_face_vertex_indices)
# Vertex normals.
_set_face_normals(face, wp.vec3(0.0, 1.0, 0.0), out_normals)
# Vertex UVs.
s_0 = 1.0 - dt_uv[0] * float(i)
s_1 = 1.0 - dt_uv[0] * float(i + 1)
t_0 = dt_uv[1] * float(j)
t_1 = dt_uv[1] * float(j + 1)
_set_face_uvs(
face,
wp.vec2(s_1, t_0),
wp.vec2(s_0, t_0),
wp.vec2(s_0, t_1),
wp.vec2(s_1, t_1),
out_uvs,
)
# Launcher
# -----------------------------------------------------------------------------
def grid_create_launch_kernel(
out_points: wp.array,
out_face_vertex_counts: wp.array,
out_face_vertex_indices: wp.array,
out_normals: wp.array,
out_uvs: wp.array,
size: Tuple[float, float],
dims: Tuple[int, int],
update_topology: bool = True,
):
"""Launches the kernel."""
face_count = dims[0] * dims[1]
half_size = (
size[0] * 0.5,
size[1] * 0.5,
)
dt_pos = wp.vec2(
size[0] / float(dims[0]),
size[1] / float(dims[1]),
)
dt_uv = (
1.0 / float(dims[0]),
1.0 / float(dims[1]),
)
wp.launch(
kernel=_kernel,
dim=face_count,
inputs=[
half_size,
dims,
update_topology,
dt_pos,
dt_uv,
],
outputs=[
out_points,
out_face_vertex_indices,
out_normals,
out_uvs,
],
)
out_face_vertex_counts.fill_(4)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/kernels/grid_create.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Shared Warp kernels."""
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/kernels/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Property to edit the file path pointing to the kernel's code."""
from typing import (
Any,
Callable,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import HORIZONTAL_SPACING
import omni.ui as ui
def get_code_file_prop_builder(layout: Any) -> Callable:
"""Builds the function used to create the property."""
def fn(ui_prop: UsdPropertyUiEntry, *args):
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._string_builder(
layout.compute_node_widget.stage,
ui_prop.prop_name,
ui_prop.property_type,
ui_prop.metadata,
prim_paths=(layout.node_prim_path,),
additional_label_kwargs={
"style": {
"alignment": ui.Alignment.RIGHT,
},
},
)
return fn
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/props/codefile.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Properties used by the custom node UI templates.
These are built against the `omni.kit.property.usd` framework and are being
passed to the `build_fn` argument of `CustomLayoutProperty` objects.
"""
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/props/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Property to edit the kernel's source code embedded to the node."""
from typing import (
Any,
Callable,
)
import omni.graph.core as og
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder
from omni.kit.widget.text_editor import TextEditor
from omni.kit.window.property.templates import HORIZONTAL_SPACING
import omni.ui as ui
_DIALOG_TITLE = "Kernel Editor"
_DIALOG_WIDTH = 800
_DIALOG_HEIGHT = 600
_BUTTON_WIDTH = 100
class _State:
"""State object shared across the various handlers."""
def __init__(self, layout: Any):
self.layout = layout
self.dialog = None
self.editor = None
self.code_str_attr = og.Controller.attribute(
"inputs:codeStr",
layout.node,
)
def is_read_only(self) -> bool:
return self.code_str_attr.get_upstream_connection_count() > 0
def _get_save_btn_clicked_handler(state: _State) -> Callable:
def fn():
# Trim the trailing new line character inserted by
# the text editor.
code = state.editor.text[:-1]
# Save the content into the corresponding string attribute.
assert not state.is_read_only()
og.Controller.set(state.code_str_attr, code, update_usd=True)
# Restore the title to its default state.
state.dialog.title = _DIALOG_TITLE
return fn
def _get_edit_btn_clicked_handler(state: _State) -> Callable:
def fn():
read_only = state.is_read_only()
dialog = ui.Window(
_DIALOG_TITLE,
width=_DIALOG_WIDTH,
height=_DIALOG_HEIGHT,
dockPreference=ui.DockPreference.MAIN,
)
with dialog.frame:
with ui.VStack():
state.editor = TextEditor(
syntax=TextEditor.Syntax.PYTHON,
text=og.Controller.get(state.code_str_attr),
read_only=read_only,
)
if not read_only:
with ui.HStack(height=0):
ui.Spacer()
ui.Button(
"Save",
width=_BUTTON_WIDTH,
clicked_fn=_get_save_btn_clicked_handler(state),
tooltip="Save the changes to the code",
)
# Store the dialog widget into the state to avoid having it
# not showing up due to being garbage collected.
state.dialog = dialog
return fn
def get_code_str_prop_builder(layout: Any) -> Callable:
"""Builds the function used to create the property."""
def fn(ui_prop: UsdPropertyUiEntry, *args):
state = _State(layout)
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._create_label(
ui_prop.prop_name,
ui_prop.metadata,
{
"style": {
"alignment": ui.Alignment.RIGHT,
},
},
)
ui.Button(
"View" if state.is_read_only() else "Edit",
width=_BUTTON_WIDTH,
clicked_fn=_get_edit_btn_clicked_handler(state),
tooltip="View/edit the embedded kernel code",
)
return fn
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/props/codestr.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Property to pick the source used to infer an attribute's value."""
from typing import (
Any,
Callable,
Sequence,
Tuple,
)
from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import HORIZONTAL_SPACING
import omni.ui as ui
def get_source_picker_prop_builder(
layout: Any,
sources: Sequence[str],
) -> Callable:
"""Builds the function used to create the property."""
def fn(ui_prop: UsdPropertyUiEntry, *args):
class _Model(TfTokenAttributeModel):
def _get_allowed_tokens(self, _) -> Tuple[str]:
return tuple(sources)
with ui.HStack(spacing=HORIZONTAL_SPACING):
# It is necessary to define a dummy allowed token otherwise
# the code in `UsdPropertiesWidgetBuilder._tftoken_builder()` exits
# before attempting to call our custom model.
metadata = ui_prop.metadata.copy()
metadata.update(
{
"allowedTokens": ("dummy",),
}
)
UsdPropertiesWidgetBuilder.build(
layout.compute_node_widget.stage,
ui_prop.prop_name,
metadata,
ui_prop.property_type,
prim_paths=(layout.node_prim_path,),
additional_label_kwargs={
"style": {
"alignment": ui.Alignment.RIGHT,
},
},
additional_widget_kwargs={
"model_cls": _Model,
},
)
return fn
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/props/sourcepicker.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Property to edit the node attributes based on the kernel's parameters."""
from functools import partial
from typing import (
Any,
Callable,
Sequence,
)
import omni.graph.core as og
import omni.ui as ui
from omni.warp.nodes._impl.kernel import (
ArrayAttributeFormat,
UserAttributeDesc,
UserAttributesEvent,
deserialize_user_attribute_descs,
serialize_user_attribute_descs,
)
from omni.warp.nodes._impl.attributes import (
ATTR_BUNDLE_TYPE,
attr_get_name,
attr_join_name,
)
from omni.warp.nodes._impl.widgets.attributeeditor import AttributeEditor
_BUTTON_WIDTH = 100
class _State:
"""State object shared across the various handlers."""
def __init__(self, layout):
self.layout = layout
self.dialog = None
self.remove_attr_menu = None
def _add_user_attribute_desc(state: _State, desc: UserAttributeDesc) -> None:
data = og.Controller.get(state.layout.user_attr_descs_attr)
descs = deserialize_user_attribute_descs(data)
descs[desc.name] = desc
data = serialize_user_attribute_descs(descs)
og.Controller.set(state.layout.user_attr_descs_attr, data, update_usd=True)
def _remove_user_attribute_desc(
state: _State,
port_type: og.AttributePortType,
base_name: str,
) -> None:
data = og.Controller.get(state.layout.user_attr_descs_attr)
descs = deserialize_user_attribute_descs(data)
name = attr_join_name(port_type, base_name)
descs.pop(name, None)
data = serialize_user_attribute_descs(descs)
og.Controller.set(state.layout.user_attr_descs_attr, data, update_usd=True)
def _get_attribute_creation_handler(state: _State) -> Callable:
def fn(attr_desc: UserAttributeDesc):
if any(attr_get_name(x) == attr_desc.name for x in state.layout.node.get_attributes()):
raise RuntimeError("The attribute '{}' already exists on the node.".format(attr_desc.name))
if attr_desc.array_format == ArrayAttributeFormat.RAW:
attr_type = attr_desc.type
elif attr_desc.array_format == ArrayAttributeFormat.BUNDLE:
attr_type = ATTR_BUNDLE_TYPE
else:
assert False, "Unexpected array attribute format '{}'.".format(
attr_desc.array_format,
)
attr = og.Controller.create_attribute(
state.layout.node,
attr_desc.base_name,
attr_type,
attr_desc.port_type,
)
if attr is None:
raise RuntimeError("Failed to create the attribute '{}'.".format(attr_desc.name))
attr.is_optional_for_compute = attr_desc.optional
# Store the new attribute's description within the node's state.
_add_user_attribute_desc(state, attr_desc)
# Inform the node that a new attribute was created.
og.Controller.set(
state.layout.user_attrs_event_attr,
UserAttributesEvent.CREATED,
)
state.layout.refresh()
return fn
def _get_attribute_removal_handler(state: _State) -> Callable:
def fn(attr):
port_type = attr.get_port_type()
name = attr_get_name(attr)
if not og.Controller.remove_attribute(attr):
return
# Remove that attribute's description from the node's state.
_remove_user_attribute_desc(state, port_type, name)
# Inform the node that an existing attribute was removed.
og.Controller.set(
state.layout.user_attrs_event_attr,
UserAttributesEvent.REMOVED,
)
state.layout.refresh()
return fn
def _get_add_btn_clicked_handler(
state: _State,
supported_types: Sequence[str],
) -> Callable:
def fn():
dialog = AttributeEditor(
supported_types,
_get_attribute_creation_handler(state),
)
# Store the dialog widget into the state to avoid having it
# not showing up due to being garbage collected.
state.dialog = dialog
return fn
def _get_remove_btn_clicked_handler(state: _State) -> Callable:
def fn():
attrs = tuple(x for x in state.layout.node.get_attributes() if x.is_dynamic())
if not attrs:
return
menu = ui.Menu()
with menu:
for attr in attrs:
ui.MenuItem(
attr_get_name(attr),
triggered_fn=partial(
_get_attribute_removal_handler(state),
attr,
),
)
menu.show()
# Store the menu widget into the state to avoid having it
# not showing up due to being garbage collected.
state.remove_attr_menu = menu
return fn
def get_edit_attrs_prop_builder(
layout: Any,
supported_types: Sequence[str],
) -> Callable:
"""Builds the function used to create the property."""
def fn(*args):
state = _State(layout)
with ui.HStack():
ui.Button(
"Add +",
width=_BUTTON_WIDTH,
clicked_fn=_get_add_btn_clicked_handler(state, supported_types),
tooltip="Opens an UI to add a new attribute",
)
ui.Spacer(width=8)
ui.Button(
"Remove -",
width=_BUTTON_WIDTH,
clicked_fn=_get_remove_btn_clicked_handler(state),
tooltip="Opens a menu to remove an existing node attribute",
)
return fn
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/props/editattrs.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:enabled",
"inputs:substepCount",
"inputs:gravity",
"inputs:globalScale",
"inputs:contactElasticStiffness",
"inputs:contactFrictionStiffness",
"inputs:contactFrictionCoeff",
"inputs:contactDampingStiffness",
"inputs:clothDensity",
"inputs:clothTriElasticStiffness",
"inputs:clothTriAreaStiffness",
"inputs:clothTriDampingStiffness",
"inputs:clothEdgeBendingStiffness",
"inputs:clothEdgeDampingStiffness",
"inputs:colliderContactDistance",
"inputs:colliderContactQueryRange",
"inputs:groundEnabled",
"inputs:groundAltitude",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpClothSimulate.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:enabled",
"inputs:substepCount",
"inputs:gravity",
"inputs:globalScale",
"inputs:contactElasticStiffness",
"inputs:contactFrictionStiffness",
"inputs:contactFrictionCoeff",
"inputs:contactDampingStiffness",
"inputs:particlesQueryRange",
"inputs:particlesContactAdhesion",
"inputs:particlesContactCohesion",
"inputs:colliderContactDistance",
"inputs:colliderContactQueryRange",
"inputs:groundEnabled",
"inputs:groundAltitude",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpParticlesSimulate.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from functools import partial
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
import warp as wp
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
"""Finds a prop by its name."""
try:
return next(p for p in props if p.prop_name == name)
except StopIteration:
return None
class CustomLayout:
"""Custom UI for the kernel node."""
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
self.dim_count_attr = og.Controller.attribute(
"inputs:dimCount",
self.node,
)
self.dim_count_attr.register_value_changed_callback(self._handle_dim_count_value_changed)
def _handle_dim_count_value_changed(self, attr: og.Attribute) -> None:
"""Callback for the dimension count attribute value having changed."""
# Redraw the UI to display a different set of attributes depending on
# the dimension count value.
self.refresh()
def refresh(self) -> None:
"""Redraws the UI."""
self.compute_node_widget.rebuild_window()
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
"""Builds the UI."""
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
prop = find_prop(props, "inputs:uri")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
prop = find_prop(props, "inputs:dimCount")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
dim_count = min(
max(
og.Controller.get(self.dim_count_attr),
0,
),
wp.types.ARRAY_MAX_DIMS,
)
for i in range(dim_count):
prop = find_prop(
props,
"inputs:dim{}".format(i + 1),
)
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=(prop.metadata["customData"]["uiName"]),
)
prop = find_prop(props, "inputs:pixelFormat")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpTextureWrite.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:torusAltitude",
"inputs:torusMajorRadius",
"inputs:torusMinorRadius",
"inputs:smoothMinRadius",
"inputs:dim",
"inputs:time",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpSampleProceduralVolume.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:size",
"inputs:dim1",
"inputs:dim2",
"inputs:dim3",
"inputs:maxPoints",
"inputs:maxTriangles",
"inputs:threshold",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpMeshFromVolume.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Templates defining custom node UIs.
These override the default behaviour from OmniGraph where widgets are
automatically generated based on the attributes defined in the node's
`.ogn` file.
"""
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:size",
"inputs:dims",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpGridCreate.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = ("inputs:time",)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpSampleMeshDeform.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:seed",
"inputs:minSdf",
"inputs:maxSdf",
"inputs:radius",
"inputs:spacing",
"inputs:spacingJitter",
"inputs:mass",
"inputs:velocityDir",
"inputs:velocityAmount",
"inputs:maxPoints",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpParticlesFromMesh.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from functools import partial
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
import warp as wp
from omni.warp.nodes._impl.common import SUPPORTED_SDF_DATA_TYPE_NAMES
from omni.warp.nodes._impl.kernel import EXPLICIT_SOURCE
from omni.warp.nodes._impl.attributes import (
attr_get_base_name,
attr_get_name,
)
from omni.warp.nodes._impl.props.codefile import get_code_file_prop_builder
from omni.warp.nodes._impl.props.codestr import get_code_str_prop_builder
from omni.warp.nodes._impl.props.editattrs import get_edit_attrs_prop_builder
from omni.warp.nodes._impl.props.sourcepicker import get_source_picker_prop_builder
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
"""Finds a prop by its name."""
try:
return next(p for p in props if p.prop_name == name)
except StopIteration:
return None
class CustomLayout:
"""Custom UI for the kernel node."""
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
self.dim_source_attr = og.Controller.attribute(
"inputs:dimSource",
self.node,
)
self.dim_count_attr = og.Controller.attribute(
"inputs:dimCount",
self.node,
)
self.code_provider_attr = og.Controller.attribute(
"inputs:codeProvider",
self.node,
)
self.user_attr_descs_attr = og.Controller.attribute(
"state:userAttrDescs",
self.node,
)
self.user_attrs_event_attr = og.Controller.attribute(
"state:userAttrsEvent",
self.node,
)
self.node.register_on_connected_callback(self._handle_node_attr_connected)
self.node.register_on_disconnected_callback(self._handle_node_attr_disconnected)
self.dim_source_attr.register_value_changed_callback(self._handle_dim_source_value_changed)
self.dim_count_attr.register_value_changed_callback(self._handle_dim_count_value_changed)
self.code_provider_attr.register_value_changed_callback(self._handle_code_provider_value_changed)
def _handle_node_attr_connected(
self,
attr_from: og.Attribute,
attr_to: og.Attribute,
) -> None:
"""Callback for a node attribute having been disconnected."""
if attr_get_name(attr_to) == "inputs:codeStr":
# Redraw the UI to update the view/edit code button label.
self.refresh()
def _handle_node_attr_disconnected(
self,
attr_from: og.Attribute,
attr_to: og.Attribute,
) -> None:
"""Callback for a node attribute having been disconnected."""
if attr_get_name(attr_to) == "inputs:codeStr":
# Redraw the UI to update the view/edit code button label.
self.refresh()
def _handle_dim_source_value_changed(self, attr: og.Attribute) -> None:
"""Callback for the dimension source attribute value having changed."""
# Redraw the UI to display a different set of attributes depending on
# the dimension source value.
self.refresh()
def _handle_dim_count_value_changed(self, attr: og.Attribute) -> None:
"""Callback for the dimension count attribute value having changed."""
# Redraw the UI to display a different set of attributes depending on
# the dimension count value.
self.refresh()
def _handle_code_provider_value_changed(self, attr: og.Attribute) -> None:
"""Callback for the code provider attribute value having changed."""
# Redraw the UI to display a different set of attributes depending on
# the code provider value.
self.refresh()
def refresh(self) -> None:
"""Redraws the UI."""
self.compute_node_widget.rebuild_window()
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
"""Builds the UI."""
input_array_attrs = tuple(
x
for x in self.node.get_attributes()
if (
x.is_dynamic()
and x.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT
and x.get_resolved_type().array_depth > 0
)
)
dim_sources = (EXPLICIT_SOURCE,) + tuple(attr_get_base_name(x) for x in input_array_attrs)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Add and Remove Attributes"):
CustomLayoutProperty(
None,
display_name=None,
build_fn=get_edit_attrs_prop_builder(
self,
SUPPORTED_SDF_DATA_TYPE_NAMES,
),
)
with CustomLayoutGroup("Inputs"):
prop = find_prop(props, "inputs:device")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
prop = find_prop(props, "inputs:dimSource")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
build_fn=partial(
get_source_picker_prop_builder(
self,
dim_sources,
),
prop,
),
)
dim_source = og.Controller.get(self.dim_source_attr)
if dim_source == EXPLICIT_SOURCE:
prop = find_prop(props, "inputs:dimCount")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
dim_count = min(
max(
og.Controller.get(self.dim_count_attr),
0,
),
wp.types.ARRAY_MAX_DIMS,
)
for i in range(dim_count):
prop = find_prop(props, "inputs:dim{}".format(i + 1))
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
prop = find_prop(props, "inputs:codeProvider")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
code_provider = og.Controller.get(self.code_provider_attr)
if code_provider == "embedded":
prop = find_prop(props, "inputs:codeStr")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
build_fn=partial(
get_code_str_prop_builder(self),
prop,
),
)
elif code_provider == "file":
prop = find_prop(props, "inputs:codeFile")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
build_fn=partial(
get_code_file_prop_builder(self),
prop,
),
)
else:
raise RuntimeError("Unexpected code provider '{}'".format(code_provider))
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpKernel.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:size",
"inputs:cellSize",
"inputs:gravity",
"inputs:amplitude",
"inputs:speed",
"inputs:damping",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpWaveSolve.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Widgets used by the custom node UI templates.
These are built solely against the `omni.ui` framework and could in theory be
reused outside of the context of node UIs, unlike the properties that are built
on top of `omni.kit.property.usd`.
"""
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/widgets/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Widget for a dialog window to author node attributes."""
from functools import partial
import omni.graph.core as og
from omni.kit.widget.searchfield import SearchField
import omni.ui as ui
from omni.warp.nodes._impl.kernel import (
ArrayAttributeFormat,
OutputArrayShapeSource,
UserAttributeDesc,
)
_DIALOG_TITLE = "Attribute Creator"
_DIALOG_PADDING = 15
_DATA_TYPE_FRAME_HEIGHT = 300
_LABEL_WIDTH = 100
_FIELD_WIDTH = 275
_DIALOG_BTNS_FRAME_HEIGHT = 20
def _add_label(title):
ui.Label(title, alignment=ui.Alignment.RIGHT, width=_LABEL_WIDTH)
ui.Spacer(width=_DIALOG_PADDING)
class AttributeEditor:
"""Editor to add/remove node attributes."""
def __init__(self, data_type_names, create_attr_callback):
self.supported_data_type_names = data_type_names
self.filtered_data_type_names = data_type_names
self.create_attr_callback = create_attr_callback
self.dialog = None
self.input_port_btn = None
self.output_port_btn = None
self.name_field = None
self.data_type_frame = None
self.selected_data_type_btn = None
self.is_array_frame = None
self.is_array_checkbox = None
self.array_format_frame = None
self.array_format_combobox = None
self.output_array_shape_source_frame = None
self.output_array_shape_source_combobox = None
self.optional_frame = None
self.optional_checkbox = None
self.error_msg_label = None
self._build()
@property
def port_type(self):
if self.input_port_btn.checked:
return og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT
if self.output_port_btn.checked:
return og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT
return None
@property
def name(self):
return self.name_field.model.get_value_as_string()
@property
def data_type(self):
if self.selected_data_type_btn is None:
return None
return self.selected_data_type_btn.text
@property
def is_array(self):
return self.is_array_checkbox.model.get_value_as_bool()
@property
def array_format(self):
return ArrayAttributeFormat(self.array_format_combobox.model.get_item_value_model().get_value_as_int())
@property
def array_shape_source(self):
if self.port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT:
enum_type = OutputArrayShapeSource
widget = self.output_array_shape_source_combobox
else:
return None
value = widget.model.get_item_value_model().get_value_as_int()
return enum_type(value)
@property
def optional(self):
return self.optional_checkbox.model.get_value_as_bool()
def _update_array_shape_source_visibility(self):
self.output_array_shape_source_frame.visible = (
self.port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT and self.is_array
)
def _handle_data_type_clicked(self, btn):
if self.selected_data_type_btn is not None:
self.selected_data_type_btn.checked = False
self.selected_data_type_btn = btn
self.selected_data_type_btn.checked = True
def _handle_input_port_btn_clicked(self):
self.is_array_frame.enabled = True
self.optional_frame.visible = True
self._update_array_shape_source_visibility()
def _handle_output_port_btn_clicked(self):
self.is_array_checkbox.model.set_value(True)
self.is_array_frame.enabled = False
self.optional_frame.visible = False
self._update_array_shape_source_visibility()
def _handle_data_type_search(self, text):
if text is None:
self.filtered_data_type_names = self.supported_data_type_names
else:
text = text[0]
self.filtered_data_type_names = tuple(x for x in self.supported_data_type_names if text in x)
self._build_data_type_frame()
self.selected_data_type_btn = None
def _handle_is_array_value_changed(self, model):
# TODO: uncomment when support for dynamic bundle attributes is added
# in OmniGraph.
# self.array_format_frame.visible = model.get_value_as_bool()
self._update_array_shape_source_visibility()
def _handle_array_format_item_changed(self, model, item):
self._update_array_shape_source_visibility()
def _handle_ok_btn_clicked(self):
port_type = self.port_type
if port_type is None:
self._set_error_msg("A port type must be selected.")
return
name = self.name
if not name:
self._set_error_msg("The attribute's name cannot be empty.")
return
if not name[0].isalpha():
self._set_error_msg("The first character of the attribute's name must be a letter.")
return
if self.data_type is None:
self._set_error_msg("A data type for the new attribute must be selected.")
return
attr_desc = UserAttributeDesc(
port_type=port_type,
base_name=name,
data_type_name=self.data_type,
is_array=self.is_array,
array_format=self.array_format,
array_shape_source=self.array_shape_source,
optional=(self.port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT and self.optional),
)
try:
self.create_attr_callback(attr_desc)
except Exception as e:
self._set_error_msg(str(e))
return
self.dialog.visible = False
def _handle_cancel_btn_clicked(self):
self.dialog.visible = False
def _set_error_msg(self, msg):
self.error_msg_label.text = msg
self.error_msg_label.visible = True
def _build_data_type_frame(self):
self.data_type_frame.clear()
with self.data_type_frame:
with ui.VStack():
for data_type_name in self.filtered_data_type_names:
btn = ui.Button(data_type_name)
btn.set_clicked_fn(
partial(
self._handle_data_type_clicked,
btn,
),
)
def _build(self):
self.dialog = ui.Window(
_DIALOG_TITLE,
padding_x=_DIALOG_PADDING,
padding_y=_DIALOG_PADDING,
auto_resize=True,
)
with self.dialog.frame:
with ui.VStack(spacing=10):
# Placeholder to display any error message.
self.error_msg_label = ui.Label(
"",
alignment=ui.Alignment.H_CENTER,
word_wrap=True,
visible=False,
style={
"color": 0xFF0000FF,
},
)
# Port type.
with ui.HStack(height=0):
_add_label("Port Type")
radio_collection = ui.RadioCollection()
with ui.HStack(width=_FIELD_WIDTH):
self.input_port_btn = ui.RadioButton(
text="input",
radio_collection=radio_collection,
clicked_fn=self._handle_input_port_btn_clicked,
)
self.output_port_btn = ui.RadioButton(
text="output",
radio_collection=radio_collection,
clicked_fn=self._handle_output_port_btn_clicked,
)
# Name.
with ui.HStack(height=0):
_add_label("Name")
self.name_field = ui.StringField(width=_FIELD_WIDTH)
# Data type.
with ui.HStack(height=0):
_add_label("Data Type")
with ui.VStack(width=_FIELD_WIDTH):
SearchField(
show_tokens=False,
on_search_fn=self._handle_data_type_search,
subscribe_edit_changed=True,
)
self.data_type_frame = ui.ScrollingFrame(
height=_DATA_TYPE_FRAME_HEIGHT,
horizontal_scrollbar_policy=(ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF),
style_type_name_override="TreeView",
)
self._build_data_type_frame()
# Is array flag.
self.is_array_frame = ui.HStack(height=0)
with self.is_array_frame:
_add_label("Is Array")
self.is_array_checkbox = ui.CheckBox(width=_FIELD_WIDTH)
self.is_array_checkbox.model.add_value_changed_fn(self._handle_is_array_value_changed)
# Array's format.
self.array_format_frame = ui.HStack(height=0, visible=False)
with self.array_format_frame:
_add_label("Array Format")
self.array_format_combobox = ui.ComboBox(
0,
*(x.label for x in ArrayAttributeFormat),
width=_FIELD_WIDTH,
)
self.array_format_combobox.model.add_item_changed_fn(self._handle_array_format_item_changed)
# Output array's shape.
self.output_array_shape_source_frame = ui.HStack(
height=0,
visible=False,
)
with self.output_array_shape_source_frame:
_add_label("Array Shape")
self.output_array_shape_source_combobox = ui.ComboBox(
0,
*(x.label for x in OutputArrayShapeSource),
width=_FIELD_WIDTH,
)
# Optional flag.
self.optional_frame = ui.HStack(height=0)
with self.optional_frame:
_add_label("Optional")
self.optional_checkbox = ui.CheckBox(width=_FIELD_WIDTH)
# Dialog buttons.
with ui.HStack(height=0):
ui.Spacer()
with ui.HStack(
width=_FIELD_WIDTH,
height=_DIALOG_BTNS_FRAME_HEIGHT,
):
ui.Button(
"OK",
clicked_fn=self._handle_ok_btn_clicked,
)
ui.Button(
"Cancel",
clicked_fn=self._handle_cancel_btn_clicked,
)
| warp-main | exts/omni.warp/omni/warp/nodes/_impl/widgets/attributeeditor.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Tests for the `from_omni_graph()` API."""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.warp
import warp as wp
from omni.warp.nodes.tests._common import (
array_are_equal,
attr_set_array,
bundle_create_attr,
bundle_get_attr,
register_node,
)
# Test Node Definitions
# -----------------------------------------------------------------------------
MAKE_DATA_NODE_DEF = """{
"WarpTestsMakeData": {
"version": 1,
"description": "Make data.",
"language": "Python",
"uiName": "Make Data",
"cudaPointers": "cpu",
"outputs": {
"floatArrayAttr": {
"type": "float[]",
"uiName": "Float Array",
"description": "Float array."
},
"vec3ArrayAttr": {
"type": "float[3][]",
"uiName": "Vector3 Array",
"description": "Vector3 array."
},
"mat4ArrayAttr": {
"type": "matrixd[4][]",
"uiName": "Matrix4 Array",
"description": "Matrix4 array."
},
"bundleAttr": {
"type": "bundle",
"uiName": "Bundle",
"description": "Bundle."
}
}
}
}
"""
class MakeDataNode:
@staticmethod
def compute(db: og.Database) -> bool:
db.outputs.floatArrayAttr = (1.0, 2.0, 3.0)
db.outputs.vec3ArrayAttr = ((1.0, 2.0, 3.0), (4.0, 5.0, 6.0))
db.outputs.mat4ArrayAttr = (
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
)
for variant in ("cpuBundle", "gpuBundle"):
attr = bundle_create_attr(
db.outputs.bundleAttr,
"{}FloatArray".format(variant),
og.Type(
og.BaseDataType.FLOAT,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=3,
)
attr_set_array(
attr,
wp.array(db.outputs.floatArrayAttr, dtype=wp.float32),
on_gpu=variant == "gpuBundle",
)
attr = bundle_create_attr(
db.outputs.bundleAttr,
"{}Vec3Array".format(variant),
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=2,
)
attr_set_array(
attr,
wp.array(db.outputs.vec3ArrayAttr, dtype=wp.vec3),
on_gpu=variant == "gpuBundle",
)
attr = bundle_create_attr(
db.outputs.bundleAttr,
"{}Mat4Array".format(variant),
og.Type(
og.BaseDataType.DOUBLE,
tuple_count=16,
array_depth=1,
role=og.AttributeRole.MATRIX,
),
size=2,
)
attr_set_array(
attr,
wp.array(db.outputs.mat4ArrayAttr, dtype=wp.mat44d),
on_gpu=variant == "gpuBundle",
)
return True
FROM_OMNI_GRAPH_NODE_DEF = """{
"WarpTestsFromOmniGraph": {
"version": 1,
"description": "From omni graph.",
"language": "Python",
"uiName": "From Omni Graph",
"cudaPointers": "cpu",
"inputs": {
"anyFloatArrayAttr": {
"type": "float[]",
"uiName": "Float Array (Any)",
"description": "Float array (any).",
"memoryType": "any"
},
"cpuFloatArrayAttr": {
"type": "float[]",
"uiName": "Float Array (CPU)",
"description": "Float array (cpu).",
"memoryType": "cpu"
},
"gpuFloatArrayAttr": {
"type": "float[]",
"uiName": "Float Array (GPU)",
"description": "Float array (gpu).",
"memoryType": "cuda"
},
"anyVec3ArrayAttr": {
"type": "float[3][]",
"uiName": "Vector3 Array (Any)",
"description": "Vector3 array (any).",
"memoryType": "any"
},
"cpuVec3ArrayAttr": {
"type": "float[3][]",
"uiName": "Vector3 Array (CPU)",
"description": "Vector3 array (cpu).",
"memoryType": "cpu"
},
"gpuVec3ArrayAttr": {
"type": "float[3][]",
"uiName": "Vector3 Array (GPU)",
"description": "Vector3 array (gpu).",
"memoryType": "cuda"
},
"anyMat4ArrayAttr": {
"type": "matrixd[4][]",
"uiName": "Matrix4 Array (Any)",
"description": "Matrix4 array (any).",
"memoryType": "any"
},
"cpuMat4ArrayAttr": {
"type": "matrixd[4][]",
"uiName": "Matrix4 Array (CPU)",
"description": "Matrix4 array (cpu).",
"memoryType": "cpu"
},
"gpuMat4ArrayAttr": {
"type": "matrixd[4][]",
"uiName": "Matrix4 Array (GPU)",
"description": "Matrix4 array (gpu).",
"memoryType": "cuda"
},
"bundleAttr": {
"type": "bundle",
"uiName": "Bundle",
"description": "Bundle."
},
"device": {
"type": "string",
"uiName": "Device",
"description": "Device."
}
},
"outputs": {
"success": {
"type": "bool",
"uiName": "Success",
"description": "Success."
}
}
}
}
"""
def compute(db: og.Database) -> None:
"""Evaluates the node."""
variants = ("any", "cpu", "gpu", "cpuBundle", "gpuBundle")
# Float Array
# --------------------------------------------------------------------------
attr = "floatArray"
for variant in variants:
if variant in ("cpuBundle", "gpuBundle"):
data = bundle_get_attr(db.inputs.bundleAttr, "{}FloatArray".format(variant))
else:
data = getattr(db.inputs, "{}FloatArrayAttr".format(variant))
result = omni.warp.from_omni_graph(data)
expected = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, shape=(3,))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) not passing.".format(attr, variant))
# Cast the array to vec3.
result = omni.warp.from_omni_graph(data, dtype=wp.vec3)
expected = wp.array(((1.0, 2.0, 3.0),), dtype=wp.vec3, shape=(1,))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with casting to wp.vec3 not passing.".format(attr, variant))
# Vector3 Array
# --------------------------------------------------------------------------
attr = "vec3Array"
for variant in variants:
if variant in ("cpuBundle", "gpuBundle"):
data = bundle_get_attr(db.inputs.bundleAttr, "{}Vec3Array".format(variant))
else:
data = getattr(db.inputs, "{}Vec3ArrayAttr".format(variant))
result = omni.warp.from_omni_graph(data)
expected = wp.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=wp.vec3, shape=(2,))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) not passing.".format(attr, variant))
# Cast the array to floats while preserving the same shape.
result = omni.warp.from_omni_graph(data, dtype=wp.float32)
expected = wp.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=wp.float32, shape=(2, 3))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with casting to float not passing.".format(attr, variant))
# Cast the array to floats while flattening it to a single dimension.
result = omni.warp.from_omni_graph(data, dtype=wp.float32, shape=(6,))
expected = wp.array((1.0, 2.0, 3.0, 4.0, 5.0, 6.0), dtype=wp.float32, shape=(6,))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with flattening not passing.".format(attr, variant))
# Matrix4 Array
# --------------------------------------------------------------------------
attr = "mat4Array"
for variant in variants:
if variant in ("cpuBundle", "gpuBundle"):
data = bundle_get_attr(db.inputs.bundleAttr, "{}Mat4Array".format(variant))
else:
data = getattr(db.inputs, "{}Mat4ArrayAttr".format(variant))
# Due to OmniGraph only supporting 1-D arrays with elements that might
# be represented as tuples, we can at best reconstruct 2-D arrays,
# however arrays made of elements such as matrices require 3 dimensions
# and hence are not something that we can infer from the data we're
# being given, so we need to explicitly pass the dtype here.
result = omni.warp.from_omni_graph(data, dtype=wp.mat44d)
expected = wp.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=wp.mat44d,
shape=(2,),
)
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) not passing.".format(attr, variant))
# Cast the array to vec4d.
result = omni.warp.from_omni_graph(data, dtype=wp.vec4d)
expected = wp.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=wp.vec4d,
shape=(2, 4),
)
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with casting to vec4 not passing.".format(attr, variant))
# Cast the array to floats while flattening it to a single dimension.
result = omni.warp.from_omni_graph(data, dtype=wp.float64, shape=(32,))
expected = wp.array(
(
1.0, 2.0, 3.0, 4.0,
2.0, 3.0, 4.0, 5.0,
3.0, 4.0, 5.0, 6.0,
4.0, 5.0, 6.0, 7.0,
2.0, 3.0, 4.0, 5.0,
3.0, 4.0, 5.0, 6.0,
4.0, 5.0, 6.0, 7.0,
5.0, 6.0, 7.0, 8.0,
),
dtype=wp.float64,
shape=(32,),
)
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with flattening not passing.".format(attr, variant))
class FromOmniGraphNode:
@staticmethod
def compute(db: og.Database) -> bool:
device = wp.get_device(db.inputs.device)
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.outputs.success = False
raise
db.outputs.success = True
return True
# Test Case
# -----------------------------------------------------------------------------
class TestApiFromOmniGraph(ogts.OmniGraphTestCase):
async def setUp(self) -> None:
await super().setUp()
register_node(MakeDataNode, MAKE_DATA_NODE_DEF, "omni.warp.nodes")
register_node(FromOmniGraphNode, FROM_OMNI_GRAPH_NODE_DEF, "omni.warp.nodes")
(graph, _, _, _) = og.Controller.edit(
"/Graph",
{
og.Controller.Keys.CREATE_NODES: [
("MakeData", "omni.warp.nodes.WarpTestsMakeData"),
("FromOmniGraph", "omni.warp.nodes.WarpTestsFromOmniGraph"),
],
og.Controller.Keys.CONNECT: [
("MakeData.outputs:floatArrayAttr", "FromOmniGraph.inputs:anyFloatArrayAttr"),
("MakeData.outputs:floatArrayAttr", "FromOmniGraph.inputs:cpuFloatArrayAttr"),
("MakeData.outputs:floatArrayAttr", "FromOmniGraph.inputs:gpuFloatArrayAttr"),
("MakeData.outputs:vec3ArrayAttr", "FromOmniGraph.inputs:anyVec3ArrayAttr"),
("MakeData.outputs:vec3ArrayAttr", "FromOmniGraph.inputs:cpuVec3ArrayAttr"),
("MakeData.outputs:vec3ArrayAttr", "FromOmniGraph.inputs:gpuVec3ArrayAttr"),
("MakeData.outputs:mat4ArrayAttr", "FromOmniGraph.inputs:anyMat4ArrayAttr"),
("MakeData.outputs:mat4ArrayAttr", "FromOmniGraph.inputs:cpuMat4ArrayAttr"),
("MakeData.outputs:mat4ArrayAttr", "FromOmniGraph.inputs:gpuMat4ArrayAttr"),
("MakeData.outputs_bundleAttr", "FromOmniGraph.inputs:bundleAttr"),
],
},
)
self.graph = graph
async def test_main(self):
node = og.Controller.node(("FromOmniGraph", self.graph))
device_attr = og.Controller.attribute("inputs:device", node)
success_attr = og.Controller.attribute("outputs:success", node)
device_attr.set("cpu")
await og.Controller.evaluate(self.graph)
self.assertTrue(success_attr.get())
device_attr.set("cuda:0")
await og.Controller.evaluate(self.graph)
self.assertTrue(success_attr.get())
| warp-main | exts/omni.warp/omni/warp/nodes/tests/test_api_from_omni_graph.py |
"""Shared helpers for the extension's tests."""
from typing import Optional
import importlib
import os
import tempfile
import numpy as np
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
import warp as wp
def register_node(
cls: type,
ogn_definition: str,
extension: str,
) -> None:
"""Registers a new node type based on its class object and OGN code."""
# Parse the OGN definition.
interface_wrapper = ogn.NodeInterfaceWrapper(ogn_definition, extension)
# Generate the node's `og.Database` class and load it as a module.
db_definition = ogn.generate_python(
ogn.GeneratorConfiguration(
node_file_path=None,
node_interface=interface_wrapper.node_interface,
extension=extension,
module=extension,
base_name=cls.__name__,
destination_directory=None,
),
)
module_name = "{}.{}".format(extension, cls.__name__)
file, file_path = tempfile.mkstemp(suffix=".py")
try:
with os.fdopen(file, "w") as f:
f.write(db_definition)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
finally:
os.remove(file_path)
# Register the node.
db_cls = getattr(module, "{}Database".format(cls.__name__))
db_cls.register(cls)
def bundle_create_attr(
bundle: og.BundleContents,
name: str,
og_type: og.Type,
size: int = 0,
) -> og.AttributeData:
"""Creates a bundle attribute if it doesn't already exist."""
if bundle.bundle.get_child_bundle_count() > 0:
prim_bundle = bundle.bundle.get_child_bundle(0)
else:
prim_bundle = bundle.bundle.create_child_bundle("prim0")
attr = prim_bundle.get_attribute_by_name(name)
if attr.is_valid() and attr.get_type() == og_type and attr.size() == size:
return attr
return prim_bundle.create_attribute(name, og_type, element_count=size)
def bundle_get_attr(
bundle: og.BundleContents,
name: str,
) -> Optional[og.AttributeData]:
"""Retrieves a bundle attribute from its name."""
if bundle.bundle.get_child_bundle_count():
attr = bundle.bundle.get_child_bundle(0).get_attribute_by_name(name)
else:
attr = bundle.bundle.get_attribute_by_name(name)
if not attr.is_valid():
return None
return attr
def attr_set_array(
attr: og.AttributeData,
value: wp.array,
on_gpu: bool = False,
) -> None:
"""Sets the given array data onto an attribute."""
if on_gpu:
attr.gpu_ptr_kind = og.PtrToPtrKind.CPU
(ptr, _) = attr.get_array(
on_gpu=True,
get_for_write=True,
reserved_element_count=attr.size(),
)
data = wp.from_ptr(ptr, attr.size(), dtype=value.dtype)
wp.copy(data, value)
else:
attr.set(value.numpy(), on_gpu=False)
def array_are_equal(
a: wp.array,
b: wp.array,
) -> bool:
"""Checks whether two arrays are equal."""
return a.shape == b.shape and a.dtype == a.dtype and np.array_equal(a.numpy(), b.numpy())
| warp-main | exts/omni.warp/omni/warp/nodes/tests/_common.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Tests for the extension omni.warp.nodes."""
scan_for_test_modules = True
| warp-main | exts/omni.warp/omni/warp/nodes/tests/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Tests for the API that does type conversions."""
from typing import Any
import omni.graph.core as og
import omni.kit
import omni.warp
import warp as wp
def are_array_annotations_equal(a: Any, b: Any) -> bool:
return (
isinstance(a, wp.array) and isinstance(b, wp.array)
and a.dtype == b.dtype
and a.ndim == b.ndim
)
class TestApiTypeConversions(omni.kit.test.AsyncTestCase):
async def test_og_to_warp_conversion(self):
og_type = og.Type(
og.BaseDataType.BOOL,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type)
expected = wp.int8
self.assertEqual(wp_type, expected)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type, dim_count=1)
expected = wp.array(dtype=wp.int8)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
# ----------------------------------------------------------------------
og_type = og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.COLOR,
)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type)
expected = wp.array(dtype=wp.vec3)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type, dim_count=0)
expected = wp.vec3
self.assertEqual(wp_type, expected)
# ----------------------------------------------------------------------
og_type = og.Type(
og.BaseDataType.DOUBLE,
tuple_count=9,
array_depth=0,
role=og.AttributeRole.MATRIX,
)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type)
expected = wp.mat33d
self.assertEqual(wp_type, expected)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type, dim_count=1)
expected = wp.array(dtype=wp.mat33d)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
# ----------------------------------------------------------------------
og_type = og.Type(
og.BaseDataType.FLOAT,
tuple_count=4,
array_depth=1,
role=og.AttributeRole.QUATERNION,
)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type)
expected = wp.array(dtype=wp.quat)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type, dim_count=0)
expected = wp.quat
self.assertEqual(wp_type, expected)
async def test_sdf_name_to_warp_conversion(self):
sdf_name = "color4f"
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name)
expected = wp.vec4
self.assertEqual(wp_type, expected)
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name, dim_count=1)
expected = wp.array(dtype=wp.vec4)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
# ----------------------------------------------------------------------
sdf_name = "point3f[]"
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name)
expected = wp.array(dtype=wp.vec3)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name, dim_count=0)
expected = wp.vec3
self.assertEqual(wp_type, expected)
# ----------------------------------------------------------------------
sdf_name = "timecode"
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name)
expected = wp.float64
self.assertEqual(wp_type, expected)
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name, dim_count=1)
expected = wp.array(dtype=wp.float64)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
# ----------------------------------------------------------------------
sdf_name = "token[]"
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name)
expected = wp.array(dtype=wp.uint64)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name, dim_count=0)
expected = wp.uint64
self.assertEqual(wp_type, expected)
async def test_sdf_name_to_og_conversion(self):
sdf_name = "float2"
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name)
expected = og.Type(
og.BaseDataType.FLOAT,
tuple_count=2,
array_depth=0,
role=og.AttributeRole.NONE,
)
self.assertEqual(og_type, expected)
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name, is_array=True)
expected = og.Type(
og.BaseDataType.FLOAT,
tuple_count=2,
array_depth=1,
role=og.AttributeRole.NONE,
)
self.assertEqual(og_type, expected)
# ----------------------------------------------------------------------
sdf_name = "matrix3d[]"
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name)
expected = og.Type(
og.BaseDataType.DOUBLE,
tuple_count=9,
array_depth=1,
role=og.AttributeRole.MATRIX,
)
self.assertEqual(og_type, expected)
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name, is_array=False)
expected = og.Type(
og.BaseDataType.DOUBLE,
tuple_count=9,
array_depth=0,
role=og.AttributeRole.MATRIX,
)
self.assertEqual(og_type, expected)
# ----------------------------------------------------------------------
sdf_name = "texCoord2f"
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name)
expected = og.Type(
og.BaseDataType.FLOAT,
tuple_count=2,
array_depth=0,
role=og.AttributeRole.TEXCOORD,
)
self.assertEqual(og_type, expected)
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name, is_array=True)
expected = og.Type(
og.BaseDataType.FLOAT,
tuple_count=2,
array_depth=1,
role=og.AttributeRole.TEXCOORD,
)
self.assertEqual(og_type, expected)
# ----------------------------------------------------------------------
sdf_name = "uchar[]"
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name)
expected = og.Type(
og.BaseDataType.UCHAR,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
)
self.assertEqual(og_type, expected)
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name, is_array=False)
expected = og.Type(
og.BaseDataType.UCHAR,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
)
self.assertEqual(og_type, expected) | warp-main | exts/omni.warp/omni/warp/nodes/tests/test_api_type_conversions.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Entry point for the extension."""
import asyncio
from contextlib import suppress
import os
import subprocess
import sys
from typing import Sequence
import webbrowser
import carb
import carb.dictionary
import omni.ext
import omni.graph.core as og
import omni.kit.actions.core
import warp as wp
SCENES_PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../data/scenes"))
NODES_INIT_PATH = os.path.normpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "../nodes/_impl/__init__.py")
)
WARP_GETTING_STARTED_URL = "https://docs.omniverse.nvidia.com/extensions/latest/ext_warp.html"
WARP_DOCUMENTATION_URL = "https://nvidia.github.io/warp/"
SETTING_ENABLE_BACKWARD = "/exts/omni.warp/enable_backward"
SETTING_KERNEL_NODE_OPT_IN = "/app/omni.warp/kernel_opt_in"
SETTING_KERNEL_NODE_ENABLE_OPT_IN = "/app/omni.warp/kernel_enable_opt_in"
OMNIGRAPH_STAGEUPDATE_ORDER = 100 # We want our attach() to run after OG so that nodes have been instantiated
def open_file(filename):
if sys.platform == "win32":
os.startfile(filename)
else:
subprocess.call(["xdg-open", filename])
def set_all_graphs_enabled(enable: bool) -> None:
"""Set the enabled state of all OmniGraphs"""
graphs = og.get_all_graphs()
for graph in graphs:
graph.set_disabled(not enable)
def is_kernel_node_check_enabled() -> bool:
"""Check whether the kernel node opt-in is enabled"""
settings = carb.settings.get_settings()
if not settings.is_accessible_as(
carb.dictionary.ItemType.BOOL,
SETTING_KERNEL_NODE_ENABLE_OPT_IN,
):
# The enable-setting is not present, we enable the check
return True
if not settings.get(SETTING_KERNEL_NODE_ENABLE_OPT_IN):
# The enable-setting is present and False, disable the check
return False
# the enable-setting is present and True, enable the check
return True
VERIFY_KERNEL_NODE_LOAD_MSG = """This stage contains Warp kernel nodes.
There is currently no limitation on what code can be executed by this node. This means that graphs that contain these nodes should only be used when the author of the graph is trusted.
Do you want to enable the Warp kernel node functionality for this session?
"""
def verify_kernel_node_load(nodes: Sequence[og.Node]):
"""Confirm the user wants to run the nodes for the current session."""
from omni.kit.window.popup_dialog import MessageDialog
def on_cancel(dialog: MessageDialog):
settings = carb.settings.get_settings()
settings.set(SETTING_KERNEL_NODE_OPT_IN, False)
dialog.hide()
def on_ok(dialog: MessageDialog):
settings = carb.settings.get_settings()
settings.set(SETTING_KERNEL_NODE_OPT_IN, True)
dialog.hide()
dialog = MessageDialog(
title="Warning",
width=400,
message=VERIFY_KERNEL_NODE_LOAD_MSG,
ok_handler=on_ok,
ok_label="Yes",
cancel_handler=on_cancel,
cancel_label="No",
)
async def show_async():
import omni.kit.app
# wait a few frames to allow the app ui to finish loading
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
dialog.show()
asyncio.ensure_future(show_async())
def check_for_kernel_nodes() -> None:
"""Check for kernel node instances and confirm user wants to run them."""
# If the check is not enabled then we are good
if not is_kernel_node_check_enabled():
return
# Check is enabled - see if they already opted-in
settings = carb.settings.get_settings()
if settings.get(SETTING_KERNEL_NODE_OPT_IN):
# The check is enabled, and they opted-in
return
# The check is enabled but they opted out, or haven't been prompted yet
try:
import omni.kit.window.popup_dialog
except ImportError:
# Don't prompt in headless mode
return
graphs = og.get_all_graphs()
nodes = tuple(
n for g in graphs for n in g.get_nodes() if n.get_node_type().get_node_type() == "omni.warp.WarpKernel"
)
if not nodes:
# No nodes means we can leave them enabled
return
# Disable them until we get the opt-in via the async dialog
set_all_graphs_enabled(False)
verify_kernel_node_load(nodes)
def on_attach(*args, **kwargs) -> None:
"""Called when USD stage is attached"""
check_for_kernel_nodes()
def on_kernel_opt_in_setting_change(
item: carb.dictionary.Item,
change_type: carb.settings.ChangeEventType,
) -> None:
"""Update the local cache of the setting value"""
if change_type != carb.settings.ChangeEventType.CHANGED:
return
settings = carb.settings.get_settings()
if settings.get(SETTING_KERNEL_NODE_OPT_IN):
set_all_graphs_enabled(True)
class OmniWarpExtension(omni.ext.IExt):
def __init__(self, *args, **kwargs):
import omni.kit.app
super().__init__(*args, **kwargs)
self._menu = None
self._stage_subscription = None
self._opt_in_setting_sub = None
with suppress(ImportError):
app = omni.kit.app.get_app()
manager = app.get_extension_manager()
if manager.is_extension_enabled("omni.graph.ui"):
import omni.graph.ui
omni.graph.ui.ComputeNodeWidget.get_instance().add_template_path(NODES_INIT_PATH)
def on_startup(self, ext_id):
import omni.kit.app
settings = carb.settings.get_settings()
wp.config.enable_backward = settings.get(SETTING_ENABLE_BACKWARD)
wp.init()
self._is_live = True
self._ext_name = "omni.warp"
with suppress(ImportError):
import omni.kit.menu.utils
from omni.warp._extension.menu import WarpMenu
self._register_actions()
self._menu = WarpMenu()
with suppress(ImportError):
import omni.kit.browser.sample
omni.kit.browser.sample.register_sample_folder(SCENES_PATH, "Warp")
stage_update = omni.stageupdate.get_stage_update_interface()
self._stage_subscription = stage_update.create_stage_update_node(
"WarpKernelAttach",
on_attach_fn=on_attach,
)
assert self._stage_subscription
nodes = stage_update.get_stage_update_nodes()
stage_update.set_stage_update_node_order(
len(nodes) - 1,
OMNIGRAPH_STAGEUPDATE_ORDER + 1,
)
self._opt_in_setting_sub = omni.kit.app.SettingChangeSubscription(
SETTING_KERNEL_NODE_OPT_IN,
on_kernel_opt_in_setting_change,
)
assert self._opt_in_setting_sub
# Expose the `from_omni_graph` function onto the `omni.warp` module for
# backward compatibility. This cannot be done by using a `__init__.py`
# file directly under the `omni/warp` folder because it represents
# a Python namespace package.
import omni.warp
import omni.warp.nodes
omni.warp.from_omni_graph = omni.warp.nodes.from_omni_graph
def on_shutdown(self):
if self._menu is not None:
self._menu.shutdown()
self._menu = None
self._deregister_actions()
with suppress(ImportError):
import omni.kit.browser.sample
omni.kit.browser.sample.unregister_sample_folder(SCENES_PATH)
self._stage_subscription = None
self._opt_in_setting_sub = None
# Clean-up the extension's API.
import omni.warp
delattr(omni.warp, "from_omni_graph")
def _register_actions(self):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Warp menu actions"
# actions
action_registry.register_action(
self._ext_name,
"getting_started",
lambda: self._on_getting_started_click(),
display_name="Warp->Getting Started",
description="",
tag=actions_tag,
)
action_registry.register_action(
self._ext_name,
"documentation",
lambda: self._on_documentation_click(),
display_name="Warp->Documentation",
description="",
tag=actions_tag,
)
action_registry.register_action(
self._ext_name,
"browse_scenes",
lambda: self._on_browse_scenes_click(),
display_name="Warp->Browse Scenes",
description="",
tag=actions_tag,
)
def _deregister_actions(self):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(self._ext_name)
def _on_browse_scenes_click(self):
open_file(SCENES_PATH)
def _on_getting_started_click(self, *_):
webbrowser.open(WARP_GETTING_STARTED_URL)
def _on_documentation_click(self, *_):
webbrowser.open(WARP_DOCUMENTATION_URL)
| warp-main | exts/omni.warp/omni/warp/_extension/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import omni.kit.menu.utils
from omni.kit.menu.utils import MenuItemDescription
class WarpMenu:
def __init__(self):
omni.kit.menu.utils.set_default_menu_proirity("Warp", -8)
self._top_menu = None
self._build_warp_menu()
def _build_warp_menu(self):
# Warp menu
warp_menu = []
warp_menu.append(MenuItemDescription(name="Documentation", onclick_action=("omni.warp", "documentation")))
warp_menu.append(MenuItemDescription(name="Getting Started", onclick_action=("omni.warp", "getting_started")))
warp_menu.append(MenuItemDescription(name="Sample Scenes", onclick_action=("omni.warp", "browse_scenes")))
self._top_menu = [MenuItemDescription(name="Warp", appear_after="Simulation", sub_menu=warp_menu)]
omni.kit.menu.utils.add_menu_items(self._top_menu, "Window", -8)
def shutdown(self):
omni.kit.menu.utils.remove_menu_items(self._top_menu, "Window")
| warp-main | exts/omni.warp/omni/warp/_extension/menu.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Public API for the omni.warp.core extension"""
# Register the extension by importing its entry point class.
from omni.warp.core._impl.extension import OmniWarpCoreExtension as _
| warp-main | exts/omni.warp.core/omni/warp/core/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Private Python implementation for the extension."""
| warp-main | exts/omni.warp.core/omni/warp/core/_impl/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import omni.ext
import warp as wp
class OmniWarpCoreExtension(omni.ext.IExt):
def on_startup(self, ext_id):
wp.init()
| warp-main | exts/omni.warp.core/omni/warp/core/_impl/extension.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Tests for the extension omni.warp."""
scan_for_test_modules = True
| warp-main | exts/omni.warp.core/omni/warp/core/tests/__init__.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Tests for the Warp library itself.
Only a trimmed down list of tests is run since the full suite is too slow.
"""
import omni.kit
import warp as wp
import warp.tests.test_codegen
import warp.tests.test_mesh_query_aabb
import warp.tests.test_mesh_query_point
import warp.tests.test_mesh_query_ray
import warp.tests.test_conditional
import warp.tests.test_operators
import warp.tests.test_rounding
import warp.tests.test_hash_grid
import warp.tests.test_ctypes
import warp.tests.test_rand
import warp.tests.test_noise
import warp.tests.test_tape
initialized = False
class BaseTestCase(omni.kit.test.AsyncTestCase):
@classmethod
def setUpClass(cls):
global initialized
if not initialized:
# Load all the Warp modules just once. This needs to be done
# within the `setUpClass` method instead of at the module level
# to avoid the reload to be done as soon as this module is imported,
# which might happen when scanning for existing tests without
# actually needing to run these ones.
wp.force_load()
initialized = True
test_clss = (
warp.tests.test_codegen.register(BaseTestCase),
warp.tests.test_mesh_query_aabb.register(BaseTestCase),
warp.tests.test_mesh_query_point.register(BaseTestCase),
warp.tests.test_mesh_query_ray.register(BaseTestCase),
warp.tests.test_conditional.register(BaseTestCase),
warp.tests.test_operators.register(BaseTestCase),
warp.tests.test_rounding.register(BaseTestCase),
warp.tests.test_hash_grid.register(BaseTestCase),
warp.tests.test_ctypes.register(BaseTestCase),
warp.tests.test_rand.register(BaseTestCase),
warp.tests.test_noise.register(BaseTestCase),
warp.tests.test_tape.register(BaseTestCase),
)
# Each test class needs to be defined at the module level to be found by
# the test runners.
locals().update({str(i): x for i, x in enumerate(test_clss)})
| warp-main | exts/omni.warp.core/omni/warp/core/tests/test_ext.py |
# Use this file to bootstrap packman into your Python environment (3.7.x). Simply
# add the path by doing sys.insert to where packmanconf.py is located and then execute:
#
# >>> import packmanconf
# >>> packmanconf.init()
#
# It will use the configured remote(s) and the version of packman in the same folder,
# giving you full access to the packman API via the following module
#
# >> import packmanapi
# >> dir(packmanapi)
import os
import platform
import sys
def init():
"""Call this function to initialize the packman configuration.
Calls to the packman API will work after successfully calling this function.
Note:
This function only needs to be called once during the execution of your
program. Calling it repeatedly is harmless but wasteful.
Compatibility with your Python interpreter is checked and upon failure
the function will report what is required.
Example:
>>> import packmanconf
>>> packmanconf.init()
>>> import packmanapi
>>> packmanapi.set_verbosity_level(packmanapi.VERBOSITY_HIGH)
"""
major = sys.version_info[0]
minor = sys.version_info[1]
if major != 3 or minor != 10:
raise RuntimeError(
f"This version of packman requires Python 3.10.x, but {major}.{minor} was provided"
)
conf_dir = os.path.dirname(os.path.abspath(__file__))
os.environ["PM_INSTALL_PATH"] = conf_dir
packages_root = get_packages_root(conf_dir)
version = get_version(conf_dir)
module_dir = get_module_dir(conf_dir, packages_root, version)
sys.path.insert(1, module_dir)
def get_packages_root(conf_dir: str) -> str:
root = os.getenv("PM_PACKAGES_ROOT")
if not root:
platform_name = platform.system()
if platform_name == "Windows":
drive, _ = os.path.splitdrive(conf_dir)
root = os.path.join(drive, "packman-repo")
elif platform_name == "Darwin":
# macOS
root = os.path.join(
os.path.expanduser("~"), "/Library/Application Support/packman-cache"
)
elif platform_name == "Linux":
try:
cache_root = os.environ["XDG_HOME_CACHE"]
except KeyError:
cache_root = os.path.join(os.path.expanduser("~"), ".cache")
return os.path.join(cache_root, "packman")
else:
raise RuntimeError(f"Unsupported platform '{platform_name}'")
# make sure the path exists:
os.makedirs(root, exist_ok=True)
return root
def get_module_dir(conf_dir, packages_root: str, version: str) -> str:
module_dir = os.path.join(packages_root, "packman-common", version)
if not os.path.exists(module_dir):
import tempfile
tf = tempfile.NamedTemporaryFile(delete=False)
target_name = tf.name
tf.close()
url = f"http://bootstrap.packman.nvidia.com/packman-common@{version}.zip"
print(f"Downloading '{url}' ...")
import urllib.request
urllib.request.urlretrieve(url, target_name)
from importlib.machinery import SourceFileLoader
# import module from path provided
script_path = os.path.join(conf_dir, "bootstrap", "install_package.py")
ip = SourceFileLoader("install_package", script_path).load_module()
print("Unpacking ...")
ip.install_package(target_name, module_dir)
os.unlink(tf.name)
return module_dir
def get_version(conf_dir: str):
path = os.path.join(conf_dir, "packman")
if not os.path.exists(path): # in dev repo fallback
path += ".sh"
with open(path, "rt", encoding="utf8") as launch_file:
for line in launch_file.readlines():
if line.startswith("PM_PACKMAN_VERSION"):
_, value = line.split("=")
return value.strip()
raise RuntimeError(f"Unable to find 'PM_PACKMAN_VERSION' in '{path}'")
| warp-main | tools/packman/packmanconf.py |
# Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import zipfile
import tempfile
import sys
import os
import stat
import time
from typing import Any, Callable
RENAME_RETRY_COUNT = 100
RENAME_RETRY_DELAY = 0.1
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
def remove_directory_item(path):
if os.path.islink(path) or os.path.isfile(path):
try:
os.remove(path)
except PermissionError:
# make sure we have access and try again:
os.chmod(path, stat.S_IRWXU)
os.remove(path)
else:
# try first to delete the dir because this will work for folder junctions, otherwise we would follow the junctions and cause destruction!
clean_out_folder = False
try:
# make sure we have access preemptively - this is necessary because recursing into a directory without permissions
# will only lead to heart ache
os.chmod(path, stat.S_IRWXU)
os.rmdir(path)
except OSError:
clean_out_folder = True
if clean_out_folder:
# we should make sure the directory is empty
names = os.listdir(path)
for name in names:
fullname = os.path.join(path, name)
remove_directory_item(fullname)
# now try to again get rid of the folder - and not catch if it raises:
os.rmdir(path)
class StagingDirectory:
def __init__(self, staging_path):
self.staging_path = staging_path
self.temp_folder_path = None
os.makedirs(staging_path, exist_ok=True)
def __enter__(self):
self.temp_folder_path = tempfile.mkdtemp(prefix="ver-", dir=self.staging_path)
return self
def get_temp_folder_path(self):
return self.temp_folder_path
# this function renames the temp staging folder to folder_name, it is required that the parent path exists!
def promote_and_rename(self, folder_name):
abs_dst_folder_name = os.path.join(self.staging_path, folder_name)
os.rename(self.temp_folder_path, abs_dst_folder_name)
def __exit__(self, type, value, traceback):
# Remove temp staging folder if it's still there (something went wrong):
path = self.temp_folder_path
if os.path.isdir(path):
remove_directory_item(path)
def rename_folder(staging_dir: StagingDirectory, folder_name: str):
try:
staging_dir.promote_and_rename(folder_name)
except OSError as exc:
# if we failed to rename because the folder now exists we can assume that another packman process
# has managed to update the package before us - in all other cases we re-raise the exception
abs_dst_folder_name = os.path.join(staging_dir.staging_path, folder_name)
if os.path.exists(abs_dst_folder_name):
logger.warning(
f"Directory {abs_dst_folder_name} already present, package installation already completed"
)
else:
raise
def call_with_retry(
op_name: str, func: Callable, retry_count: int = 3, retry_delay: float = 20
) -> Any:
retries_left = retry_count
while True:
try:
return func()
except (OSError, IOError) as exc:
logger.warning(f"Failure while executing {op_name} [{str(exc)}]")
if retries_left:
retry_str = "retry" if retries_left == 1 else "retries"
logger.warning(
f"Retrying after {retry_delay} seconds"
f" ({retries_left} {retry_str} left) ..."
)
time.sleep(retry_delay)
else:
logger.error("Maximum retries exceeded, giving up")
raise
retries_left -= 1
def rename_folder_with_retry(staging_dir: StagingDirectory, folder_name):
dst_path = os.path.join(staging_dir.staging_path, folder_name)
call_with_retry(
f"rename {staging_dir.get_temp_folder_path()} -> {dst_path}",
lambda: rename_folder(staging_dir, folder_name),
RENAME_RETRY_COUNT,
RENAME_RETRY_DELAY,
)
def install_package(package_path, install_path):
staging_path, version = os.path.split(install_path)
with StagingDirectory(staging_path) as staging_dir:
output_folder = staging_dir.get_temp_folder_path()
with zipfile.ZipFile(package_path, allowZip64=True) as zip_file:
zip_file.extractall(output_folder)
# attempt the rename operation
rename_folder_with_retry(staging_dir, version)
print(f"Package successfully installed to {install_path}")
if __name__ == "__main__":
executable_paths = os.getenv("PATH")
paths_list = executable_paths.split(os.path.pathsep) if executable_paths else []
target_path_np = os.path.normpath(sys.argv[2])
target_path_np_nc = os.path.normcase(target_path_np)
for exec_path in paths_list:
if os.path.normcase(os.path.normpath(exec_path)) == target_path_np_nc:
raise RuntimeError(f"packman will not install to executable path '{exec_path}'")
install_package(sys.argv[1], target_path_np)
| warp-main | tools/packman/bootstrap/install_package.py |
import os
import sys
import io
import contextlib
import packmanapi
REPO_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..")
REPO_DEPS_FILE = os.path.join(REPO_ROOT, "deps/repo-deps.packman.xml")
def bootstrap():
"""
Bootstrap all omni.repo modules.
Pull with packman from repo.packman.xml and add them all to python sys.path to enable importing.
"""
#with contextlib.redirect_stdout(io.StringIO()):
deps = packmanapi.pull(REPO_DEPS_FILE)
for dep_path in deps.values():
if dep_path not in sys.path:
sys.path.append(dep_path)
if __name__ == "__main__":
bootstrap()
import omni.repo.man
omni.repo.man.main(REPO_ROOT)
| warp-main | tools/repoman/repoman.py |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath(".."))
# -- Project information -----------------------------------------------------
project = "Warp"
copyright = "2023, NVIDIA"
author = "NVIDIA"
version = "1.0.0-beta.2"
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon", # Convert docstrings to reStructuredText
"sphinx.ext.intersphinx",
"sphinx.ext.autosummary",
"sphinx.ext.todo",
# Third-party extensions:
# 'sphinx_tabs.tabs',
# 'sphinx_copybutton'
# 'autodocsumm'
]
# put type hints inside the description instead of the signature (easier to read)
autodoc_typehints = "description"
# document class *and* __init__ methods
autoclass_content = "both"
autodoc_member_order = "bysource"
# autodoc_typehints_format
# add_module_names = False
todo_include_todos = True
todo_emit_warnings = True
intersphinx_mapping = {
"python": ("https://docs.python.org/3", None),
"numpy": ("http://docs.scipy.org/doc/numpy/", None),
}
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "furo"
html_title = f"Warp {version}"
html_show_sphinx = False
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
html_css_files = ["custom.css"]
html_theme_options = {
"top_of_page_button": None,
"light_css_variables": {
"admonition-title-font-size": "100%",
"admonition-font-size": "100%",
"color-api-pre-name": "#4e9a06", # "#76b900",
"color-api-name": "#4e9a06", # "#76b900",
"color-admonition-title--seealso": "#ffffff",
"color-admonition-title-background--seealso": "#448aff",
"color-admonition-title-background--note": "#76b900",
"color-admonition-title--note": "#ffffff",
},
"dark_css_variables": {
"color-admonition-title-background--note": "#535353",
"color-admonition-title--note": "#ffffff",
},
"light_logo": "logo-light-mode.png",
"dark_logo": "logo-dark-mode.png",
"footer_icons": [
{
"name": "GitHub",
"url": "https://github.com/NVIDIA/warp",
"html": """
<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"></path>
</svg>
""",
"class": "",
},
],
}
| warp-main | docs/conf.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Rigid FEM
#
# Shows how to set up a rigid sphere colliding with an FEM beam
# using wp.sim.ModelBuilder().
#
###########################################################################
import os
import warp as wp
import warp.sim
import warp.sim.render
wp.init()
class Example:
def __init__(self, stage):
self.sim_width = 8
self.sim_height = 8
self.sim_fps = 60.0
self.sim_substeps = 32
self.sim_duration = 5.0
self.sim_frames = int(self.sim_duration * self.sim_fps)
self.sim_dt = (1.0 / self.sim_fps) / self.sim_substeps
self.sim_time = 0.0
self.sim_iterations = 1
self.sim_relaxation = 1.0
builder = wp.sim.ModelBuilder()
builder.default_particle_radius = 0.01
builder.add_soft_grid(
pos=(0.0, 0.0, 0.0),
rot=wp.quat_identity(),
vel=(0.0, 0.0, 0.0),
dim_x=20,
dim_y=10,
dim_z=10,
cell_x=0.1,
cell_y=0.1,
cell_z=0.1,
density=100.0,
k_mu=50000.0,
k_lambda=20000.0,
k_damp=0.0,
)
b = builder.add_body(origin=wp.transform((0.5, 2.5, 0.5), wp.quat_identity()))
builder.add_shape_sphere(body=b, radius=0.75, density=100.0)
self.model = builder.finalize()
self.model.ground = True
self.model.soft_contact_ke = 1.0e3
self.model.soft_contact_kd = 0.0
self.model.soft_contact_kf = 1.0e3
self.integrator = wp.sim.SemiImplicitIntegrator()
self.state_0 = self.model.state()
self.state_1 = self.model.state()
self.renderer = wp.sim.render.SimRendererOpenGL(self.model, stage, scaling=1.0)
def update(self):
with wp.ScopedTimer("simulate", active=True):
for s in range(self.sim_substeps):
wp.sim.collide(self.model, self.state_0)
self.state_0.clear_forces()
self.state_1.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
self.sim_time += self.sim_dt
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def render(self, is_live=False):
with wp.ScopedTimer("render", active=True):
time = 0.0 if is_live else self.sim_time
self.renderer.begin_frame(time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
stage_path = os.path.join(os.path.dirname(__file__), "outputs/example_sim_rigid_fem.usd")
example = Example(stage_path)
for i in range(example.sim_frames):
example.update()
example.render()
example.renderer.save()
| warp-main | examples/example_sim_rigid_fem.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Smooth Particle Hydrodynamics
#
# Shows how to implement a SPH
# Neighbors are found using the wp.HashGrid class, and
# wp.hash_grid_query(), wp.hash_grid_query_next() kernel methods.
#
# Reference Publication
# Müller, Matthias, David Charypar, and Markus H. Gross.
# "Particle-based fluid simulation for interactive applications."
# Symposium on Computer animation. Vol. 2. 2003.
#
###########################################################################
import numpy as np
import warp as wp
import warp.render
import os
wp.init()
@wp.func
def square(x: float):
return x * x
@wp.func
def cube(x: float):
return x * x * x
@wp.func
def fifth(x: float):
return x * x * x * x * x
@wp.func
def density_kernel(xyz: wp.vec3, smoothing_length: float):
# calculate distance
distance = wp.dot(xyz, xyz)
return wp.max(cube(square(smoothing_length) - distance), 0.0)
@wp.func
def diff_pressure_kernel(
xyz: wp.vec3, pressure: float, neighbor_pressure: float, neighbor_rho: float, smoothing_length: float
):
# calculate distance
distance = wp.sqrt(wp.dot(xyz, xyz))
if distance < smoothing_length:
# calculate terms of kernel
term_1 = -xyz / distance
term_2 = (neighbor_pressure + pressure) / (2.0 * neighbor_rho)
term_3 = square(smoothing_length - distance)
return term_1 * term_2 * term_3
else:
return wp.vec3()
@wp.func
def diff_viscous_kernel(xyz: wp.vec3, v: wp.vec3, neighbor_v: wp.vec3, neighbor_rho: float, smoothing_length: float):
# calculate distance
distance = wp.sqrt(wp.dot(xyz, xyz))
# calculate terms of kernel
if distance < smoothing_length:
term_1 = (neighbor_v - v) / neighbor_rho
term_2 = smoothing_length - distance
return term_1 * term_2
else:
return wp.vec3()
@wp.kernel
def compute_density(
grid: wp.uint64,
particle_x: wp.array(dtype=wp.vec3),
particle_rho: wp.array(dtype=float),
density_normalization: float,
smoothing_length: float,
):
tid = wp.tid()
# order threads by cell
i = wp.hash_grid_point_id(grid, tid)
# get local particle variables
x = particle_x[i]
# store density
rho = float(0.0)
# particle contact
neighbors = wp.hash_grid_query(grid, x, smoothing_length)
# loop through neighbors to compute density
for index in neighbors:
# compute distance
distance = x - particle_x[index]
# compute kernel derivative
rho += density_kernel(distance, smoothing_length)
# add external potential
particle_rho[i] = density_normalization * rho
@wp.kernel
def get_acceleration(
grid: wp.uint64,
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_rho: wp.array(dtype=float),
particle_a: wp.array(dtype=wp.vec3),
isotropic_exp: float,
base_density: float,
gravity: float,
pressure_normalization: float,
viscous_normalization: float,
smoothing_length: float,
):
tid = wp.tid()
# order threads by cell
i = wp.hash_grid_point_id(grid, tid)
# get local particle variables
x = particle_x[i]
v = particle_v[i]
rho = particle_rho[i]
pressure = isotropic_exp * (rho - base_density)
# store forces
pressure_force = wp.vec3()
viscous_force = wp.vec3()
# particle contact
neighbors = wp.hash_grid_query(grid, x, smoothing_length)
# loop through neighbors to compute acceleration
for index in neighbors:
if index != i:
# get neighbor velocity
neighbor_v = particle_v[index]
# get neighbor density and pressures
neighbor_rho = particle_rho[index]
neighbor_pressure = isotropic_exp * (neighbor_rho - base_density)
# compute relative position
relative_position = particle_x[index] - x
# calculate pressure force
pressure_force += diff_pressure_kernel(
relative_position, pressure, neighbor_pressure, neighbor_rho, smoothing_length
)
# compute kernel derivative
viscous_force += diff_viscous_kernel(relative_position, v, neighbor_v, neighbor_rho, smoothing_length)
# sum all forces
force = pressure_normalization * pressure_force + viscous_normalization * viscous_force
# add external potential
particle_a[i] = force / rho + wp.vec3(0.0, gravity, 0.0)
@wp.kernel
def apply_bounds(
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
damping_coef: float,
width: float,
height: float,
length: float,
):
tid = wp.tid()
# get pos and velocity
x = particle_x[tid]
v = particle_v[tid]
# clamp x left
if x[0] < 0.0:
x = wp.vec3(0.0, x[1], x[2])
v = wp.vec3(v[0] * damping_coef, v[1], v[2])
# clamp x right
if x[0] > width:
x = wp.vec3(width, x[1], x[2])
v = wp.vec3(v[0] * damping_coef, v[1], v[2])
# clamp y bot
if x[1] < 0.0:
x = wp.vec3(x[0], 0.0, x[2])
v = wp.vec3(v[0], v[1] * damping_coef, v[2])
# clamp z left
if x[2] < 0.0:
x = wp.vec3(x[0], x[1], 0.0)
v = wp.vec3(v[0], v[1], v[2] * damping_coef)
# clamp z right
if x[2] > length:
x = wp.vec3(x[0], x[1], length)
v = wp.vec3(v[0], v[1], v[2] * damping_coef)
# apply clamps
particle_x[tid] = x
particle_v[tid] = v
@wp.kernel
def kick(particle_v: wp.array(dtype=wp.vec3), particle_a: wp.array(dtype=wp.vec3), dt: float):
tid = wp.tid()
v = particle_v[tid]
particle_v[tid] = v + particle_a[tid] * dt
@wp.kernel
def drift(particle_x: wp.array(dtype=wp.vec3), particle_v: wp.array(dtype=wp.vec3), dt: float):
tid = wp.tid()
x = particle_x[tid]
particle_x[tid] = x + particle_v[tid] * dt
@wp.kernel
def initialize_particles(
particle_x: wp.array(dtype=wp.vec3), smoothing_length: float, width: float, height: float, length: float
):
tid = wp.tid()
# grid size
nr_x = wp.int32(width / 4.0 / smoothing_length)
nr_y = wp.int32(height / smoothing_length)
nr_z = wp.int32(length / 4.0 / smoothing_length)
# calculate particle position
z = wp.float(tid % nr_z)
y = wp.float((tid // nr_z) % nr_y)
x = wp.float((tid // (nr_z * nr_y)) % nr_x)
pos = smoothing_length * wp.vec3(x, y, z)
# add small jitter
state = wp.rand_init(123, tid)
pos = pos + 0.001 * smoothing_length * wp.vec3(wp.randn(state), wp.randn(state), wp.randn(state))
# set position
particle_x[tid] = pos
class Example:
def __init__(self, stage):
# render params
self.frame_dt = 1.0 / 60.0
self.frame_count = 600
self.renderer = wp.render.UsdRenderer(stage)
self.sim_time = 0.0
# simulation params
self.smoothing_length = 0.8 # NOTE change this to adjust number of particles
self.width = 80.0 # x
self.height = 80.0 # y
self.length = 80.0 # z
self.isotropic_exp = 20
self.base_density = 1.0
self.particle_mass = 0.01 * self.smoothing_length**3 # reduce according to smoothing length
self.dt = 0.01 * self.smoothing_length # decrease sim dt by smoothing length
self.dynamic_visc = 0.025
self.damping_coef = -0.95
self.gravity = -0.1
self.n = int(
self.height * (self.width / 4.0) * (self.height / 4.0) / (self.smoothing_length**3)
) # number particles (small box in corner)
self.sim_step_to_frame_ratio = int(32 / self.smoothing_length)
# constants
self.density_normalization = (315.0 * self.particle_mass) / (
64.0 * np.pi * self.smoothing_length**9
) # integrate density kernel
self.pressure_normalization = -(45.0 * self.particle_mass) / (np.pi * self.smoothing_length**6)
self.viscous_normalization = (45.0 * self.dynamic_visc * self.particle_mass) / (
np.pi * self.smoothing_length**6
)
# allocate arrays
self.x = wp.empty(tuple([self.n]), dtype=wp.vec3)
self.v = wp.zeros(tuple([self.n]), dtype=wp.vec3)
self.rho = wp.zeros(tuple([self.n]), dtype=float)
self.a = wp.zeros(tuple([self.n]), dtype=wp.vec3)
# set random positions
wp.launch(
kernel=initialize_particles,
dim=self.n,
inputs=[self.x, self.smoothing_length, self.width, self.height, self.length],
) # initialize in small area
# create hash array
grid_size = int(self.height / (4.0 * self.smoothing_length))
self.grid = wp.HashGrid(grid_size, grid_size, grid_size)
def update(self):
with wp.ScopedTimer("simulate", active=True):
for s in range(self.sim_step_to_frame_ratio):
with wp.ScopedTimer("grid build", active=False):
# build grid
self.grid.build(self.x, self.smoothing_length)
with wp.ScopedTimer("forces", active=False):
# compute density of points
wp.launch(
kernel=compute_density,
dim=self.n,
inputs=[self.grid.id, self.x, self.rho, self.density_normalization, self.smoothing_length],
)
# get new acceleration
wp.launch(
kernel=get_acceleration,
dim=self.n,
inputs=[
self.grid.id,
self.x,
self.v,
self.rho,
self.a,
self.isotropic_exp,
self.base_density,
self.gravity,
self.pressure_normalization,
self.viscous_normalization,
self.smoothing_length,
],
)
# apply bounds
wp.launch(
kernel=apply_bounds,
dim=self.n,
inputs=[self.x, self.v, self.damping_coef, self.width, self.height, self.length],
)
# kick
wp.launch(kernel=kick, dim=self.n, inputs=[self.v, self.a, self.dt])
# drift
wp.launch(kernel=drift, dim=self.n, inputs=[self.x, self.v, self.dt])
def render(self, is_live=False):
with wp.ScopedTimer("render", active=True):
time = 0.0 if is_live else self.sim_time
self.renderer.begin_frame(time)
self.renderer.render_points(points=self.x.numpy(), radius=self.smoothing_length, name="points")
self.renderer.end_frame()
self.sim_time += self.frame_dt
if __name__ == "__main__":
stage_path = os.path.join(os.path.dirname(__file__), "outputs/example_sph.usd")
example = Example(stage_path)
for i in range(example.frame_count):
example.render()
example.update()
example.renderer.save()
| warp-main | examples/example_sph.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#############################################################################
# Example Ray Cast
#
# Shows how to use the built-in wp.Mesh data structure and wp.mesh_query_ray()
# function to implement a basic ray-tracer.
#
##############################################################################
import matplotlib.pyplot as plt
from pxr import Usd, UsdGeom
import warp as wp
import numpy as np
import os
wp.init()
@wp.kernel
def draw(mesh: wp.uint64, cam_pos: wp.vec3, width: int, height: int, pixels: wp.array(dtype=wp.vec3)):
tid = wp.tid()
x = tid % width
y = tid // width
sx = 2.0 * float(x) / float(height) - 1.0
sy = 2.0 * float(y) / float(height) - 1.0
# compute view ray
ro = cam_pos
rd = wp.normalize(wp.vec3(sx, sy, -1.0))
t = float(0.0)
u = float(0.0)
v = float(0.0)
sign = float(0.0)
n = wp.vec3()
f = int(0)
color = wp.vec3(0.0, 0.0, 0.0)
if wp.mesh_query_ray(mesh, ro, rd, 1.0e6, t, u, v, sign, n, f):
color = n * 0.5 + wp.vec3(0.5, 0.5, 0.5)
pixels[tid] = color
class Example:
def __init__(self):
self.width = 1024
self.height = 1024
self.cam_pos = (0.0, 1.0, 2.0)
asset_stage = Usd.Stage.Open(os.path.join(os.path.dirname(__file__), "assets/bunny.usd"))
mesh_geom = UsdGeom.Mesh(asset_stage.GetPrimAtPath("/bunny/bunny"))
points = np.array(mesh_geom.GetPointsAttr().Get())
indices = np.array(mesh_geom.GetFaceVertexIndicesAttr().Get())
self.pixels = wp.zeros(self.width * self.height, dtype=wp.vec3)
# create wp mesh
self.mesh = wp.Mesh(
points=wp.array(points, dtype=wp.vec3), velocities=None, indices=wp.array(indices, dtype=int)
)
def update(self):
pass
def render(self, is_live=False):
with wp.ScopedTimer("render"):
wp.launch(
kernel=draw,
dim=self.width * self.height,
inputs=[self.mesh.id, self.cam_pos, self.width, self.height, self.pixels],
)
wp.synchronize_device()
plt.imshow(
self.pixels.numpy().reshape((self.height, self.width, 3)), origin="lower", interpolation="antialiased"
)
plt.show()
if __name__ == "__main__":
example = Example()
example.render()
| warp-main | examples/example_raycast.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Rigid Chain
#
# Shows how to set up a chain of rigid bodies connected by different joint
# types using wp.sim.ModelBuilder(). There is one chain for each joint
# type, including fixed joints which act as a flexible beam.
#
###########################################################################
import numpy as np
import os
import warp as wp
import warp.sim
import warp.sim.render
wp.init()
class Example:
frame_dt = 1.0 / 100.0
episode_duration = 5.0 # seconds
episode_frames = int(episode_duration / frame_dt)
sim_substeps = 32 # 5
sim_dt = frame_dt / sim_substeps
sim_steps = int(episode_duration / sim_dt)
sim_time = 0.0
render_time = 0.0
def __init__(self, stage=None, render=True):
self.chain_length = 8
self.chain_width = 1.0
self.chain_types = [
wp.sim.JOINT_REVOLUTE,
wp.sim.JOINT_FIXED,
wp.sim.JOINT_BALL,
wp.sim.JOINT_UNIVERSAL,
wp.sim.JOINT_COMPOUND,
]
self.enable_rendering = render
builder = wp.sim.ModelBuilder()
for c, t in enumerate(self.chain_types):
# start a new articulation
builder.add_articulation()
for i in range(self.chain_length):
if i == 0:
parent = -1
parent_joint_xform = wp.transform([0.0, 0.0, c * 1.0], wp.quat_identity())
else:
parent = builder.joint_count - 1
parent_joint_xform = wp.transform([self.chain_width, 0.0, 0.0], wp.quat_identity())
# create body
b = builder.add_body(origin=wp.transform([i, 0.0, c * 1.0], wp.quat_identity()), armature=0.1)
# create shape
s = builder.add_shape_box(
pos=(self.chain_width * 0.5, 0.0, 0.0),
hx=self.chain_width * 0.5,
hy=0.1,
hz=0.1,
density=10.0,
body=b,
)
joint_type = t
if joint_type == wp.sim.JOINT_REVOLUTE:
joint_limit_lower = -np.deg2rad(60.0)
joint_limit_upper = np.deg2rad(60.0)
builder.add_joint_revolute(
parent=parent,
child=b,
axis=(0.0, 0.0, 1.0),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
limit_lower=joint_limit_lower,
limit_upper=joint_limit_upper,
target_ke=0.0,
target_kd=0.0,
limit_ke=30.0,
limit_kd=30.0,
)
elif joint_type == wp.sim.JOINT_UNIVERSAL:
builder.add_joint_universal(
parent=parent,
child=b,
axis_0=wp.sim.JointAxis((1.0, 0.0, 0.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
axis_1=wp.sim.JointAxis((0.0, 0.0, 1.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
)
elif joint_type == wp.sim.JOINT_BALL:
builder.add_joint_ball(
parent=parent,
child=b,
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
)
elif joint_type == wp.sim.JOINT_FIXED:
builder.add_joint_fixed(
parent=parent,
child=b,
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
)
elif joint_type == wp.sim.JOINT_COMPOUND:
builder.add_joint_compound(
parent=parent,
child=b,
axis_0=wp.sim.JointAxis((1.0, 0.0, 0.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
axis_1=wp.sim.JointAxis((0.0, 1.0, 0.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
axis_2=wp.sim.JointAxis((0.0, 0.0, 1.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
)
# finalize model
self.model = builder.finalize()
self.model.ground = False
self.integrator = wp.sim.XPBDIntegrator(iterations=5)
# -----------------------
# set up Usd renderer
self.renderer = None
if render:
self.renderer = wp.sim.render.SimRenderer(self.model, stage, scaling=20.0)
def update(self):
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
self.state_0, self.state_1 = self.state_1, self.state_0
def render(self, is_live=False):
time = 0.0 if is_live else self.sim_time
self.renderer.begin_frame(time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
def run(self, render=True):
# ---------------
# run simulation
self.sim_time = 0.0
self.state_0 = self.model.state()
self.state_1 = self.model.state()
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state_0)
profiler = {}
# create update graph
wp.capture_begin()
# simulate
self.update()
graph = wp.capture_end()
# simulate
with wp.ScopedTimer("simulate", detailed=False, print=False, active=True, dict=profiler):
for f in range(0, self.episode_frames):
with wp.ScopedTimer("simulate", active=True):
wp.capture_launch(graph)
self.sim_time += self.frame_dt
if self.enable_rendering:
with wp.ScopedTimer("render", active=True):
self.render()
wp.synchronize()
if self.enable_rendering:
self.renderer.save()
if __name__ == "__main__":
stage = os.path.join(os.path.dirname(__file__), "outputs/example_sim_rigid_chain.usd")
robot = Example(stage, render=True)
robot.run()
| warp-main | examples/example_sim_rigid_chain.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Struct
#
# Shows how to define a custom struct and use it during gradient computation
#
###########################################################################
import numpy as np
import warp as wp
wp.init()
@wp.struct
class TestStruct:
x: wp.vec3
a: wp.array(dtype=wp.vec3)
b: wp.array(dtype=wp.vec3)
@wp.kernel
def test_kernel(s: TestStruct):
tid = wp.tid()
s.b[tid] = s.a[tid] + s.x
@wp.kernel
def loss_kernel(s: TestStruct, loss: wp.array(dtype=float)):
tid = wp.tid()
v = s.b[tid]
wp.atomic_add(loss, 0, float(tid + 1) * (v[0] + 2.0 * v[1] + 3.0 * v[2]))
# create struct
ts = TestStruct()
# set members
ts.x = wp.vec3(1.0, 2.0, 3.0)
ts.a = wp.array(
np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
dtype=wp.vec3,
requires_grad=True,
)
ts.b = wp.zeros(2, dtype=wp.vec3, requires_grad=True)
loss = wp.zeros(1, dtype=float, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(test_kernel, dim=2, inputs=[ts])
wp.launch(loss_kernel, dim=2, inputs=[ts, loss])
tape.backward(loss)
print(loss)
print(tape.gradients[ts].a)
| warp-main | examples/example_struct.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Mesh
#
# Shows how to implement a PBD particle simulation with collision against
# a deforming triangle mesh. The mesh collision uses wp.mesh_query_point_sign_normal()
# to compute the closest point, and wp.Mesh.refit() to update the mesh
# object after deformation.
#
###########################################################################
import numpy as np
import warp as wp
import warp.render
from pxr import Usd, UsdGeom
import os
wp.init()
@wp.kernel
def deform(positions: wp.array(dtype=wp.vec3), t: float):
tid = wp.tid()
x = positions[tid]
offset = -wp.sin(x[0]) * 0.02
scale = wp.sin(t)
x = x + wp.vec3(0.0, offset * scale, 0.0)
positions[tid] = x
@wp.kernel
def simulate(
positions: wp.array(dtype=wp.vec3),
velocities: wp.array(dtype=wp.vec3),
mesh: wp.uint64,
restitution: float,
margin: float,
dt: float,
):
tid = wp.tid()
x = positions[tid]
v = velocities[tid]
v = v + wp.vec3(0.0, 0.0 - 9.8, 0.0) * dt - v * 0.1 * dt
xpred = x + v * dt
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
max_dist = 1.5
if wp.mesh_query_point_sign_normal(mesh, xpred, max_dist, sign, face_index, face_u, face_v):
p = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
delta = xpred - p
dist = wp.length(delta) * sign
err = dist - margin
# mesh collision
if err < 0.0:
n = wp.normalize(delta) * sign
xpred = xpred - n * err
# pbd update
v = (xpred - x) * (1.0 / dt)
x = xpred
positions[tid] = x
velocities[tid] = v
class Example:
def __init__(self, stage):
self.num_particles = 1000
self.sim_steps = 500
self.sim_dt = 1.0 / 60.0
self.sim_time = 0.0
self.sim_timers = {}
self.sim_restitution = 0.0
self.sim_margin = 0.1
self.renderer = wp.render.UsdRenderer(stage)
usd_stage = Usd.Stage.Open(os.path.join(os.path.dirname(__file__), "assets/bunny.usd"))
usd_geom = UsdGeom.Mesh(usd_stage.GetPrimAtPath("/bunny/bunny"))
usd_scale = 10.0
# create collision mesh
self.mesh = wp.Mesh(
points=wp.array(usd_geom.GetPointsAttr().Get() * usd_scale, dtype=wp.vec3),
indices=wp.array(usd_geom.GetFaceVertexIndicesAttr().Get(), dtype=int),
)
# random particles
init_pos = (np.random.rand(self.num_particles, 3) - np.array([0.5, -1.5, 0.5])) * 10.0
init_vel = np.random.rand(self.num_particles, 3) * 0.0
self.positions = wp.from_numpy(init_pos, dtype=wp.vec3)
self.velocities = wp.from_numpy(init_vel, dtype=wp.vec3)
def update(self):
with wp.ScopedTimer("simulate", detailed=False, dict=self.sim_timers):
wp.launch(kernel=deform, dim=len(self.mesh.points), inputs=[self.mesh.points, self.sim_time])
# refit the mesh BVH to account for the deformation
self.mesh.refit()
wp.launch(
kernel=simulate,
dim=self.num_particles,
inputs=[
self.positions,
self.velocities,
self.mesh.id,
self.sim_restitution,
self.sim_margin,
self.sim_dt,
],
)
def render(self, is_live=False):
with wp.ScopedTimer("render", detailed=False):
time = 0.0 if is_live else self.sim_time
self.renderer.begin_frame(time)
self.renderer.render_mesh(name="mesh", points=self.mesh.points.numpy(), indices=self.mesh.indices.numpy())
self.renderer.render_points(name="points", points=self.positions.numpy(), radius=self.sim_margin)
self.renderer.end_frame()
self.sim_time += self.sim_dt
if __name__ == "__main__":
stage_path = os.path.join(os.path.dirname(__file__), "outputs/example_mesh.usd")
example = Example(stage_path)
for i in range(example.sim_steps):
example.update()
example.render()
example.renderer.save()
| warp-main | examples/example_mesh.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Cloth
#
# Shows a simulation of an FEM cloth model colliding against a static
# rigid body mesh using the wp.sim.ModelBuilder().
#
###########################################################################
import argparse
import os
import math
from enum import Enum
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
from pxr import Usd, UsdGeom
wp.init()
class IntegratorType(Enum):
EULER = "euler"
XPBD = "xpbd"
def __str__(self):
return self.value
class Example:
def __init__(self, stage):
self.parser = argparse.ArgumentParser()
self.parser.add_argument(
"--integrator",
help="Type of integrator",
type=IntegratorType,
choices=list(IntegratorType),
default=IntegratorType.EULER,
)
args = self.parser.parse_args()
self.integrator_type = args.integrator
self.sim_width = 64
self.sim_height = 32
self.sim_fps = 60.0
self.sim_substeps = 32
self.sim_duration = 5.0
self.sim_frames = int(self.sim_duration * self.sim_fps)
self.sim_dt = (1.0 / self.sim_fps) / self.sim_substeps
self.sim_time = 0.0
self.sim_use_graph = wp.get_device().is_cuda
self.simulate_timer = wp.ScopedTimer("simulate", dict={})
builder = wp.sim.ModelBuilder()
if self.integrator_type == IntegratorType.EULER:
builder.add_cloth_grid(
pos=(0.0, 4.0, 0.0),
rot=wp.quat_from_axis_angle((1.0, 0.0, 0.0), math.pi * 0.5),
vel=(0.0, 0.0, 0.0),
dim_x=self.sim_width,
dim_y=self.sim_height,
cell_x=0.1,
cell_y=0.1,
mass=0.1,
fix_left=True,
tri_ke=1.0e3,
tri_ka=1.0e3,
tri_kd=1.0e1,
)
else:
builder.add_cloth_grid(
pos=(0.0, 4.0, 0.0),
rot=wp.quat_from_axis_angle((1.0, 0.0, 0.0), math.pi * 0.5),
vel=(0.0, 0.0, 0.0),
dim_x=self.sim_width,
dim_y=self.sim_height,
cell_x=0.1,
cell_y=0.1,
mass=0.1,
fix_left=True,
edge_ke=1.0e2,
add_springs=True,
spring_ke=1.0e3,
spring_kd=0.0,
)
usd_stage = Usd.Stage.Open(os.path.join(os.path.dirname(__file__), "assets/bunny.usd"))
usd_geom = UsdGeom.Mesh(usd_stage.GetPrimAtPath("/bunny/bunny"))
mesh_points = np.array(usd_geom.GetPointsAttr().Get())
mesh_indices = np.array(usd_geom.GetFaceVertexIndicesAttr().Get())
mesh = wp.sim.Mesh(mesh_points, mesh_indices)
builder.add_shape_mesh(
body=-1,
mesh=mesh,
pos=(1.0, 0.0, 1.0),
rot=wp.quat_from_axis_angle((0.0, 1.0, 0.0), math.pi * 0.5),
scale=(2.0, 2.0, 2.0),
ke=1.0e2,
kd=1.0e2,
kf=1.0e1,
)
self.model = builder.finalize()
self.model.ground = True
self.model.soft_contact_ke = 1.0e4
self.model.soft_contact_kd = 1.0e2
if self.integrator_type == IntegratorType.EULER:
self.integrator = wp.sim.SemiImplicitIntegrator()
else:
self.integrator = wp.sim.XPBDIntegrator(iterations=1)
self.state_0 = self.model.state()
self.state_1 = self.model.state()
self.renderer = wp.sim.render.SimRenderer(self.model, stage, scaling=40.0)
if self.sim_use_graph:
# create update graph
wp.capture_begin()
wp.sim.collide(self.model, self.state_0)
for s in range(self.sim_substeps):
self.state_0.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
self.graph = wp.capture_end()
def update(self):
with self.simulate_timer:
if self.sim_use_graph:
wp.capture_launch(self.graph)
else:
wp.sim.collide(self.model, self.state_0)
for s in range(self.sim_substeps):
self.state_0.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def render(self, is_live=False):
with wp.ScopedTimer("render", active=True):
time = 0.0 if is_live else self.sim_time
self.renderer.begin_frame(time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
self.sim_time += 1.0 / self.sim_fps
if __name__ == "__main__":
stage_path = os.path.join(os.path.dirname(__file__), "outputs/example_sim_cloth.usd")
example = Example(stage_path)
for i in range(example.sim_frames):
example.update()
example.render()
frame_times = example.simulate_timer.dict["simulate"]
print("\nAverage frame sim time: {:.2f} ms".format(sum(frame_times) / len(frame_times)))
example.renderer.save()
| warp-main | examples/example_sim_cloth.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Multi-GPU
#
# A basic example that shows how to allocate arrays and launch kernels
# on all available CUDA devices.
#
###########################################################################
import warp as wp
wp.init()
@wp.kernel
def inc(a: wp.array(dtype=float)):
tid = wp.tid()
a[tid] = a[tid] + 1.0
# get all CUDA devices
devices = wp.get_cuda_devices()
device_count = len(devices)
# number of launches
iters = 1000
# list of arrays, one per device
arrs = []
# loop over all devices
for device in devices:
# use a ScopedDevice to set the target device
with wp.ScopedDevice(device):
# allocate array
a = wp.zeros(250 * 1024 * 1024, dtype=float)
arrs.append(a)
# launch kernels
for _ in range(iters):
wp.launch(inc, dim=a.size, inputs=[a])
# synchronize all devices
wp.synchronize()
# print results
for i in range(device_count):
print(f"{arrs[i].device} -> {arrs[i].numpy()}")
| warp-main | examples/example_multigpu.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Grad Bounce
#
# Shows how to use Warp to optimize the initial velocity of a particle
# such that it bounces off the wall and floor in order to hit a target.
#
# This example uses the built-in wp.Tape() object to compute gradients of
# the distance to target (loss) w.r.t the initial velocity, followed by
# a simple gradient-descent optimization step.
#
###########################################################################
import os
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
wp.init()
class Bounce:
# seconds
sim_duration = 0.6
# control frequency
frame_dt = 1.0 / 60.0
frame_steps = int(sim_duration / frame_dt)
# sim frequency
sim_substeps = 8
sim_steps = frame_steps * sim_substeps
sim_dt = frame_dt / sim_substeps
sim_time = 0.0
render_time = 0.0
train_iters = 250
train_rate = 0.02
ke = 1.0e4
kf = 0.0
kd = 1.0e1
mu = 0.25
def __init__(self, render=True, profile=False, adapter=None):
builder = wp.sim.ModelBuilder()
builder.add_particle(pos=(-0.5, 1.0, 0.0), vel=(5.0, -5.0, 0.0), mass=1.0)
builder.add_shape_box(
body=-1, pos=(2.0, 1.0, 0.0), hx=0.25, hy=1.0, hz=1.0, ke=self.ke, kf=self.kf, kd=self.kd, mu=self.mu
)
self.device = wp.get_device(adapter)
self.profile = profile
self.model = builder.finalize(self.device)
self.model.ground = True
self.model.soft_contact_ke = self.ke
self.model.soft_contact_kf = self.kf
self.model.soft_contact_kd = self.kd
self.model.soft_contact_mu = self.mu
self.model.soft_contact_margin = 10.0
self.model.soft_contact_restitution = 1.0
self.integrator = wp.sim.SemiImplicitIntegrator()
self.target = (-2.0, 1.5, 0.0)
self.loss = wp.zeros(1, dtype=wp.float32, device=self.device, requires_grad=True)
# allocate sim states for trajectory
self.states = []
for i in range(self.sim_steps + 1):
self.states.append(self.model.state(requires_grad=True))
# one-shot contact creation (valid if we're doing simple collision against a constant normal plane)
wp.sim.collide(self.model, self.states[0])
self.stage = None
if render:
self.stage = wp.sim.render.SimRendererOpenGL(
self.model, os.path.join(os.path.dirname(__file__), "outputs/example_sim_grad_bounce.usd"), scaling=1.0
)
@wp.kernel
def loss_kernel(pos: wp.array(dtype=wp.vec3), target: wp.vec3, loss: wp.array(dtype=float)):
# distance to target
delta = pos[0] - target
loss[0] = wp.dot(delta, delta)
@wp.kernel
def step_kernel(x: wp.array(dtype=wp.vec3), grad: wp.array(dtype=wp.vec3), alpha: float):
tid = wp.tid()
# gradient descent step
x[tid] = x[tid] - grad[tid] * alpha
def compute_loss(self):
# run control loop
for i in range(self.sim_steps):
self.states[i].clear_forces()
self.integrator.simulate(self.model, self.states[i], self.states[i + 1], self.sim_dt)
# compute loss on final state
wp.launch(
self.loss_kernel, dim=1, inputs=[self.states[-1].particle_q, self.target, self.loss], device=self.device
)
return self.loss
def render(self, iter):
if self.stage is None:
return
# render every 16 iters
if iter % 16 > 0:
return
# draw trajectory
traj_verts = [self.states[0].particle_q.numpy()[0].tolist()]
for i in range(0, self.sim_steps, self.sim_substeps):
traj_verts.append(self.states[i].particle_q.numpy()[0].tolist())
self.stage.begin_frame(self.render_time)
self.stage.render(self.states[i])
self.stage.render_box(pos=self.target, rot=wp.quat_identity(), extents=(0.1, 0.1, 0.1), name="target")
self.stage.render_line_strip(
vertices=traj_verts,
color=wp.render.bourke_color_map(0.0, 7.0, self.loss.numpy()[0]),
radius=0.02,
name=f"traj_{iter}",
)
self.stage.end_frame()
self.render_time += self.frame_dt
def check_grad(self):
param = self.states[0].particle_qd
# initial value
x_c = param.numpy().flatten()
# compute numeric gradient
x_grad_numeric = np.zeros_like(x_c)
for i in range(len(x_c)):
eps = 1.0e-3
step = np.zeros_like(x_c)
step[i] = eps
x_1 = x_c + step
x_0 = x_c - step
param.assign(x_1)
l_1 = self.compute_loss().numpy()[0]
param.assign(x_0)
l_0 = self.compute_loss().numpy()[0]
dldx = (l_1 - l_0) / (eps * 2.0)
x_grad_numeric[i] = dldx
# reset initial state
param.assign(x_c)
# compute analytic gradient
tape = wp.Tape()
with tape:
l = self.compute_loss()
tape.backward(l)
x_grad_analytic = tape.gradients[param]
print(f"numeric grad: {x_grad_numeric}")
print(f"analytic grad: {x_grad_analytic}")
tape.zero()
def train(self):
for i in range(self.train_iters):
tape = wp.Tape()
with wp.ScopedTimer("Forward", active=self.profile):
with tape:
self.compute_loss()
with wp.ScopedTimer("Backward", active=self.profile):
tape.backward(self.loss)
with wp.ScopedTimer("Render", active=self.profile):
self.render(i)
with wp.ScopedTimer("Step", active=self.profile):
x = self.states[0].particle_qd
x_grad = tape.gradients[self.states[0].particle_qd]
print(f"Iter: {i} Loss: {self.loss}")
print(f" x: {x} g: {x_grad}")
wp.launch(self.step_kernel, dim=len(x), inputs=[x, x_grad, self.train_rate], device=self.device)
tape.zero()
if self.stage is not None:
self.stage.save()
def train_graph(self):
# capture forward/backward passes
wp.capture_begin()
tape = wp.Tape()
with tape:
self.compute_loss()
tape.backward(self.loss)
self.graph = wp.capture_end()
# replay and optimize
for i in range(self.train_iters):
with wp.ScopedTimer("Step", active=self.profile):
# forward + backward
wp.capture_launch(self.graph)
# gradient descent step
x = self.states[0].particle_qd
wp.launch(self.step_kernel, dim=len(x), inputs=[x, x.grad, self.train_rate], device=self.device)
x_grad = tape.gradients[self.states[0].particle_qd]
print(f"Iter: {i} Loss: {self.loss}")
print(f" x: {x} g: {x_grad}")
# clear grads for next iteration
tape.zero()
with wp.ScopedTimer("Render", active=self.profile):
self.render(i)
if self.stage is not None:
self.stage.save()
bounce = Bounce(profile=False, render=True)
bounce.check_grad()
bounce.train_graph()
| warp-main | examples/example_sim_grad_bounce.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#############################################################################
# Example Mesh Intersection
#
# Show how to use built-in BVH query to test if two triangle meshes intersect.
#
##############################################################################
import warp as wp
import warp.render
import numpy as np
np.random.seed(42)
from pxr import Usd, UsdGeom
import os
wp.init()
@wp.func
def cw_min(a: wp.vec3, b: wp.vec3):
return wp.vec3(wp.min(a[0], b[0]), wp.min(a[1], b[1]), wp.min(a[2], b[2]))
@wp.func
def cw_max(a: wp.vec3, b: wp.vec3):
return wp.vec3(wp.max(a[0], b[0]), wp.max(a[1], b[1]), wp.max(a[2], b[2]))
@wp.kernel
def intersect(
mesh_0: wp.uint64,
mesh_1: wp.uint64,
num_faces: int,
xforms: wp.array(dtype=wp.transform),
result: wp.array(dtype=int),
):
tid = wp.tid()
# mesh_0 is assumed to be the query mesh, we launch one thread
# for each face in mesh_0 and test it against the opposing mesh's BVH
face = tid % num_faces
batch = tid // num_faces
# transforms from mesh_0 -> mesh_1 space
xform = xforms[batch]
# load query triangles points and transform to mesh_1's space
v0 = wp.transform_point(xform, wp.mesh_eval_position(mesh_0, face, 1.0, 0.0))
v1 = wp.transform_point(xform, wp.mesh_eval_position(mesh_0, face, 0.0, 1.0))
v2 = wp.transform_point(xform, wp.mesh_eval_position(mesh_0, face, 0.0, 0.0))
# compute bounds of the query triangle
lower = cw_min(cw_min(v0, v1), v2)
upper = cw_max(cw_max(v0, v1), v2)
query = wp.mesh_query_aabb(mesh_1, lower, upper)
for f in query:
u0 = wp.mesh_eval_position(mesh_1, f, 1.0, 0.0)
u1 = wp.mesh_eval_position(mesh_1, f, 0.0, 1.0)
u2 = wp.mesh_eval_position(mesh_1, f, 0.0, 0.0)
# test for triangle intersection
i = wp.intersect_tri_tri(v0, v1, v2, u0, u1, u2)
if i > 0:
result[batch] = 1
return
# use if you want to count all intersections
# wp.atomic_add(result, batch, i)
class Example:
def __init__(self, stage):
self.query_count = 1024
self.has_queried = False
self.renderer = wp.render.UsdRenderer(stage)
self.path_0 = "assets/cube.usda"
self.path_1 = "assets/sphere.usda"
self.mesh_0 = self.load_mesh(self.path_0, "/Cube/Cube_001")
self.mesh_1 = self.load_mesh(self.path_1, "/Sphere/Sphere")
self.query_num_faces = int(len(self.mesh_0.indices) / 3)
self.query_num_points = len(self.mesh_0.points)
# generate random relative transforms
self.xforms = []
for i in range(self.query_count):
# random offset
p = (np.random.rand(3) * 0.5 - 0.5) * 5.0
# random orientation
axis = wp.normalize(np.random.rand(3) * 0.5 - 0.5)
angle = float(np.random.rand(1)[0])
q = wp.quat_from_axis_angle(wp.normalize(axis), angle)
self.xforms.append(wp.transform(p, q))
self.array_result = wp.zeros(self.query_count, dtype=int)
self.array_xforms = wp.array(self.xforms, dtype=wp.transform)
# force module load (for accurate profiling)
wp.force_load()
def update(self):
with wp.ScopedTimer("intersect", active=True):
wp.launch(
kernel=intersect,
dim=self.query_num_faces * self.query_count,
inputs=[self.mesh_0.id, self.mesh_1.id, self.query_num_faces, self.array_xforms, self.array_result],
)
wp.synchronize()
def render(self, is_live=False):
# bring results back to host
result = self.array_result.numpy()
print(result)
with wp.ScopedTimer("render", active=True):
self.renderer.begin_frame(0.0)
for i in range(self.query_count):
spacing = 8.0
offset = i * spacing
xform = self.xforms[i]
self.renderer.render_ref(
f"mesh_{i}_0",
os.path.join(os.path.dirname(__file__), self.path_0),
pos=wp.vec3(xform.p[0] + offset, xform.p[1], xform.p[2]),
rot=xform.q,
scale=(1.0, 1.0, 1.0),
)
self.renderer.render_ref(
f"mesh_{i}_1",
os.path.join(os.path.dirname(__file__), self.path_1),
pos=(offset, 0.0, 0.0),
rot=wp.quat_identity(),
scale=(1.0, 1.0, 1.0),
)
# if pair intersects then draw a small box above the pair
if result[i] > 0:
self.renderer.render_box(
f"result_{i}",
pos=wp.vec3(xform.p[0] + offset, xform.p[1] + 5.0, xform.p[2]),
rot=wp.quat_identity(),
extents=(0.1, 0.1, 0.1),
)
self.renderer.end_frame()
# create collision meshes
def load_mesh(self, path, prim):
usd_path = os.path.join(os.path.dirname(__file__), path)
usd_stage = Usd.Stage.Open(usd_path)
usd_geom = UsdGeom.Mesh(usd_stage.GetPrimAtPath(prim))
mesh = wp.Mesh(
points=wp.array(usd_geom.GetPointsAttr().Get(), dtype=wp.vec3),
indices=wp.array(usd_geom.GetFaceVertexIndicesAttr().Get(), dtype=int),
)
return mesh
if __name__ == "__main__":
stage_path = os.path.join(os.path.dirname(__file__), "outputs/example_mesh_intersect.usd")
example = Example(stage_path)
example.update()
example.render()
example.renderer.save()
| warp-main | examples/example_mesh_intersect.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Ray March
#
# Shows how to implement an SDF ray marching based renderer. Please see
# https://iquilezles.org/www/articles/distfunctions/distfunctions.htm
# for reference on different distance functions.
#
###########################################################################
import matplotlib.pyplot as plt
import warp as wp
wp.init()
# signed sphere
@wp.func
def sdf_sphere(p: wp.vec3, r: float):
return wp.length(p) - r
# signed box
@wp.func
def sdf_box(upper: wp.vec3, p: wp.vec3):
qx = wp.abs(p[0]) - upper[0]
qy = wp.abs(p[1]) - upper[1]
qz = wp.abs(p[2]) - upper[2]
e = wp.vec3(wp.max(qx, 0.0), wp.max(qy, 0.0), wp.max(qz, 0.0))
return wp.length(e) + wp.min(wp.max(qx, wp.max(qy, qz)), 0.0)
@wp.func
def sdf_plane(p: wp.vec3, plane: wp.vec4):
return plane[0] * p[0] + plane[1] * p[1] + plane[2] * p[2] + plane[3]
# union
@wp.func
def op_union(d1: float, d2: float):
return wp.min(d1, d2)
# subtraction
@wp.func
def op_subtract(d1: float, d2: float):
return wp.max(-d1, d2)
# intersection
@wp.func
def op_intersect(d1: float, d2: float):
return wp.max(d1, d2)
# simple scene
@wp.func
def sdf(p: wp.vec3):
# intersection of two spheres
sphere_1 = wp.vec3(0.0, 0.0, 0.0)
sphere_2 = wp.vec3(0.0, 0.75, 0.0)
d = op_subtract(sdf_sphere(p - sphere_2, 0.75), sdf_box(wp.vec3(1.0, 0.5, 0.5), p))
# sdf_sphere(p + sphere_1, 1.0))
# ground plane
d = op_union(d, sdf_plane(p, wp.vec4(0.0, 1.0, 0.0, 1.0)))
return d
@wp.func
def normal(p: wp.vec3):
eps = 1.0e-5
# compute gradient of the SDF using finite differences
dx = sdf(p + wp.vec3(eps, 0.0, 0.0)) - sdf(p - wp.vec3(eps, 0.0, 0.0))
dy = sdf(p + wp.vec3(0.0, eps, 0.0)) - sdf(p - wp.vec3(0.0, eps, 0.0))
dz = sdf(p + wp.vec3(0.0, 0.0, eps)) - sdf(p - wp.vec3(0.0, 0.0, eps))
return wp.normalize(wp.vec3(dx, dy, dz))
@wp.func
def shadow(ro: wp.vec3, rd: wp.vec3):
t = float(0.0)
s = float(1.0)
for i in range(64):
d = sdf(ro + t * rd)
t = t + wp.clamp(d, 0.0001, 2.0)
h = wp.clamp(4.0 * d / t, 0.0, 1.0)
s = wp.min(s, h * h * (3.0 - 2.0 * h))
if t > 8.0:
return 1.0
return s
@wp.kernel
def draw(cam_pos: wp.vec3, cam_rot: wp.quat, width: int, height: int, pixels: wp.array(dtype=wp.vec3)):
tid = wp.tid()
x = tid % width
y = tid // width
# compute pixel coordinates
sx = (2.0 * float(x) - float(width)) / float(height)
sy = (2.0 * float(y) - float(height)) / float(height)
# compute view ray
ro = cam_pos
rd = wp.quat_rotate(cam_rot, wp.normalize(wp.vec3(sx, sy, -2.0)))
t = float(0.0)
# ray march
for i in range(128):
d = sdf(ro + rd * t)
t = t + d
if d < 0.01:
p = ro + rd * t
n = normal(p)
l = wp.normalize(wp.vec3(0.6, 0.4, 0.5))
# half-vector
h = wp.normalize(l - rd)
diffuse = wp.dot(n, l)
specular = wp.clamp(wp.dot(n, h), 0.0, 1.0) ** 80.0
fresnel = 0.04 + 0.96 * wp.clamp(1.0 - wp.dot(h, l), 0.0, 1.0) ** 5.0
intensity = 2.0
result = (
wp.vec3(0.6, 0.6, 0.59) * (diffuse * (1.0 - fresnel) + specular * fresnel * 10.0) * shadow(p, l) * intensity
)
# gamma
pixels[tid] = wp.vec3(result[0] ** 2.2, result[1] ** 2.2, result[2] ** 2.2)
else:
pixels[tid] = wp.vec3(0.4, 0.45, 0.5) * 1.5
class Example:
def __init__(self):
self.width = 2048
self.height = 1024
self.cam_pos = (-1.25, 1.0, 2.0)
self.cam_rot = wp.quat_rpy(-0.5, -0.5, 0.0)
self.pixels = wp.zeros(self.width * self.height, dtype=wp.vec3)
def render(self, is_live=False):
with wp.ScopedTimer("render"):
wp.launch(
kernel=draw,
dim=self.width * self.height,
inputs=[self.cam_pos, self.cam_rot, self.width, self.height, self.pixels],
)
wp.synchronize_device()
plt.imshow(
self.pixels.numpy().reshape((self.height, self.width, 3)), origin="lower", interpolation="antialiased"
)
plt.show()
if __name__ == "__main__":
example = Example()
example.render()
| warp-main | examples/example_raymarch.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Rigid Kinematics
#
# Tests rigid body forward and backwards kinematics through the
# wp.sim.eval_ik() and wp.sim.eval_fk() methods.
#
###########################################################################
import os
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
wp.init()
TARGET = wp.constant(wp.vec3(2.0, 1.0, 0.0))
@wp.kernel
def compute_loss(body_q: wp.array(dtype=wp.transform), body_index: int, loss: wp.array(dtype=float)):
x = wp.transform_get_translation(body_q[body_index])
delta = x - TARGET
loss[0] = wp.dot(delta, delta)
@wp.kernel
def step_kernel(x: wp.array(dtype=float), grad: wp.array(dtype=float), alpha: float):
tid = wp.tid()
# gradient descent step
x[tid] = x[tid] - grad[tid] * alpha
class Robot:
def __init__(self, render=True, num_envs=1, device=None):
builder = wp.sim.ModelBuilder()
builder.add_articulation()
chain_length = 4
chain_width = 1.0
for i in range(chain_length):
if i == 0:
parent = -1
parent_joint_xform = wp.transform([0.0, 0.0, 0.0], wp.quat_identity())
else:
parent = builder.joint_count - 1
parent_joint_xform = wp.transform([chain_width, 0.0, 0.0], wp.quat_identity())
# create body
b = builder.add_body(origin=wp.transform([i, 0.0, 0.0], wp.quat_identity()), armature=0.1)
builder.add_joint_revolute(
parent=parent,
child=b,
axis=(0.0, 0.0, 1.0),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
limit_lower=-np.deg2rad(60.0),
limit_upper=np.deg2rad(60.0),
target_ke=0.0,
target_kd=0.0,
limit_ke=30.0,
limit_kd=30.0,
)
if i == chain_length - 1:
# create end effector
s = builder.add_shape_sphere(pos=(0.0, 0.0, 0.0), radius=0.1, density=10.0, body=b)
else:
# create shape
s = builder.add_shape_box(
pos=(chain_width * 0.5, 0.0, 0.0), hx=chain_width * 0.5, hy=0.1, hz=0.1, density=10.0, body=b
)
self.device = wp.get_device(device)
# finalize model
self.model = builder.finalize(self.device)
self.model.ground = False
self.state = self.model.state()
# -----------------------
# set up Usd renderer
self.renderer = wp.sim.render.SimRenderer(
self.model, os.path.join(os.path.dirname(__file__), "outputs/example_sim_fk_grad.usd"), scaling=50.0
)
def run(self, render=True):
render_time = 0.0
train_iters = 1024
train_rate = 0.01
# optimization variables
self.loss = wp.zeros(1, dtype=float, device=self.device)
self.model.joint_q.requires_grad = True
self.state.body_q.requires_grad = True
self.loss.requires_grad = True
for i in range(train_iters):
tape = wp.Tape()
with tape:
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state)
wp.launch(
compute_loss,
dim=1,
inputs=[self.state.body_q, len(self.state.body_q) - 1, self.loss],
device=self.device,
)
tape.backward(loss=self.loss)
print(self.loss)
print(tape.gradients[self.model.joint_q])
# gradient descent
wp.launch(
step_kernel,
dim=len(self.model.joint_q),
inputs=[self.model.joint_q, tape.gradients[self.model.joint_q], train_rate],
device=self.device,
)
# zero gradients
tape.zero()
# render
self.renderer.begin_frame(render_time)
self.renderer.render(self.state)
self.renderer.render_sphere(name="target", pos=TARGET, rot=wp.quat_identity(), radius=0.1)
self.renderer.end_frame()
render_time += 1.0 / 60.0
self.renderer.save()
robot = Robot(render=True, device=wp.get_preferred_device(), num_envs=1)
robot.run()
| warp-main | examples/example_sim_fk_grad.py |
# Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Bechmarks for kernel launches with different types of args
###########################################################################
import warp as wp
@wp.struct
class S0:
pass
@wp.struct
class Sf:
x: float
y: float
z: float
@wp.struct
class Sv:
u: wp.vec3
v: wp.vec3
w: wp.vec3
@wp.struct
class Sm:
M: wp.mat33
N: wp.mat33
O: wp.mat33
@wp.struct
class Sa:
a: wp.array(dtype=float)
b: wp.array(dtype=float)
c: wp.array(dtype=float)
@wp.struct
class Sz:
a: wp.array(dtype=float)
b: wp.array(dtype=float)
c: wp.array(dtype=float)
x: float
y: float
z: float
u: wp.vec3
v: wp.vec3
w: wp.vec3
@wp.kernel
def k0():
tid = wp.tid()
@wp.kernel
def kf(x: float, y: float, z: float):
tid = wp.tid()
@wp.kernel
def kv(u: wp.vec3, v: wp.vec3, w: wp.vec3):
tid = wp.tid()
@wp.kernel
def km(M: wp.mat33, N: wp.mat33, O: wp.mat33):
tid = wp.tid()
@wp.kernel
def ka(a: wp.array(dtype=float), b: wp.array(dtype=float), c: wp.array(dtype=float)):
tid = wp.tid()
@wp.kernel
def kz(
a: wp.array(dtype=float),
b: wp.array(dtype=float),
c: wp.array(dtype=float),
x: float,
y: float,
z: float,
u: wp.vec3,
v: wp.vec3,
w: wp.vec3,
):
tid = wp.tid()
@wp.kernel
def ks0(s: S0):
tid = wp.tid()
@wp.kernel
def ksf(s: Sf):
tid = wp.tid()
@wp.kernel
def ksv(s: Sv):
tid = wp.tid()
@wp.kernel
def ksm(s: Sm):
tid = wp.tid()
@wp.kernel
def ksa(s: Sa):
tid = wp.tid()
@wp.kernel
def ksz(s: Sz):
tid = wp.tid()
wp.init()
wp.build.clear_kernel_cache()
devices = wp.get_devices()
num_launches = 100000
for device in devices:
with wp.ScopedDevice(device):
print(f"\n=================== Device '{device}' ===================")
wp.force_load(device)
n = 1
a = wp.zeros(n, dtype=float)
b = wp.zeros(n, dtype=float)
c = wp.zeros(n, dtype=float)
x = 17.0
y = 42.0
z = 99.0
u = wp.vec3(1, 2, 3)
v = wp.vec3(10, 20, 30)
w = wp.vec3(100, 200, 300)
M = wp.mat33()
N = wp.mat33()
O = wp.mat33()
s0 = S0()
sf = Sf()
sf.x = x
sf.y = y
sf.z = z
sv = Sv()
sv.u = u
sv.v = v
sv.w = w
sm = Sm()
sm.M = M
sm.N = N
sm.O = O
sa = Sa()
sa.a = a
sa.b = b
sa.c = c
sz = Sz()
sz.a = a
sz.b = b
sz.c = c
sz.x = x
sz.y = y
sz.z = z
sz.u = u
sz.v = v
sz.w = w
tk0 = wp.ScopedTimer("k0")
tkf = wp.ScopedTimer("kf")
tkv = wp.ScopedTimer("kv")
tkm = wp.ScopedTimer("km")
tka = wp.ScopedTimer("ka")
tkz = wp.ScopedTimer("kz")
ts0 = wp.ScopedTimer("s0")
tsf = wp.ScopedTimer("sf")
tsv = wp.ScopedTimer("sv")
tsm = wp.ScopedTimer("sm")
tsa = wp.ScopedTimer("sa")
tsz = wp.ScopedTimer("sz")
wp.synchronize_device()
with tk0:
for _ in range(num_launches):
wp.launch(k0, dim=1, inputs=[])
wp.synchronize_device()
with tkf:
for _ in range(num_launches):
wp.launch(kf, dim=1, inputs=[x, y, z])
wp.synchronize_device()
with tkv:
for _ in range(num_launches):
wp.launch(kv, dim=1, inputs=[u, v, w])
wp.synchronize_device()
with tkm:
for _ in range(num_launches):
wp.launch(km, dim=1, inputs=[M, N, O])
wp.synchronize_device()
with tka:
for _ in range(num_launches):
wp.launch(ka, dim=1, inputs=[a, b, c])
wp.synchronize_device()
with tkz:
for _ in range(num_launches):
wp.launch(kz, dim=1, inputs=[a, b, c, x, y, z, u, v, w])
# structs
wp.synchronize_device()
with ts0:
for _ in range(num_launches):
wp.launch(ks0, dim=1, inputs=[s0])
wp.synchronize_device()
with tsf:
for _ in range(num_launches):
wp.launch(ksf, dim=1, inputs=[sf])
wp.synchronize_device()
with tsv:
for _ in range(num_launches):
wp.launch(ksv, dim=1, inputs=[sv])
wp.synchronize_device()
with tsm:
for _ in range(num_launches):
wp.launch(ksm, dim=1, inputs=[sm])
wp.synchronize_device()
with tsa:
for _ in range(num_launches):
wp.launch(ksa, dim=1, inputs=[sa])
wp.synchronize_device()
with tsz:
for _ in range(num_launches):
wp.launch(ksz, dim=1, inputs=[sz])
wp.synchronize_device()
timers = [
[tk0, ts0],
[tkf, tsf],
[tkv, tsv],
[tkm, tsm],
[tka, tsa],
[tkz, tsz],
]
print("--------------------------------")
print(f"| args | direct | struct |")
print("--------------------------------")
for tk, ts in timers:
print(f"| {tk.name} |{tk.elapsed:10.0f} |{ts.elapsed:10.0f} |")
print("--------------------------------")
| warp-main | examples/benchmark_launches.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Quadruped
#
# Shows how to set up a simulation of a rigid-body quadruped articulation
# from a URDF using the wp.sim.ModelBuilder().
# Note this example does not include a trained policy.
#
###########################################################################
import math
import numpy as np
import os
import warp as wp
import warp.sim
import warp.sim.render
from env.environment import compute_env_offsets
wp.init()
class Example:
frame_dt = 1.0 / 100.0
episode_duration = 5.0 # seconds
episode_frames = int(episode_duration / frame_dt)
sim_substeps = 5
sim_dt = frame_dt / sim_substeps
sim_steps = int(episode_duration / sim_dt)
sim_time = 0.0
render_time = 0.0
def __init__(self, stage=None, render=True, num_envs=1):
self.enable_rendering = render
self.num_envs = num_envs
articulation_builder = wp.sim.ModelBuilder()
wp.sim.parse_urdf(
os.path.join(os.path.dirname(__file__), "assets/quadruped.urdf"),
articulation_builder,
xform=wp.transform([0.0, 0.7, 0.0], wp.quat_from_axis_angle((1.0, 0.0, 0.0), -math.pi * 0.5)),
floating=True,
density=1000,
armature=0.01,
stiffness=120,
damping=1,
shape_ke=1.0e4,
shape_kd=1.0e2,
shape_kf=1.0e2,
shape_mu=0.0,
limit_ke=1.0e4,
limit_kd=1.0e1,
)
builder = wp.sim.ModelBuilder()
offsets = compute_env_offsets(num_envs)
for i in range(num_envs):
builder.add_builder(articulation_builder, xform=wp.transform(offsets[i], wp.quat_identity()))
builder.joint_q[-12:] = [0.2, 0.4, -0.6, -0.2, -0.4, 0.6, -0.2, 0.4, -0.6, 0.2, -0.4, 0.6]
builder.joint_target[-12:] = [0.2, 0.4, -0.6, -0.2, -0.4, 0.6, -0.2, 0.4, -0.6, 0.2, -0.4, 0.6]
np.set_printoptions(suppress=True)
# finalize model
self.model = builder.finalize()
self.model.ground = True
self.model.joint_attach_ke = 16000.0
self.model.joint_attach_kd = 200.0
self.integrator = wp.sim.XPBDIntegrator()
# -----------------------
# set up Usd renderer
self.renderer = None
if render:
self.renderer = wp.sim.render.SimRenderer(self.model, stage)
def update(self):
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
wp.sim.collide(self.model, self.state_0)
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
self.state_0, self.state_1 = self.state_1, self.state_0
def render(self, is_live=False):
time = 0.0 if is_live else self.sim_time
self.renderer.begin_frame(time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
def run(self, render=True):
# ---------------
# run simulation
self.sim_time = 0.0
self.state_0 = self.model.state()
self.state_1 = self.model.state()
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state_0)
profiler = {}
# create update graph
wp.capture_begin()
# simulate
self.update()
graph = wp.capture_end()
# simulate
with wp.ScopedTimer("simulate", detailed=False, print=False, active=True, dict=profiler):
for f in range(0, self.episode_frames):
with wp.ScopedTimer("simulate", active=True):
wp.capture_launch(graph)
self.sim_time += self.frame_dt
if self.enable_rendering:
with wp.ScopedTimer("render", active=True):
self.render()
self.renderer.save()
wp.synchronize()
avg_time = np.array(profiler["simulate"]).mean() / self.episode_frames
avg_steps_second = 1000.0 * float(self.num_envs) / avg_time
print(f"envs: {self.num_envs} steps/second {avg_steps_second} avg_time {avg_time}")
return 1000.0 * float(self.num_envs) / avg_time
profile = False
if profile:
env_count = 2
env_times = []
env_size = []
for i in range(15):
robot = Example(render=False, num_envs=env_count)
steps_per_second = robot.run()
env_size.append(env_count)
env_times.append(steps_per_second)
env_count *= 2
# dump times
for i in range(len(env_times)):
print(f"envs: {env_size[i]} steps/second: {env_times[i]}")
# plot
import matplotlib.pyplot as plt
plt.figure(1)
plt.plot(env_size, env_times)
plt.xscale("log")
plt.xlabel("Number of Envs")
plt.yscale("log")
plt.ylabel("Steps/Second")
plt.show()
else:
stage = os.path.join(os.path.dirname(__file__), "outputs/example_sim_quadruped.usd")
robot = Example(stage, render=True, num_envs=25)
robot.run()
| warp-main | examples/example_sim_quadruped.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Rigid Kinematics
#
# Tests rigid body forward and backwards kinematics through the
# wp.sim.eval_ik() and wp.sim.eval_fk() methods. Shows how to connect
# gradients from Warp to PyTorch, through custom autograd nodes.
#
###########################################################################
import os
import numpy as np
import torch
import warp as wp
import warp.sim
import warp.sim.render
wp.init()
class ForwardKinematics(torch.autograd.Function):
@staticmethod
def forward(ctx, joint_q, joint_qd, model):
# ensure Torch operations complete before running Warp
wp.synchronize_device()
ctx.tape = wp.Tape()
ctx.model = model
ctx.joint_q = wp.from_torch(joint_q)
ctx.joint_qd = wp.from_torch(joint_qd)
# allocate output
ctx.state = model.state()
with ctx.tape:
wp.sim.eval_fk(model, ctx.joint_q, ctx.joint_qd, None, ctx.state)
# ensure Warp operations complete before returning data to Torch
wp.synchronize_device()
return (wp.to_torch(ctx.state.body_q), wp.to_torch(ctx.state.body_qd))
@staticmethod
def backward(ctx, adj_body_q, adj_body_qd):
# ensure Torch operations complete before running Warp
wp.synchronize_device()
# map incoming Torch grads to our output variables
ctx.state.body_q.grad = wp.from_torch(adj_body_q, dtype=wp.transform)
ctx.state.body_qd.grad = wp.from_torch(adj_body_qd, dtype=wp.spatial_vector)
ctx.tape.backward()
# ensure Warp operations complete before returning data to Torch
wp.synchronize_device()
# return adjoint w.r.t. inputs
return (wp.to_torch(ctx.tape.gradients[ctx.joint_q]), wp.to_torch(ctx.tape.gradients[ctx.joint_qd]), None)
class Robot:
def __init__(self, render=True, num_envs=1, device=None):
builder = wp.sim.ModelBuilder()
builder.add_articulation()
chain_length = 4
chain_width = 1.0
for i in range(chain_length):
if i == 0:
parent = -1
parent_joint_xform = wp.transform([0.0, 0.0, 0.0], wp.quat_identity())
else:
parent = builder.joint_count - 1
parent_joint_xform = wp.transform([chain_width, 0.0, 0.0], wp.quat_identity())
# create body
b = builder.add_body(origin=wp.transform([i, 0.0, 0.0], wp.quat_identity()), armature=0.1)
builder.add_joint_revolute(
parent=parent,
child=b,
axis=(0.0, 0.0, 1.0),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
limit_lower=-np.deg2rad(60.0),
limit_upper=np.deg2rad(60.0),
target_ke=0.0,
target_kd=0.0,
limit_ke=30.0,
limit_kd=30.0,
)
if i == chain_length - 1:
# create end effector
s = builder.add_shape_sphere(pos=(0.0, 0.0, 0.0), radius=0.1, density=10.0, body=b)
else:
# create shape
s = builder.add_shape_box(
pos=(chain_width * 0.5, 0.0, 0.0), hx=chain_width * 0.5, hy=0.1, hz=0.1, density=10.0, body=b
)
# finalize model
self.model = builder.finalize(device)
self.model.ground = False
self.torch_device = wp.device_to_torch(self.model.device)
# -----------------------
# set up Usd renderer
self.renderer = wp.sim.render.SimRenderer(
self.model, os.path.join(os.path.dirname(__file__), "outputs/example_sim_fk_grad.usd"), scaling=50.0
)
def run(self, render=True):
render_time = 0.0
train_iters = 1024
train_rate = 0.01
target = torch.from_numpy(np.array((2.0, 1.0, 0.0))).to(self.torch_device)
# optimization variable
joint_q = torch.zeros(len(self.model.joint_q), requires_grad=True, device=self.torch_device)
joint_qd = torch.zeros(len(self.model.joint_qd), requires_grad=True, device=self.torch_device)
for i in range(train_iters):
(body_q, body_qd) = ForwardKinematics.apply(joint_q, joint_qd, self.model)
l = torch.norm(body_q[self.model.body_count - 1][0:3] - target) ** 2.0
l.backward()
print(l)
print(joint_q.grad)
with torch.no_grad():
joint_q -= joint_q.grad * train_rate
joint_q.grad.zero_()
# render
s = self.model.state()
s.body_q = wp.from_torch(body_q, dtype=wp.transform)
s.body_qd = wp.from_torch(body_qd, dtype=wp.spatial_vector)
self.renderer.begin_frame(render_time)
self.renderer.render(s)
self.renderer.render_sphere(name="target", pos=target, rot=wp.quat_identity(), radius=0.1)
self.renderer.end_frame()
render_time += 1.0 / 60.0
self.renderer.save()
robot = Robot(render=True, device="cuda", num_envs=1)
robot.run()
| warp-main | examples/example_sim_fk_grad_torch.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Trajectory Optimization
#
# Shows how to optimize torque trajectories for a simple planar environment
# using Warp's provided Adam optimizer.
#
###########################################################################
import os
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
from warp.optim import Adam
import matplotlib.pyplot as plt
wp.init()
@wp.kernel
def loss_l2(states: wp.array(dtype=wp.float32), targets: wp.array(dtype=wp.float32), loss: wp.array(dtype=wp.float32)):
i = wp.tid()
diff = states[i] - targets[i]
l = diff * diff
wp.atomic_add(loss, 0, l)
@wp.kernel
def apply_torque(torques: wp.array(dtype=wp.float32), start_index: int, body_f: wp.array(dtype=wp.spatial_vector)):
fx = torques[start_index + 0]
fz = torques[start_index + 1]
body_f[0] = wp.spatial_vector(0.0, 0.0, 0.0, fx, 0.0, fz)
@wp.kernel
def save_state(body_q: wp.array(dtype=wp.transform), start_index: int, states: wp.array(dtype=wp.float32)):
pos = wp.transform_get_translation(body_q[0])
states[start_index + 0] = pos[0]
states[start_index + 1] = pos[2]
class Environment:
frame_dt = 1.0 / 60.0
episode_frames = 100
sim_substeps = 1
sim_dt = frame_dt / sim_substeps
sim_time = 0.0
render_time = 0.0
def __init__(self, device="cpu"):
builder = wp.sim.ModelBuilder()
self.device = device
# add planar joints
builder = wp.sim.ModelBuilder(gravity=0.0)
builder.add_articulation()
b = builder.add_body(origin=wp.transform())
s = builder.add_shape_box(pos=(0.0, 0.0, 0.0), hx=0.5, hy=0.5, hz=0.5, density=100.0, body=b)
# compute reference trajectory
rad = np.linspace(0.0, np.pi * 2, self.episode_frames)
self.ref_traj = np.stack([np.cos(rad), np.sin(rad)], axis=1)
# set initial joint configuration to first reference state
builder.body_q[0] = wp.transform(p=[self.ref_traj[0][0], 0.0, self.ref_traj[0][1]])
self.ref_traj = wp.array(self.ref_traj.flatten(), dtype=wp.float32, device=self.device, requires_grad=True)
# finalize model
self.model = builder.finalize(device, requires_grad=True)
self.builder = builder
self.model.ground = False
self.dof_q = self.model.joint_coord_count
self.dof_qd = self.model.joint_dof_count
self.num_bodies = self.model.body_count
self.action_dim = 2
self.state_dim = 2
assert len(self.ref_traj) == self.episode_frames * self.state_dim
self.integrator = wp.sim.SemiImplicitIntegrator()
def simulate(self, state: wp.sim.State, action: wp.array, action_index: int, requires_grad=False) -> wp.sim.State:
"""
Simulate the system for the given states.
"""
for _ in range(self.sim_substeps):
if requires_grad:
next_state = self.model.state(requires_grad=True)
else:
next_state = state
next_state.clear_forces()
wp.sim.collide(self.model, state)
# apply generalized torques to rigid body here, instead of planar joints
wp.launch(apply_torque, 1, inputs=[action, action_index], outputs=[state.body_f], device=action.device)
state = self.integrator.simulate(self.model, state, next_state, self.sim_dt, requires_grad=requires_grad)
return state
def _render(self, state: wp.sim.State):
self.renderer.begin_frame(self.render_time)
self.renderer.render(state)
self.renderer.end_frame()
self.render_time += self.frame_dt
self.renderer.save()
def forward(self, actions: wp.array, requires_grad=False, loss=None, render=False):
"""
Advances the system dynamics given the rigid-body state in maximal coordinates and generalized joint torques [body_q, body_qd, tau].
Simulates for the set number of substeps and returns the next state in maximal and (optional) generalized coordinates [body_q_next, body_qd_next, joint_q_next, joint_qd_next].
"""
actions.requires_grad = requires_grad
state = self.model.state(requires_grad=requires_grad)
if render:
# set up Usd renderer
self.renderer = wp.sim.render.SimRenderer(
self.model, os.path.join(os.path.dirname(__file__), "outputs/example_sim_trajopt.usd"), scaling=100.0
)
self.render_time = 0.0
self._render(state)
states = wp.zeros(
self.episode_frames * self.state_dim, dtype=wp.float32, device=self.device, requires_grad=requires_grad
)
for i in range(self.episode_frames):
# simulate
next_state = self.simulate(state, actions, action_index=i * self.action_dim, requires_grad=requires_grad)
# save state
wp.launch(
save_state, dim=1, inputs=[next_state.body_q, i * self.state_dim], outputs=[states], device=self.device
)
# update state
state = next_state
if render:
self._render(state)
# compute loss
if loss is None:
loss = wp.zeros(1, dtype=wp.float32, device=self.device, requires_grad=requires_grad)
wp.launch(
loss_l2,
dim=self.state_dim * self.episode_frames,
inputs=[states, self.ref_traj],
outputs=[loss],
device=self.device,
)
return states
def optimize(self, num_iter=100, lr=0.01):
# initial guess
actions = wp.array(
np.zeros(self.episode_frames * self.action_dim) * 100.0,
dtype=wp.float32,
device=self.device,
requires_grad=True,
)
optimizer = Adam([actions], lr=lr)
loss = wp.zeros(1, dtype=wp.float32, device=self.device, requires_grad=True)
# optimize
for i in range(1, num_iter + 1):
loss.zero_()
tape = wp.Tape()
with tape:
self.forward(actions, requires_grad=True, loss=loss)
if i % 10 == 0:
print(f"iter {i}/{num_iter} loss: {loss.numpy()[0]:.3f}")
tape.backward(loss=loss)
# print("action grad", actions.grad.numpy())
assert not np.isnan(actions.grad.numpy()).any(), "NaN in gradient"
optimizer.step([actions.grad])
tape.zero()
return actions
np.set_printoptions(precision=4, linewidth=2000, suppress=True)
sim = Environment(device=wp.get_preferred_device())
best_actions = sim.optimize(num_iter=250, lr=1e2)
# render
opt_traj = sim.forward(best_actions, render=True)
np_states = opt_traj.numpy().reshape((-1, 2))
np_ref = sim.ref_traj.numpy().reshape((-1, 2))
plt.plot(np_ref[:, 0], np_ref[:, 1], label="reference")
plt.plot(np_states[:, 0], np_states[:, 1], label="optimized")
plt.grid()
plt.legend()
plt.axis("equal")
plt.show()
| warp-main | examples/example_sim_trajopt.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
import os
example_dir = os.path.dirname(os.path.realpath(__file__))
# set default cache directory before wp.init()
wp.config.kernel_cache_dir = os.path.join(example_dir, "tmp", "warpcache1")
wp.init()
print("+++ Current cache directory: ", wp.config.kernel_cache_dir)
# change cache directory after wp.init()
wp.build.init_kernel_cache(os.path.join(example_dir, "tmp", "warpcache2"))
print("+++ Current cache directory: ", wp.config.kernel_cache_dir)
# clear kernel cache (forces fresh kernel builds every time)
wp.build.clear_kernel_cache()
@wp.kernel
def basic(x: wp.array(dtype=float)):
tid = wp.tid()
x[tid] = float(tid)
device = "cpu"
n = 10
x = wp.zeros(n, dtype=float, device=device)
wp.launch(kernel=basic, dim=n, inputs=[x], device=device)
print(x.numpy())
| warp-main | examples/example_cache_management.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Fluid
#
# Shows how to implement a simple 2D Stable Fluids solver using
# multidimensional arrays and launches.
#
###########################################################################
import math
import warp as wp
import warp.render
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as anim
wp.init()
grid_width = wp.constant(256)
grid_height = wp.constant(128)
@wp.func
def lookup_float(f: wp.array2d(dtype=float), x: int, y: int):
x = wp.clamp(x, 0, grid_width - 1)
y = wp.clamp(y, 0, grid_height - 1)
return f[x, y]
@wp.func
def sample_float(f: wp.array2d(dtype=float), x: float, y: float):
lx = int(wp.floor(x))
ly = int(wp.floor(y))
tx = x - float(lx)
ty = y - float(ly)
s0 = wp.lerp(lookup_float(f, lx, ly), lookup_float(f, lx + 1, ly), tx)
s1 = wp.lerp(lookup_float(f, lx, ly + 1), lookup_float(f, lx + 1, ly + 1), tx)
s = wp.lerp(s0, s1, ty)
return s
@wp.func
def lookup_vel(f: wp.array2d(dtype=wp.vec2), x: int, y: int):
if x < 0 or x >= grid_width:
return wp.vec2()
if y < 0 or y >= grid_height:
return wp.vec2()
return f[x, y]
@wp.func
def sample_vel(f: wp.array2d(dtype=wp.vec2), x: float, y: float):
lx = int(wp.floor(x))
ly = int(wp.floor(y))
tx = x - float(lx)
ty = y - float(ly)
s0 = wp.lerp(lookup_vel(f, lx, ly), lookup_vel(f, lx + 1, ly), tx)
s1 = wp.lerp(lookup_vel(f, lx, ly + 1), lookup_vel(f, lx + 1, ly + 1), tx)
s = wp.lerp(s0, s1, ty)
return s
@wp.kernel
def advect(
u0: wp.array2d(dtype=wp.vec2),
u1: wp.array2d(dtype=wp.vec2),
rho0: wp.array2d(dtype=float),
rho1: wp.array2d(dtype=float),
dt: float,
):
i, j = wp.tid()
u = u0[i, j]
# trace backward
p = wp.vec2(float(i), float(j))
p = p - u * dt
# advect
u1[i, j] = sample_vel(u0, p[0], p[1])
rho1[i, j] = sample_float(rho0, p[0], p[1])
@wp.kernel
def divergence(u: wp.array2d(dtype=wp.vec2), div: wp.array2d(dtype=float)):
i, j = wp.tid()
if i == grid_width - 1:
return
if j == grid_height - 1:
return
dx = (u[i + 1, j][0] - u[i, j][0]) * 0.5
dy = (u[i, j + 1][1] - u[i, j][1]) * 0.5
div[i, j] = dx + dy
@wp.kernel
def pressure_solve(p0: wp.array2d(dtype=float), p1: wp.array2d(dtype=float), div: wp.array2d(dtype=float)):
i, j = wp.tid()
s1 = lookup_float(p0, i - 1, j)
s2 = lookup_float(p0, i + 1, j)
s3 = lookup_float(p0, i, j - 1)
s4 = lookup_float(p0, i, j + 1)
# Jacobi update
err = s1 + s2 + s3 + s4 - div[i, j]
p1[i, j] = err * 0.25
@wp.kernel
def pressure_apply(p: wp.array2d(dtype=float), u: wp.array2d(dtype=wp.vec2)):
i, j = wp.tid()
if i == 0 or i == grid_width - 1:
return
if j == 0 or j == grid_height - 1:
return
# pressure gradient
f_p = wp.vec2(p[i + 1, j] - p[i - 1, j], p[i, j + 1] - p[i, j - 1]) * 0.5
u[i, j] = u[i, j] - f_p
@wp.kernel
def integrate(u: wp.array2d(dtype=wp.vec2), rho: wp.array2d(dtype=float), dt: float):
i, j = wp.tid()
# gravity
f_g = wp.vec2(-90.8, 0.0) * rho[i, j]
# integrate
u[i, j] = u[i, j] + dt * f_g
# fade
rho[i, j] = rho[i, j] * (1.0 - 0.1 * dt)
@wp.kernel
def init(rho: wp.array2d(dtype=float), u: wp.array2d(dtype=wp.vec2), radius: int, dir: wp.vec2):
i, j = wp.tid()
d = wp.length(wp.vec2(float(i - grid_width / 2), float(j - grid_height / 2)))
if d < radius:
rho[i, j] = 1.0
u[i, j] = dir
class Example:
def __init__(self):
self.sim_fps = 60.0
self.sim_substeps = 2
self.iterations = 100
self.sim_dt = (1.0 / self.sim_fps) / self.sim_substeps
self.sim_time = 0.0
self.device = wp.get_device()
shape = (grid_width, grid_height)
self.u0 = wp.zeros(shape, dtype=wp.vec2)
self.u1 = wp.zeros(shape, dtype=wp.vec2)
self.rho0 = wp.zeros(shape, dtype=float)
self.rho1 = wp.zeros(shape, dtype=float)
self.p0 = wp.zeros(shape, dtype=float)
self.p1 = wp.zeros(shape, dtype=float)
self.div = wp.zeros(shape, dtype=float)
# capture pressure solve as a CUDA graph
if self.device.is_cuda:
wp.capture_begin()
self.solve()
self.graph = wp.capture_end()
def update(self):
pass
def solve(self):
for i in range(self.iterations):
wp.launch(pressure_solve, dim=self.p0.shape, inputs=[self.p0, self.p1, self.div])
# swap pressure fields
(self.p0, self.p1) = (self.p1, self.p0)
def render(self, img, i):
with wp.ScopedTimer("update"):
for i in range(self.sim_substeps):
shape = (grid_width, grid_height)
dt = self.sim_dt
speed = 400.0
angle = math.sin(self.sim_time * 4.0) * 1.5
vel = wp.vec2(math.cos(angle) * speed, math.sin(angle) * speed)
# update emitters
wp.launch(init, dim=shape, inputs=[self.rho0, self.u0, 5, vel])
# force integrate
wp.launch(integrate, dim=shape, inputs=[self.u0, self.rho0, dt])
wp.launch(divergence, dim=shape, inputs=[self.u0, self.div])
# pressure solve
self.p0.zero_()
self.p1.zero_()
if self.device.is_cuda:
wp.capture_launch(self.graph)
else:
self.solve()
# velocity update
wp.launch(pressure_apply, dim=shape, inputs=[self.p0, self.u0])
# semi-Lagrangian advection
wp.launch(advect, dim=shape, inputs=[self.u0, self.u1, self.rho0, self.rho1, dt])
# swap buffers
(self.u0, self.u1) = (self.u1, self.u0)
(self.rho0, self.rho1) = (self.rho1, self.rho0)
self.sim_time += dt
# plot
with wp.ScopedTimer("render"):
img.set_array(self.rho0.numpy())
return (img,)
if __name__ == "__main__":
example = Example()
fig = plt.figure()
img = plt.imshow(example.rho0.numpy(), origin="lower", animated=True, interpolation="antialiased")
img.set_norm(matplotlib.colors.Normalize(0.0, 1.0))
seq = anim.FuncAnimation(fig, lambda i: example.render(img, i), frames=100000, blit=True, interval=8, repeat=False)
plt.show()
| warp-main | examples/example_fluid.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Rigid Force
#
# Shows how to apply an external force (torque) to a rigid body causing
# it to roll.
#
###########################################################################
import os
import warp as wp
import warp.sim
import warp.sim.render
wp.init()
class Example:
def __init__(self, stage):
self.sim_fps = 60.0
self.sim_substeps = 5
self.sim_duration = 5.0
self.sim_frames = int(self.sim_duration * self.sim_fps)
self.sim_dt = (1.0 / self.sim_fps) / self.sim_substeps
self.sim_time = 0.0
builder = wp.sim.ModelBuilder()
b = builder.add_body(origin=wp.transform((0.0, 2.0, 0.0), wp.quat_identity()))
builder.add_shape_box(body=b, hx=0.5, hy=0.5, hz=0.5, density=1000.0)
self.model = builder.finalize()
self.model.ground = True
self.integrator = wp.sim.XPBDIntegrator()
self.state_0 = self.model.state()
self.state_1 = self.model.state()
self.renderer = wp.sim.render.SimRenderer(self.model, stage, scaling=20.0)
def update(self):
with wp.ScopedTimer("simulate"):
for s in range(self.sim_substeps):
wp.sim.collide(self.model, self.state_0)
self.state_0.clear_forces()
self.state_1.clear_forces()
self.state_0.body_f.assign(
[
[0.0, 0.0, -3000.0, 0.0, 0.0, 0.0],
]
)
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
self.sim_time += self.sim_dt
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def render(self, is_live=False):
with wp.ScopedTimer("render"):
time = 0.0 if is_live else self.sim_time
self.renderer.begin_frame(time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
stage_path = os.path.join(os.path.dirname(__file__), "outputs/example_sim_rigid_force.usd")
example = Example(stage_path)
for i in range(example.sim_frames):
example.update()
example.render()
example.renderer.save()
| warp-main | examples/example_sim_rigid_force.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Wave
#
# Shows how to implement a simple 2D wave-equation solver with collision
# against a moving sphere.
#
###########################################################################
import os
import math
import warp as wp
import warp.render
wp.init()
@wp.func
def sample(f: wp.array(dtype=float), x: int, y: int, width: int, height: int):
# clamp texture coords
x = wp.clamp(x, 0, width - 1)
y = wp.clamp(y, 0, height - 1)
s = f[y * width + x]
return s
@wp.func
def laplacian(f: wp.array(dtype=float), x: int, y: int, width: int, height: int):
ddx = sample(f, x + 1, y, width, height) - 2.0 * sample(f, x, y, width, height) + sample(f, x - 1, y, width, height)
ddy = sample(f, x, y + 1, width, height) - 2.0 * sample(f, x, y, width, height) + sample(f, x, y - 1, width, height)
return ddx + ddy
@wp.kernel
def wave_displace(
hcurrent: wp.array(dtype=float),
hprevious: wp.array(dtype=float),
width: int,
height: int,
center_x: float,
center_y: float,
r: float,
mag: float,
t: float,
):
tid = wp.tid()
x = tid % width
y = tid // width
dx = float(x) - center_x
dy = float(y) - center_y
dist_sq = float(dx * dx + dy * dy)
if dist_sq < r * r:
h = mag * wp.sin(t)
hcurrent[tid] = h
hprevious[tid] = h
@wp.kernel
def wave_solve(
hprevious: wp.array(dtype=float),
hcurrent: wp.array(dtype=float),
width: int,
height: int,
inv_cell: float,
k_speed: float,
k_damp: float,
dt: float,
):
tid = wp.tid()
x = tid % width
y = tid // width
l = laplacian(hcurrent, x, y, width, height) * inv_cell * inv_cell
# integrate
h1 = hcurrent[tid]
h0 = hprevious[tid]
h = 2.0 * h1 - h0 + dt * dt * (k_speed * l - k_damp * (h1 - h0))
# buffers get swapped each iteration
hprevious[tid] = h
# simple kernel to apply height deltas to a vertex array
@wp.kernel
def grid_update(heights: wp.array(dtype=float), vertices: wp.array(dtype=wp.vec3)):
tid = wp.tid()
h = heights[tid]
v = vertices[tid]
v_new = wp.vec3(v[0], h, v[2])
vertices[tid] = v_new
class Example:
def __init__(self, stage):
self.sim_width = 128
self.sim_height = 128
self.sim_fps = 60.0
self.sim_substeps = 16
self.sim_duration = 5.0
self.sim_frames = int(self.sim_duration * self.sim_fps)
self.sim_dt = (1.0 / self.sim_fps) / self.sim_substeps
self.sim_time = 0.0
# wave constants
self.k_speed = 1.0
self.k_damp = 0.0
# grid constants
self.grid_size = 0.1
self.grid_displace = 0.5
self.renderer = wp.render.UsdRenderer(stage)
vertices = []
self.indices = []
def grid_index(x, y, stride):
return y * stride + x
for z in range(self.sim_height):
for x in range(self.sim_width):
pos = (
float(x) * self.grid_size,
0.0,
float(z) * self.grid_size,
) # - Gf.Vec3f(float(self.sim_width)/2*self.grid_size, 0.0, float(self.sim_height)/2*self.grid_size)
# directly modifies verts_host memory since this is a numpy alias of the same buffer
vertices.append(pos)
if x > 0 and z > 0:
self.indices.append(grid_index(x - 1, z - 1, self.sim_width))
self.indices.append(grid_index(x, z, self.sim_width))
self.indices.append(grid_index(x, z - 1, self.sim_width))
self.indices.append(grid_index(x - 1, z - 1, self.sim_width))
self.indices.append(grid_index(x - 1, z, self.sim_width))
self.indices.append(grid_index(x, z, self.sim_width))
# simulation grids
self.sim_grid0 = wp.zeros(self.sim_width * self.sim_height, dtype=float)
self.sim_grid1 = wp.zeros(self.sim_width * self.sim_height, dtype=float)
self.sim_verts = wp.array(vertices, dtype=wp.vec3)
# create surface displacment around a point
self.cx = self.sim_width / 2 + math.sin(self.sim_time) * self.sim_width / 3
self.cy = self.sim_height / 2 + math.cos(self.sim_time) * self.sim_height / 3
def update(self):
with wp.ScopedTimer("simulate", active=True):
for s in range(self.sim_substeps):
# create surface displacment around a point
self.cx = self.sim_width / 2 + math.sin(self.sim_time) * self.sim_width / 3
self.cy = self.sim_height / 2 + math.cos(self.sim_time) * self.sim_height / 3
wp.launch(
kernel=wave_displace,
dim=self.sim_width * self.sim_height,
inputs=[
self.sim_grid0,
self.sim_grid1,
self.sim_width,
self.sim_height,
self.cx,
self.cy,
10.0,
self.grid_displace,
-math.pi * 0.5,
],
)
# integrate wave equation
wp.launch(
kernel=wave_solve,
dim=self.sim_width * self.sim_height,
inputs=[
self.sim_grid0,
self.sim_grid1,
self.sim_width,
self.sim_height,
1.0 / self.grid_size,
self.k_speed,
self.k_damp,
self.sim_dt,
],
)
# swap grids
(self.sim_grid0, self.sim_grid1) = (self.sim_grid1, self.sim_grid0)
self.sim_time += self.sim_dt
with wp.ScopedTimer("mesh", active=False):
# update grid vertices from heights
wp.launch(kernel=grid_update, dim=self.sim_width * self.sim_height, inputs=[self.sim_grid0, self.sim_verts])
def render(self, is_live=False):
with wp.ScopedTimer("render", active=True):
time = 0.0 if is_live else self.sim_time
vertices = self.sim_verts.numpy()
self.renderer.begin_frame(time)
self.renderer.render_mesh("surface", vertices, self.indices)
self.renderer.render_sphere(
"sphere",
(self.cx * self.grid_size, 0.0, self.cy * self.grid_size),
(0.0, 0.0, 0.0, 1.0),
10.0 * self.grid_size,
)
self.renderer.end_frame()
if __name__ == "__main__":
stage_path = os.path.join(os.path.dirname(__file__), "outputs/example_wave.usd")
example = Example(stage_path)
for i in range(example.sim_frames):
example.update()
example.render()
example.renderer.save()
| warp-main | examples/example_wave.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example NanoVDB
#
# Shows how to implement a particle simulation with collision against
# a NanoVDB signed-distance field. In this example the NanoVDB field
# is created offline in Houdini. The particle kernel uses the Warp
# wp.volume_sample_f() method to compute the SDF and normal at a point.
#
###########################################################################
import os
import math
import numpy as np
import warp as wp
import warp.render
wp.init()
@wp.func
def volume_grad(volume: wp.uint64, p: wp.vec3):
eps = 1.0
q = wp.volume_world_to_index(volume, p)
# compute gradient of the SDF using finite differences
dx = wp.volume_sample_f(volume, q + wp.vec3(eps, 0.0, 0.0), wp.Volume.LINEAR) - wp.volume_sample_f(
volume, q - wp.vec3(eps, 0.0, 0.0), wp.Volume.LINEAR
)
dy = wp.volume_sample_f(volume, q + wp.vec3(0.0, eps, 0.0), wp.Volume.LINEAR) - wp.volume_sample_f(
volume, q - wp.vec3(0.0, eps, 0.0), wp.Volume.LINEAR
)
dz = wp.volume_sample_f(volume, q + wp.vec3(0.0, 0.0, eps), wp.Volume.LINEAR) - wp.volume_sample_f(
volume, q - wp.vec3(0.0, 0.0, eps), wp.Volume.LINEAR
)
return wp.normalize(wp.vec3(dx, dy, dz))
@wp.kernel
def simulate(
positions: wp.array(dtype=wp.vec3),
velocities: wp.array(dtype=wp.vec3),
volume: wp.uint64,
restitution: float,
margin: float,
dt: float,
):
tid = wp.tid()
x = positions[tid]
v = velocities[tid]
v = v + wp.vec3(0.0, 0.0, -980.0) * dt - v * 0.1 * dt
xpred = x + v * dt
xpred_local = wp.volume_world_to_index(volume, xpred)
#d = wp.volume_sample_f(volume, xpred_local, wp.Volume.LINEAR)
n = wp.vec3()
d = wp.volume_sample_grad_f(volume, xpred_local, wp.Volume.LINEAR, n)
if d < margin:
#n = volume_grad(volume, xpred)
n = wp.normalize(n)
err = d - margin
# mesh collision
xpred = xpred - n * err
# ground collision
if xpred[2] < 0.0:
xpred = wp.vec3(xpred[0], xpred[1], 0.0)
# pbd update
v = (xpred - x) * (1.0 / dt)
x = xpred
positions[tid] = x
velocities[tid] = v
class Example:
def __init__(self, stage):
self.num_particles = 10000
self.sim_steps = 1000
self.sim_dt = 1.0 / 60.0
self.sim_substeps = 3
self.sim_time = 0.0
self.sim_timers = {}
self.sim_render = True
self.sim_restitution = 0.0
self.sim_margin = 15.0
self.renderer = wp.render.UsdRenderer(stage, up_axis="z")
self.renderer.render_ground(size=10000.0)
init_pos = 1000.0 * (np.random.rand(self.num_particles, 3) * 2.0 - 1.0) + np.array((0.0, 0.0, 3000.0))
init_vel = np.random.rand(self.num_particles, 3)
self.positions = wp.from_numpy(init_pos.astype(np.float32), dtype=wp.vec3)
self.velocities = wp.from_numpy(init_vel.astype(np.float32), dtype=wp.vec3)
# load collision volume
file = open(os.path.join(os.path.dirname(__file__), "assets/rocks.nvdb"), "rb")
# create Volume object
self.volume = wp.Volume.load_from_nvdb(file)
def update(self):
with wp.ScopedTimer("simulate", detailed=False, dict=self.sim_timers):
for s in range(self.sim_substeps):
wp.launch(
kernel=simulate,
dim=self.num_particles,
inputs=[
self.positions,
self.velocities,
self.volume.id,
self.sim_restitution,
self.sim_margin,
self.sim_dt / float(self.sim_substeps),
],
)
wp.synchronize_device()
def render(self, is_live=False):
with wp.ScopedTimer("render", detailed=False):
time = 0.0 if is_live else self.sim_time
self.renderer.begin_frame(time)
self.renderer.render_ref(
name="collision",
path=os.path.join(os.path.dirname(__file__), "assets/rocks.usd"),
pos=(0.0, 0.0, 0.0),
rot=wp.quat_from_axis_angle((1.0, 0.0, 0.0), math.pi),
scale=(1.0, 1.0, 1.0),
)
self.renderer.render_points(name="points", points=self.positions.numpy(), radius=self.sim_margin)
self.renderer.end_frame()
self.sim_time += self.sim_dt
if __name__ == "__main__":
stage_path = os.path.join(os.path.dirname(__file__), "outputs/example_nvdb.usd")
example = Example(stage_path)
for i in range(example.sim_steps):
example.update()
example.render()
example.renderer.save()
| warp-main | examples/example_nvdb.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Jacobian
#
# Demonstrates how to compute the Jacobian of a multi-valued function.
# Here, we use the simulation of a cartpole to differentiate
# through the kinematics function. We instantiate multiple copies of the
# cartpole and compute the Jacobian of the state of each cartpole in parallel
# in order to perform inverse kinematics via Jacobian transpose.
#
###########################################################################
import os
import math
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
wp.init()
class Robot:
frame_dt = 1.0 / 60.0
render_time = 0.0
# step size to use for the IK updates
step_size = 0.1
def __init__(self, render=True, num_envs=1, device=None):
builder = wp.sim.ModelBuilder()
self.render = render
self.num_envs = num_envs
self.device = device
articulation_builder = wp.sim.ModelBuilder()
wp.sim.parse_urdf(
os.path.join(os.path.dirname(__file__), "assets/cartpole.urdf"),
articulation_builder,
xform=wp.transform_identity(),
floating=False,
density=0,
armature=0.1,
stiffness=0.0,
damping=0.0,
shape_ke=1.0e4,
shape_kd=1.0e2,
shape_kf=1.0e2,
shape_mu=1.0,
limit_ke=1.0e4,
limit_kd=1.0e1,
)
builder = wp.sim.ModelBuilder()
self.num_links = len(articulation_builder.joint_type)
# use the last link as the end-effector
self.ee_link_index = self.num_links - 1
self.ee_link_offset = wp.vec3(0.0, 0.0, 1.0)
self.dof = len(articulation_builder.joint_q)
self.target_origin = []
for i in range(num_envs):
builder.add_builder(
articulation_builder,
xform=wp.transform(
np.array((i * 2.0, 4.0, 0.0)), wp.quat_from_axis_angle((1.0, 0.0, 0.0), -math.pi * 0.5)
),
)
self.target_origin.append((i * 2.0, 4.0, 0.0))
# joint initial positions
builder.joint_q[-3:] = np.random.uniform(-0.5, 0.5, size=3)
self.target_origin = np.array(self.target_origin)
# finalize model
self.model = builder.finalize(device)
self.model.ground = True
self.model.joint_q.requires_grad = True
self.model.body_q.requires_grad = True
self.model.joint_attach_ke = 1600.0
self.model.joint_attach_kd = 20.0
self.integrator = wp.sim.SemiImplicitIntegrator()
# -----------------------
# set up Usd renderer
if self.render:
self.renderer = wp.sim.render.SimRenderer(
self.model, os.path.join(os.path.dirname(__file__), "outputs/example_jacobian_ik.usd")
)
self.ee_pos = wp.zeros(self.num_envs, dtype=wp.vec3, device=device, requires_grad=True)
@wp.kernel
def compute_endeffector_position(
body_q: wp.array(dtype=wp.transform),
num_links: int,
ee_link_index: int,
ee_link_offset: wp.vec3,
ee_pos: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
ee_pos[tid] = wp.transform_point(body_q[tid * num_links + ee_link_index], ee_link_offset)
def compute_ee_position(self):
# computes the end-effector position from the current joint angles
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state)
wp.launch(
self.compute_endeffector_position,
dim=self.num_envs,
inputs=[self.state.body_q, self.num_links, self.ee_link_index, self.ee_link_offset],
outputs=[self.ee_pos],
device=self.device,
)
return self.ee_pos
def compute_jacobian(self):
# our function has 3 outputs (EE position), so we need a 3xN jacobian per environment
jacobians = np.empty((self.num_envs, 3, self.dof), dtype=np.float32)
tape = wp.Tape()
with tape:
self.compute_ee_position()
for output_index in range(3):
# select which row of the Jacobian we want to compute
select_index = np.zeros(3)
select_index[output_index] = 1.0
e = wp.array(np.tile(select_index, self.num_envs), dtype=wp.vec3, device=self.device)
tape.backward(grads={self.ee_pos: e})
q_grad_i = tape.gradients[self.model.joint_q]
jacobians[:, output_index, :] = q_grad_i.numpy().reshape(self.num_envs, self.dof)
tape.zero()
return jacobians
def compute_fd_jacobian(self, eps=1e-4):
jacobians = np.zeros((self.num_envs, 3, self.dof), dtype=np.float32)
q0 = self.model.joint_q.numpy().copy()
for e in range(self.num_envs):
for i in range(self.dof):
q = q0.copy()
q[e * self.dof + i] += eps
self.model.joint_q.assign(q)
self.compute_ee_position()
f_plus = self.ee_pos.numpy()[e].copy()
q[e * self.dof + i] -= 2 * eps
self.model.joint_q.assign(q)
self.compute_ee_position()
f_minus = self.ee_pos.numpy()[e].copy()
jacobians[e, :, i] = (f_plus - f_minus) / (2 * eps)
return jacobians
def run(self, render=True):
profiler = {}
self.state = self.model.state(requires_grad=True)
if render:
print("autodiff:")
print(self.compute_jacobian())
print("finite diff:")
print(self.compute_fd_jacobian())
for _ in range(5):
# select new random target points
targets = self.target_origin.copy()
targets[:, 1:] += np.random.uniform(-0.5, 0.5, size=(self.num_envs, 2))
for iter in range(50):
with wp.ScopedTimer("jacobian", print=False, active=True, dict=profiler):
# compute jacobian
jacobians = self.compute_jacobian()
# jacobians = self.compute_fd_jacobian()
# compute error
ee_pos = self.compute_ee_position().numpy()
error = targets - ee_pos
error = error.reshape(self.num_envs, 3, 1)
# compute Jacobian transpose update
delta_q = np.matmul(jacobians.transpose(0, 2, 1), error)
self.model.joint_q = wp.array(
self.model.joint_q.numpy() + self.step_size * delta_q.flatten(),
dtype=wp.float32,
device=self.device,
requires_grad=True,
)
# render
if render:
self.render_time += self.frame_dt
self.renderer.begin_frame(self.render_time)
self.renderer.render(self.state)
self.renderer.render_points("targets", targets, radius=0.05)
self.renderer.render_points("ee_pos", ee_pos, radius=0.05)
self.renderer.end_frame()
self.renderer.save()
print("iter:", iter, "error:", error.mean())
avg_time = np.array(profiler["jacobian"]).mean()
avg_steps_second = 1000.0 * float(self.num_envs) / avg_time
print(f"envs: {self.num_envs} steps/second {avg_steps_second} avg_time {avg_time}")
return 1000.0 * float(self.num_envs) / avg_time
profile = False
if profile:
env_count = 2
env_times = []
env_size = []
for i in range(12):
robot = Robot(render=False, num_envs=env_count)
steps_per_second = robot.run(render=False)
env_size.append(env_count)
env_times.append(steps_per_second)
env_count *= 2
# dump times
for i in range(len(env_times)):
print(f"envs: {env_size[i]} steps/second: {env_times[i]}")
# plot
import matplotlib.pyplot as plt
plt.figure(1)
plt.plot(env_size, env_times)
plt.xscale("log")
plt.xlabel("Number of Envs")
plt.yscale("log")
plt.ylabel("Steps/Second")
plt.show()
else:
robot = Robot(render=True, num_envs=10)
robot.run()
| warp-main | examples/example_jacobian_ik.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# OpenGL renderer example
#
# Demonstrates how to set up tiled rendering and retrieves the pixels from
# OpenGLRenderer as a Warp array while keeping all memory on the GPU.
#
###########################################################################
import warp as wp
import warp.render
import numpy as np
wp.init()
# number of viewports to render in a single frame
num_tiles = 4
# whether to split tiles into subplots
split_up_tiles = True
# whether to apply custom tile arrangement
custom_tile_arrangement = False
# whether to display the pixels in a matplotlib figure
show_plot = True
renderer = wp.render.OpenGLRenderer(vsync=False)
instance_ids = []
if custom_tile_arrangement:
positions = []
sizes = []
else:
positions = None
sizes = None
if num_tiles > 1:
# set up instances to hide one of the capsules in each tile
for i in range(num_tiles):
instances = [j for j in np.arange(13) if j != i + 2]
instance_ids.append(instances)
if custom_tile_arrangement:
angle = np.pi * 2.0 / num_tiles * i
positions.append((int(np.cos(angle) * 150 + 250), int(np.sin(angle) * 150 + 250)))
sizes.append((150, 150))
renderer.setup_tiled_rendering(instance_ids, tile_positions=positions, tile_sizes=sizes)
renderer.render_ground()
if show_plot:
import matplotlib.pyplot as plt
if split_up_tiles:
pixels = wp.zeros((num_tiles, renderer.tile_height, renderer.tile_width, 3), dtype=wp.float32)
ncols = int(np.ceil(np.sqrt(num_tiles)))
nrows = int(np.ceil(num_tiles / float(ncols)))
img_plots = []
aspect_ratio = renderer.tile_height / renderer.tile_width
fig, axes = plt.subplots(
ncols=ncols,
nrows=nrows,
constrained_layout=True,
figsize=(ncols * 3.5, nrows * 3.5 * aspect_ratio),
squeeze=False,
sharex=True,
sharey=True,
num=1,
)
tile_temp = np.zeros((renderer.tile_height, renderer.tile_width, 3), dtype=np.float32)
for dim in range(ncols * nrows):
ax = axes[dim // ncols, dim % ncols]
if dim >= num_tiles:
ax.axis("off")
continue
img_plots.append(ax.imshow(tile_temp))
else:
fig = plt.figure(1)
pixels = wp.zeros((renderer.screen_height, renderer.screen_width, 3), dtype=wp.float32)
img_plot = plt.imshow(pixels.numpy())
plt.ion()
plt.show()
while renderer.is_running():
time = renderer.clock_time
renderer.begin_frame(time)
for i in range(10):
renderer.render_capsule(
f"capsule_{i}", [i - 5.0, np.sin(time + i * 0.2), -3.0], [0.0, 0.0, 0.0, 1.0], radius=0.5, half_height=0.8
)
renderer.render_cylinder(
"cylinder",
[3.2, 1.0, np.sin(time + 0.5)],
np.array(wp.quat_from_axis_angle((1.0, 0.0, 0.0), np.sin(time + 0.5))),
radius=0.5,
half_height=0.8,
)
renderer.render_cone(
"cone",
[-1.2, 1.0, 0.0],
np.array(wp.quat_from_axis_angle((0.707, 0.707, 0.0), time)),
radius=0.5,
half_height=0.8,
)
renderer.end_frame()
if show_plot and plt.fignum_exists(1):
if split_up_tiles:
pixel_shape = (num_tiles, renderer.tile_height, renderer.tile_width, 3)
else:
pixel_shape = (renderer.screen_height, renderer.screen_width, 3)
if pixel_shape != pixels.shape:
# make sure we resize the pixels array to the right dimensions if the user resizes the window
pixels = wp.zeros(pixel_shape, dtype=wp.float32)
renderer.get_pixels(pixels, split_up_tiles=split_up_tiles)
if split_up_tiles:
pixels_np = pixels.numpy()
for i, img_plot in enumerate(img_plots):
img_plot.set_data(pixels_np[i])
else:
img_plot.set_data(pixels.numpy())
fig.canvas.draw()
fig.canvas.flush_events()
renderer.clear()
| warp-main | examples/example_render_opengl.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Granular
#
# Shows how to set up a particle-based granular material model using the
# wp.sim.ModelBuilder().
#
###########################################################################
import os
import warp as wp
import warp.sim
import warp.sim.render
wp.init()
class Example:
def __init__(self, stage):
self.frame_dt = 1.0 / 60
self.frame_count = 400
self.sim_substeps = 64
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_steps = self.frame_count * self.sim_substeps
self.sim_time = 0.0
self.radius = 0.1
builder = wp.sim.ModelBuilder()
builder.default_particle_radius = self.radius
builder.add_particle_grid(
dim_x=16,
dim_y=32,
dim_z=16,
cell_x=self.radius * 2.0,
cell_y=self.radius * 2.0,
cell_z=self.radius * 2.0,
pos=(0.0, 1.0, 0.0),
rot=wp.quat_identity(),
vel=(5.0, 0.0, 0.0),
mass=0.1,
jitter=self.radius * 0.1,
)
self.model = builder.finalize()
self.model.particle_kf = 25.0
self.model.soft_contact_kd = 100.0
self.model.soft_contact_kf *= 2.0
self.state_0 = self.model.state()
self.state_1 = self.model.state()
self.integrator = wp.sim.SemiImplicitIntegrator()
self.renderer = wp.sim.render.SimRenderer(self.model, stage, scaling=20.0)
def update(self):
with wp.ScopedTimer("simulate", active=True):
self.model.particle_grid.build(self.state_0.particle_q, self.radius * 2.0)
for s in range(self.sim_substeps):
self.state_0.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def render(self, is_live=False):
with wp.ScopedTimer("render", active=True):
time = 0.0 if is_live else self.sim_time
self.renderer.begin_frame(time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
self.sim_time += self.frame_dt
if __name__ == "__main__":
stage_path = os.path.join(os.path.dirname(__file__), "outputs/example_sim_granular.usd")
example = Example(stage_path)
for i in range(example.frame_count):
example.update()
example.render()
example.renderer.save()
| warp-main | examples/example_sim_granular.py |
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Grad Cloth
#
# Shows how to use Warp to optimize the initial velocities of a piece of
# cloth such that it's center of mass hits a target after a specified time.
#
# This example uses the built-in wp.Tape() object to compute gradients of
# the distance to target (loss) w.r.t the initial velocity, followed by
# a simple gradient-descent optimization step.
#
###########################################################################
import os
import math
import warp as wp
import warp.sim
import warp.sim.render
wp.init()
class Cloth:
# seconds
sim_duration = 2.0
# control frequency
frame_dt = 1.0 / 60.0
frame_steps = int(sim_duration / frame_dt)
# sim frequency
sim_substeps = 16
sim_steps = frame_steps * sim_substeps
sim_dt = frame_dt / sim_substeps
sim_time = 0.0
render_time = 0.0
train_iters = 64
train_rate = 5.0
def __init__(self, render=True, profile=False, adapter=None):
builder = wp.sim.ModelBuilder()
builder.default_particle_radius = 0.01
dim_x = 16
dim_y = 16
builder.add_cloth_grid(
pos=(0.0, 0.0, 0.0),
vel=(0.1, 0.1, 0.0),
rot=wp.quat_from_axis_angle((1.0, 0.0, 0.0), -math.pi * 0.25),
dim_x=dim_x,
dim_y=dim_y,
cell_x=1.0 / dim_x,
cell_y=1.0 / dim_y,
mass=1.0,
tri_ke=10000.0,
tri_ka=10000.0,
tri_kd=100.0,
tri_lift=10.0,
tri_drag=5.0,
)
self.device = wp.get_device(adapter)
self.profile = profile
self.model = builder.finalize(self.device)
self.model.ground = False
self.integrator = wp.sim.SemiImplicitIntegrator()
self.target = (8.0, 0.0, 0.0)
self.com = wp.zeros(1, dtype=wp.vec3, device=self.device, requires_grad=True)
self.loss = wp.zeros(1, dtype=wp.float32, device=self.device, requires_grad=True)
# allocate sim states for trajectory
self.states = []
for i in range(self.sim_steps + 1):
self.states.append(self.model.state(requires_grad=True))
if self.render:
self.stage = wp.sim.render.SimRendererOpenGL(
self.model, os.path.join(os.path.dirname(__file__), "outputs/example_sim_grad_cloth.usd"), scaling=4.0
)
@wp.kernel
def com_kernel(positions: wp.array(dtype=wp.vec3), n: int, com: wp.array(dtype=wp.vec3)):
tid = wp.tid()
# compute center of mass
wp.atomic_add(com, 0, positions[tid] / float(n))
@wp.kernel
def loss_kernel(com: wp.array(dtype=wp.vec3), target: wp.vec3, loss: wp.array(dtype=float)):
# sq. distance to target
delta = com[0] - target
loss[0] = wp.dot(delta, delta)
@wp.kernel
def step_kernel(x: wp.array(dtype=wp.vec3), grad: wp.array(dtype=wp.vec3), alpha: float):
tid = wp.tid()
# gradient descent step
x[tid] = x[tid] - grad[tid] * alpha
def compute_loss(self):
# run control loop
for i in range(self.sim_steps):
self.states[i].clear_forces()
self.integrator.simulate(self.model, self.states[i], self.states[i + 1], self.sim_dt)
# compute loss on final state
self.com.zero_()
wp.launch(
self.com_kernel,
dim=self.model.particle_count,
inputs=[self.states[-1].particle_q, self.model.particle_count, self.com],
device=self.device,
)
wp.launch(self.loss_kernel, dim=1, inputs=[self.com, self.target, self.loss], device=self.device)
return self.loss
def render(self, iter):
# render every 4 iters
if iter % 4 > 0:
return
# draw trajectory
traj_verts = [self.states[0].particle_q.numpy().mean(axis=0)]
for i in range(0, self.sim_steps, self.sim_substeps):
traj_verts.append(self.states[i].particle_q.numpy().mean(axis=0))
self.stage.begin_frame(self.render_time)
self.stage.render(self.states[i])
self.stage.render_box(pos=self.target, rot=wp.quat_identity(), extents=(0.1, 0.1, 0.1), name="target")
self.stage.render_line_strip(
vertices=traj_verts,
color=wp.render.bourke_color_map(0.0, 269.0, self.loss.numpy()[0]),
radius=0.02,
name=f"traj_{iter}",
)
self.stage.end_frame()
self.render_time += self.frame_dt
def train(self, mode="gd"):
tape = wp.Tape()
for i in range(self.train_iters):
with wp.ScopedTimer("Forward", active=self.profile):
with tape:
self.compute_loss()
with wp.ScopedTimer("Backward", active=self.profile):
tape.backward(self.loss)
with wp.ScopedTimer("Render", active=self.profile):
self.render(i)
with wp.ScopedTimer("Step", active=self.profile):
x = self.states[0].particle_qd
x_grad = tape.gradients[self.states[0].particle_qd]
print(f"Iter: {i} Loss: {self.loss}")
wp.launch(self.step_kernel, dim=len(x), inputs=[x, x_grad, self.train_rate], device=self.device)
tape.reset()
def train_graph(self, mode="gd"):
wp.capture_begin()
tape = wp.Tape()
with tape:
self.compute_loss()
tape.backward(self.loss)
self.graph = wp.capture_end()
for i in range(self.train_iters):
with wp.ScopedTimer("Replay", active=self.profile):
wp.capture_launch(self.graph)
with wp.ScopedTimer("Render", active=self.profile):
self.render(i)
with wp.ScopedTimer("Step", active=self.profile):
x = self.states[0].particle_qd
print(f"Iter: {i} Loss: {self.loss}")
wp.launch(self.step_kernel, dim=len(x), inputs=[x, x.grad, self.train_rate], device=self.device)
tape.zero()
self.stage.save()
bounce = Cloth(profile=False, render=True)
bounce.train_graph("gd")
| warp-main | examples/example_sim_grad_cloth.py |
Subsets and Splits