file_path
stringlengths
21
224
content
stringlengths
0
80.8M
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.converters.rst
orbit.sim.converters ==================== .. automodule:: omni.isaac.orbit.sim.converters .. rubric:: Classes .. autosummary:: AssetConverterBase AssetConverterBaseCfg MeshConverter MeshConverterCfg UrdfConverter UrdfConverterCfg Asset Converter Base -------------------- .. autoclass:: AssetConverterBase :members: .. autoclass:: AssetConverterBaseCfg :members: :exclude-members: __init__ Mesh Converter -------------- .. autoclass:: MeshConverter :members: :inherited-members: :show-inheritance: .. autoclass:: MeshConverterCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__ URDF Converter -------------- .. autoclass:: UrdfConverter :members: :inherited-members: :show-inheritance: .. autoclass:: UrdfConverterCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.spawners.rst
orbit.sim.spawners ================== .. automodule:: omni.isaac.orbit.sim.spawners .. rubric:: Submodules .. autosummary:: shapes lights sensors from_files materials .. rubric:: Classes .. autosummary:: SpawnerCfg RigidObjectSpawnerCfg Spawners -------- .. autoclass:: SpawnerCfg :members: :exclude-members: __init__ .. autoclass:: RigidObjectSpawnerCfg :members: :show-inheritance: :exclude-members: __init__ Shapes ------ .. automodule:: omni.isaac.orbit.sim.spawners.shapes .. rubric:: Classes .. autosummary:: ShapeCfg CapsuleCfg ConeCfg CuboidCfg CylinderCfg SphereCfg .. autoclass:: ShapeCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_capsule .. autoclass:: CapsuleCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_cone .. autoclass:: ConeCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_cuboid .. autoclass:: CuboidCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_cylinder .. autoclass:: CylinderCfg :members: :show-inheritance: :exclude-members: __init__, func .. autofunction:: spawn_sphere .. autoclass:: SphereCfg :members: :show-inheritance: :exclude-members: __init__, func Lights ------ .. automodule:: omni.isaac.orbit.sim.spawners.lights .. rubric:: Classes .. autosummary:: LightCfg CylinderLightCfg DiskLightCfg DistantLightCfg DomeLightCfg SphereLightCfg .. autofunction:: spawn_light .. autoclass:: LightCfg :members: :exclude-members: __init__, func .. autoclass:: CylinderLightCfg :members: :exclude-members: __init__, func .. autoclass:: DiskLightCfg :members: :exclude-members: __init__, func .. autoclass:: DistantLightCfg :members: :exclude-members: __init__, func .. autoclass:: DomeLightCfg :members: :exclude-members: __init__, func .. autoclass:: SphereLightCfg :members: :exclude-members: __init__, func Sensors ------- .. automodule:: omni.isaac.orbit.sim.spawners.sensors .. rubric:: Classes .. autosummary:: PinholeCameraCfg FisheyeCameraCfg .. autofunction:: spawn_camera .. autoclass:: PinholeCameraCfg :members: :exclude-members: __init__, func .. autoclass:: FisheyeCameraCfg :members: :exclude-members: __init__, func From Files ---------- .. automodule:: omni.isaac.orbit.sim.spawners.from_files .. rubric:: Classes .. autosummary:: UrdfFileCfg UsdFileCfg GroundPlaneCfg .. autofunction:: spawn_from_urdf .. autoclass:: UrdfFileCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_from_usd .. autoclass:: UsdFileCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_ground_plane .. autoclass:: GroundPlaneCfg :members: :exclude-members: __init__, func Materials --------- .. automodule:: omni.isaac.orbit.sim.spawners.materials .. rubric:: Classes .. autosummary:: VisualMaterialCfg PreviewSurfaceCfg MdlFileCfg GlassMdlCfg PhysicsMaterialCfg RigidBodyMaterialCfg Visual Materials ~~~~~~~~~~~~~~~~ .. autoclass:: VisualMaterialCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_preview_surface .. autoclass:: PreviewSurfaceCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_from_mdl_file .. autoclass:: MdlFileCfg :members: :exclude-members: __init__, func .. autoclass:: GlassMdlCfg :members: :exclude-members: __init__, func Physical Materials ~~~~~~~~~~~~~~~~~~ .. autoclass:: PhysicsMaterialCfg :members: :exclude-members: __init__, func .. autofunction:: spawn_rigid_body_material .. autoclass:: RigidBodyMaterialCfg :members: :exclude-members: __init__, func
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.controllers.rst
orbit.controllers ================= .. automodule:: omni.isaac.orbit.controllers .. rubric:: Classes .. autosummary:: DifferentialIKController DifferentialIKControllerCfg Differential Inverse Kinematics ------------------------------- .. autoclass:: DifferentialIKController :members: :inherited-members: :show-inheritance: .. autoclass:: DifferentialIKControllerCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.envs.rst
orbit.envs ========== .. automodule:: omni.isaac.orbit.envs .. rubric:: Submodules .. autosummary:: mdp ui .. rubric:: Classes .. autosummary:: BaseEnv BaseEnvCfg ViewerCfg RLTaskEnv RLTaskEnvCfg Base Environment ---------------- .. autoclass:: BaseEnv :members: .. autoclass:: BaseEnvCfg :members: :exclude-members: __init__, class_type .. autoclass:: ViewerCfg :members: :exclude-members: __init__ RL Task Environment ------------------- .. autoclass:: RLTaskEnv :members: :inherited-members: :show-inheritance: .. autoclass:: RLTaskEnvCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.scene.rst
orbit.scene =========== .. automodule:: omni.isaac.orbit.scene .. rubric:: Classes .. autosummary:: InteractiveScene InteractiveSceneCfg interactive Scene ----------------- .. autoclass:: InteractiveScene :members: :undoc-members: :show-inheritance: .. autoclass:: InteractiveSceneCfg :members: :exclude-members: __init__
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sensors.patterns.rst
orbit.sensors.patterns ====================== .. automodule:: omni.isaac.orbit.sensors.patterns .. rubric:: Classes .. autosummary:: PatternBaseCfg GridPatternCfg PinholeCameraPatternCfg BpearlPatternCfg Pattern Base ------------ .. autoclass:: PatternBaseCfg :members: :inherited-members: :exclude-members: __init__ Grid Pattern ------------ .. autofunction:: omni.isaac.orbit.sensors.patterns.grid_pattern .. autoclass:: GridPatternCfg :members: :inherited-members: :exclude-members: __init__, func Pinhole Camera Pattern ---------------------- .. autofunction:: omni.isaac.orbit.sensors.patterns.pinhole_camera_pattern .. autoclass:: PinholeCameraPatternCfg :members: :inherited-members: :exclude-members: __init__, func RS-Bpearl Pattern ----------------- .. autofunction:: omni.isaac.orbit.sensors.patterns.bpearl_pattern .. autoclass:: BpearlPatternCfg :members: :inherited-members: :exclude-members: __init__, func
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.assets.rst
orbit.assets ============ .. automodule:: omni.isaac.orbit.assets .. rubric:: Classes .. autosummary:: AssetBase AssetBaseCfg RigidObject RigidObjectData RigidObjectCfg Articulation ArticulationData ArticulationCfg .. currentmodule:: omni.isaac.orbit.assets Asset Base ---------- .. autoclass:: AssetBase :members: .. autoclass:: AssetBaseCfg :members: :exclude-members: __init__, class_type Rigid Object ------------ .. autoclass:: RigidObject :members: :inherited-members: :show-inheritance: .. autoclass:: RigidObjectData :members: :inherited-members: :show-inheritance: :exclude-members: __init__ .. autoclass:: RigidObjectCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type Articulation ------------ .. autoclass:: Articulation :members: :inherited-members: :show-inheritance: .. autoclass:: ArticulationData :members: :inherited-members: :show-inheritance: :exclude-members: __init__ .. autoclass:: ArticulationCfg :members: :inherited-members: :show-inheritance: :exclude-members: __init__, class_type
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.envs.mdp.rst
orbit.envs.mdp ============== .. automodule:: omni.isaac.orbit.envs.mdp Observations ------------ .. automodule:: omni.isaac.orbit.envs.mdp.observations :members: Actions ------- .. automodule:: omni.isaac.orbit.envs.mdp.actions .. automodule:: omni.isaac.orbit.envs.mdp.actions.actions_cfg :members: :show-inheritance: :exclude-members: __init__, class_type Events ------ .. automodule:: omni.isaac.orbit.envs.mdp.events :members: Commands -------- .. automodule:: omni.isaac.orbit.envs.mdp.commands .. automodule:: omni.isaac.orbit.envs.mdp.commands.commands_cfg :members: :show-inheritance: :exclude-members: __init__, class_type Rewards ------- .. automodule:: omni.isaac.orbit.envs.mdp.rewards :members: Terminations ------------ .. automodule:: omni.isaac.orbit.envs.mdp.terminations :members: Curriculum ---------- .. automodule:: omni.isaac.orbit.envs.mdp.curriculums :members:
NVIDIA-Omniverse/orbit/docs/source/api/orbit/omni.isaac.orbit.sim.schemas.rst
orbit.sim.schemas ================= .. automodule:: omni.isaac.orbit.sim.schemas .. rubric:: Classes .. autosummary:: ArticulationRootPropertiesCfg RigidBodyPropertiesCfg CollisionPropertiesCfg MassPropertiesCfg JointDrivePropertiesCfg FixedTendonPropertiesCfg .. rubric:: Functions .. autosummary:: define_articulation_root_properties modify_articulation_root_properties define_rigid_body_properties modify_rigid_body_properties activate_contact_sensors define_collision_properties modify_collision_properties define_mass_properties modify_mass_properties modify_joint_drive_properties modify_fixed_tendon_properties Articulation Root ----------------- .. autoclass:: ArticulationRootPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_articulation_root_properties .. autofunction:: modify_articulation_root_properties Rigid Body ---------- .. autoclass:: RigidBodyPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_rigid_body_properties .. autofunction:: modify_rigid_body_properties .. autofunction:: activate_contact_sensors Collision --------- .. autoclass:: CollisionPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_collision_properties .. autofunction:: modify_collision_properties Mass ---- .. autoclass:: MassPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: define_mass_properties .. autofunction:: modify_mass_properties Joint Drive ----------- .. autoclass:: JointDrivePropertiesCfg :members: :exclude-members: __init__ .. autofunction:: modify_joint_drive_properties Fixed Tendon ------------ .. autoclass:: FixedTendonPropertiesCfg :members: :exclude-members: __init__ .. autofunction:: modify_fixed_tendon_properties
NVIDIA-Omniverse/orbit/docs/source/features/actuators.rst
.. _feature-actuators: Actuators ========= An articulated system comprises of actuated joints, also called the degrees of freedom (DOF). In a physical system, the actuation typically happens either through active components, such as electric or hydraulic motors, or passive components, such as springs. These components can introduce certain non-linear characteristics which includes delays or maximum producible velocity or torque. In simulation, the joints are either position, velocity, or torque-controlled. For position and velocity control, the physics engine internally implements a spring-damp (PD) controller which computes the torques applied on the actuated joints. In torque-control, the commands are set directly as the joint efforts. While this mimics an ideal behavior of the joint mechanism, it does not truly model how the drives work in the physical world. Thus, we provide a mechanism to inject external models to compute the joint commands that would represent the physical robot's behavior. Actuator models --------------- We name two different types of actuator models: 1. **implicit**: corresponds to the ideal simulation mechanism (provided by physics engine). 2. **explicit**: corresponds to external drive models (implemented by user). The explicit actuator model performs two steps: 1) it computes the desired joint torques for tracking the input commands, and 2) it clips the desired torques based on the motor capabilities. The clipped torques are the desired actuation efforts that are set into the simulation. As an example of an ideal explicit actuator model, we provide the :class:`omni.isaac.orbit.actuators.IdealPDActuator` class, which implements a PD controller with feed-forward effort, and simple clipping based on the configured maximum effort: .. math:: \tau_{j, computed} & = k_p * (q - q_{des}) + k_d * (\dot{q} - \dot{q}_{des}) + \tau_{ff} \\ \tau_{j, applied} & = clip(\tau_{computed}, -\tau_{j, max}, \tau_{j, max}) where, :math:`k_p` and :math:`k_d` are joint stiffness and damping gains, :math:`q` and :math:`\dot{q}` are the current joint positions and velocities, :math:`q_{des}`, :math:`\dot{q}_{des}` and :math:`\tau_{ff}` are the desired joint positions, velocities and torques commands. The parameters :math:`\gamma` and :math:`\tau_{motor, max}` are the gear box ratio and the maximum motor effort possible. Actuator groups --------------- The actuator models by themselves are computational blocks that take as inputs the desired joint commands and output the the joint commands to apply into the simulator. They do not contain any knowledge about the joints they are acting on themselves. These are handled by the :class:`omni.isaac.orbit.assets.Articulation` class, which wraps around the physics engine's articulation class. Actuator are collected as a set of actuated joints on an articulation that are using the same actuator model. For instance, the quadruped, ANYmal-C, uses series elastic actuator, ANYdrive 3.0, for all its joints. This grouping configures the actuator model for those joints, translates the input commands to the joint level commands, and returns the articulation action to set into the simulator. Having an arm with a different actuator model, such as a DC motor, would require configuring a different actuator group. The following figure shows the actuator groups for a legged mobile manipulator: .. image:: ../_static/actuator_groups.svg :width: 600 :align: center :alt: Actuator groups for a legged mobile manipulator .. seealso:: We provide implementations for various explicit actuator models. These are detailed in `omni.isaac.orbit.actuators <../api/orbit.actuators.html>`_ sub-package.
NVIDIA-Omniverse/orbit/docs/source/features/motion_generators.rst
Motion Generators ================= Robotic tasks are typically defined in task-space in terms of desired end-effector trajectory, while control actions are executed in the joint-space. This naturally leads to *joint-space* and *task-space* (operational-space) control methods. However, successful execution of interaction tasks using motion control often requires an accurate model of both the robot manipulator as well as its environment. While a sufficiently precise manipulator's model might be known, detailed description of environment is hard to obtain :cite:p:`siciliano2009force`. Planning errors caused by this mismatch can be overcome by introducing a *compliant* behavior during interaction. While compliance is achievable passively through robot's structure (such as elastic actuators, soft robot arms), we are more interested in controller designs that focus on active interaction control. These are broadly categorized into: 1. **impedance control:** indirect control method where motion deviations caused during interaction relates to contact force as a mass-spring-damper system with adjustable parameters (stiffness and damping). A specialized case of this is *stiffness* control where only the static relationship between position error and contact force is considered. 2. **hybrid force/motion control:** active control method which controls motion and force along unconstrained and constrained task directions respectively. Among the various schemes for hybrid motion control, the provided implementation is based on inverse dynamics control in the operational space :cite:p:`khatib1987osc`. .. note:: To provide an even broader set of motion generators, we welcome contributions from the community. If you are interested, please open an issue to start a discussion! Joint-space controllers ----------------------- Torque control ~~~~~~~~~~~~~~ Action dimensions: ``"n"`` (number of joints) In torque control mode, the input actions are directly set as feed-forward joint torque commands, i.e. at every time-step, .. math:: \tau = \tau_{des} Thus, this control mode is achievable by setting the command type for the actuator group, via the :class:`ActuatorControlCfg` class, to ``"t_abs"``. Velocity control ~~~~~~~~~~~~~~~~ Action dimensions: ``"n"`` (number of joints) In velocity control mode, a proportional control law is required to reduce the error between the current and desired joint velocities. Based on input actions, the joint torques commands are computed as: .. math:: \tau = k_d (\dot{q}_{des} - \dot{q}) where :math:`k_d` are the gains parsed from configuration. This control mode is achievable by setting the command type for the actuator group, via the :class:`ActuatorControlCfg` class, to ``"v_abs"`` or ``"v_rel"``. .. attention:: While performing velocity control, in many cases, gravity compensation is required to ensure better tracking of the command. In this case, we suggest disabling gravity for the links in the articulation in simulation. Position control with fixed impedance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"n"`` (number of joints) In position control mode, a proportional-damping (PD) control law is employed to track the desired joint positions and ensuring the articulation remains still at the desired location (i.e., desired joint velocities are zero). Based on the input actions, the joint torque commands are computed as: .. math:: \tau = k_p (q_{des} - q) - k_d \dot{q} where :math:`k_p` and :math:`k_d` are the gains parsed from configuration. In its simplest above form, the control mode is achievable by setting the command type for the actuator group, via the :class:`ActuatorControlCfg` class, to ``"p_abs"`` or ``"p_rel"``. However, a more complete formulation which considers the dynamics of the articulation would be: .. math:: \tau = M \left( k_p (q_{des} - q) - k_d \dot{q} \right) + g where :math:`M` is the joint-space inertia matrix of size :math:`n \times n`, and :math:`g` is the joint-space gravity vector. This implementation is available through the :class:`JointImpedanceController` class by setting the impedance mode to ``"fixed"``. The gains :math:`k_p` are parsed from the input configuration and :math:`k_d` are computed while considering the system as a decoupled point-mass oscillator, i.e., .. math:: k_d = 2 \sqrt{k_p} \times D where :math:`D` is the damping ratio of the system. Critical damping is achieved for :math:`D = 1`, overcritical damping for :math:`D > 1` and undercritical damping for :math:`D < 1`. Additionally, it is possible to disable the inertial or gravity compensation in the controller by setting the flags :attr:`inertial_compensation` and :attr:`gravity_compensation` in the configuration to :obj:`False`, respectively. Position control with variable stiffness ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"2n"`` (number of joints) In stiffness control, the same formulation as above is employed, however, the gains :math:`k_p` are part of the input commands. This implementation is available through the :class:`JointImpedanceController` class by setting the impedance mode to ``"variable_kp"``. Position control with variable impedance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"3n"`` (number of joints) In impedance control, the same formulation as above is employed, however, both :math:`k_p` and :math:`k_d` are part of the input commands. This implementation is available through the :class:`JointImpedanceController` class by setting the impedance mode to ``"variable"``. Task-space controllers ---------------------- Differential inverse kinematics (IK) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Action dimensions: ``"3"`` (relative/absolute position), ``"6"`` (relative pose), or ``"7"`` (absolute pose) Inverse kinematics converts the task-space tracking error to joint-space error. In its most typical implementation, the pose error in the task-sace, :math:`\Delta \chi_e = (\Delta p_e, \Delta \phi_e)`, is computed as the cartesian distance between the desired and current task-space positions, and the shortest distance in :math:`\mathbb{SO}(3)` between the desired and current task-space orientations. Using the geometric Jacobian :math:`J_{eO} \in \mathbb{R}^{6 \times n}`, that relates task-space velocity to joint-space velocities, we design the control law to obtain the desired joint positions as: .. math:: q_{des} = q + \eta J_{eO}^{-} \Delta \chi_e where :math:`\eta` is a scaling parameter and :math:`J_{eO}^{-}` is the pseudo-inverse of the Jacobian. It is possible to compute the pseudo-inverse of the Jacobian using different formulations: * Moore-Penrose pseduo-inverse: :math:`A^{-} = A^T(AA^T)^{-1}`. * Levenberg-Marquardt pseduo-inverse (damped least-squares): :math:`A^{-} = A^T (AA^T + \lambda \mathbb{I})^{-1}`. * Tanspose pseudo-inverse: :math:`A^{-} = A^T`. * Adaptive singular-vale decomposition (SVD) pseduo-inverse from :cite:t:`buss2004ik`. These implementations are available through the :class:`DifferentialInverseKinematics` class. Impedance controller ~~~~~~~~~~~~~~~~~~~~ It uses task-space pose error and Jacobian to compute join torques through mass-spring-damper system with a) fixed stiffness, b) variable stiffness (stiffness control), and c) variable stiffness and damping (impedance control). Operational-space controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Similar to task-space impedance control but uses the Equation of Motion (EoM) for computing the task-space force Closed-loop proportional force controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It uses a proportional term to track the desired wrench command with respect to current wrench at the end-effector. Hybrid force-motion controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It combines closed-loop force control and operational-space motion control to compute the desired wrench at the end-effector. It uses selection matrices that define the unconstrainted and constrained task directions. Reactive planners ----------------- Typical task-space controllers do not account for motion constraints such as joint limits, self-collision and environment collision. Instead they rely on high-level planners (such as RRT) to handle these non-Euclidean constraints and give joint/task-space way-points to the controller. However, these methods are often conservative and have undesirable deceleration when close to an object. More recently, different approaches combine the constraints directly into an optimization problem, thereby providing a holistic solution for motion generation and control. We currently support the following planners: - **RMPFlow (lula):** An acceleration-based policy that composes various Reimannian Motion Policies (RMPs) to solve a hierarchy of tasks :cite:p:`cheng2021rmpflow`. It is capable of performing dynamic collision avoidance while navigating the end-effector to a target. - **MPC (OCS2):** A receding horizon control policy based on sequential linear-quadratic (SLQ) programming. It formulates various constraints into a single optimization problem via soft-penalties and uses automatic differentiation to compute derivatives of the system dynamics, constraints and costs. Currently, we support the MPC formulation for end-effector trajectory tracking in fixed-arm and mobile manipulators. The formulation considers a kinematic system model with joint limits and self-collision avoidance :cite:p:`mittal2021articulated`. .. warning:: We wrap around the python bindings for these reactive planners to perform a batched computing of robot actions. However, their current implementations are CPU-based which may cause certain slowdown for learning.
NVIDIA-Omniverse/orbit/docs/source/features/environments.rst
Environments ============ The following lists comprises of all the RL tasks implementations that are available in Orbit. While we try to keep this list up-to-date, you can always get the latest list of environments by running the following command: .. code-block:: bash ./orbit.sh -p source/standalone/environments/list_envs.py We are actively working on adding more environments to the list. If you have any environments that you would like to add to Orbit, please feel free to open a pull request! Classic ------- Classic environments that are based on IsaacGymEnvs implementation of MuJoCo-style environments. .. table:: :widths: 33 37 30 +------------------+-----------------------------+-------------------------------------------------------------------------+ | World | Environment ID | Description | +==================+=============================+=========================================================================+ | |humanoid| | |humanoid-link| | Move towards a direction with the MuJoCo humanoid robot | +------------------+-----------------------------+-------------------------------------------------------------------------+ | |ant| | |ant-link| | Move towards a direction with the MuJoCo ant robot | +------------------+-----------------------------+-------------------------------------------------------------------------+ | |cartpole| | |cartpole-link| | Move the cart to keep the pole upwards in the classic cartpole control | +------------------+-----------------------------+-------------------------------------------------------------------------+ .. |humanoid| image:: ../_static/tasks/classic/humanoid.jpg .. |ant| image:: ../_static/tasks/classic/ant.jpg .. |cartpole| image:: ../_static/tasks/classic/cartpole.jpg .. |humanoid-link| replace:: `Isaac-Humanoid-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/humanoid_env_cfg.py>`__ .. |ant-link| replace:: `Isaac-Ant-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/ant_env_cfg.py>`__ .. |cartpole-link| replace:: `Isaac-Cartpole-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/cartpole_env_cfg.py>`__ Manipulation ------------ Environments based on fixed-arm manipulation tasks. For many of these tasks, we include configurations with different arm action spaces. For example, for the reach environment: * |lift-cube-link|: Franka arm with joint position control * |lift-cube-ik-abs-link|: Franka arm with absolute IK control * |lift-cube-ik-rel-link|: Franka arm with relative IK control .. table:: :widths: 33 37 30 +----------------+---------------------+-----------------------------------------------------------------------------+ | World | Environment ID | Description | +================+=====================+=============================================================================+ | |reach-franka| | |reach-franka-link| | Move the end-effector to a sampled target pose with the Franka robot | +----------------+---------------------+-----------------------------------------------------------------------------+ | |reach-ur10| | |reach-ur10-link| | Move the end-effector to a sampled target pose with the UR10 robot | +----------------+---------------------+-----------------------------------------------------------------------------+ | |lift-cube| | |lift-cube-link| | Pick a cube and bring it to a sampled target position with the Franka robot | +----------------+---------------------+-----------------------------------------------------------------------------+ | |cabi-franka| | |cabi-franka-link| | Grasp the handle of a cabinet's drawer and open it with the Franka robot | +----------------+---------------------+-----------------------------------------------------------------------------+ .. |reach-franka| image:: ../_static/tasks/manipulation/franka_reach.jpg .. |reach-ur10| image:: ../_static/tasks/manipulation/ur10_reach.jpg .. |lift-cube| image:: ../_static/tasks/manipulation/franka_lift.jpg .. |cabi-franka| image:: ../_static/tasks/manipulation/franka_open_drawer.jpg .. |reach-franka-link| replace:: `Isaac-Reach-Franka-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/franka/joint_pos_env_cfg.py>`__ .. |reach-ur10-link| replace:: `Isaac-Reach-UR10-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/ur_10/joint_pos_env_cfg.py>`__ .. |lift-cube-link| replace:: `Isaac-Lift-Cube-Franka-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/joint_pos_env_cfg.py>`__ .. |lift-cube-ik-abs-link| replace:: `Isaac-Lift-Cube-Franka-IK-Abs-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/ik_abs_env_cfg.py>`__ .. |lift-cube-ik-rel-link| replace:: `Isaac-Lift-Cube-Franka-IK-Rel-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/ik_rel_env_cfg.py>`__ .. |cabi-franka-link| replace:: `Isaac-Open-Drawer-Franka-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/cabinet/config/franka/joint_pos_env_cfg.py>`__ Locomotion ---------- Environments based on legged locomotion tasks. .. table:: :widths: 33 37 30 +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | World | Environment ID | Description | +==============================+==============================================+=========================================================================+ | |velocity-flat-anymal-b| | |velocity-flat-anymal-b-link| | Track a velocity command on flat terrain with the Anymal B robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-anymal-b| | |velocity-rough-anymal-b-link| | Track a velocity command on rough terrain with the Anymal B robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-anymal-c| | |velocity-flat-anymal-c-link| | Track a velocity command on flat terrain with the Anymal C robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-anymal-c| | |velocity-rough-anymal-c-link| | Track a velocity command on rough terrain with the Anymal C robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-anymal-d| | |velocity-flat-anymal-d-link| | Track a velocity command on flat terrain with the Anymal D robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-anymal-d| | |velocity-rough-anymal-d-link| | Track a velocity command on rough terrain with the Anymal D robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-unitree-a1| | |velocity-flat-unitree-a1-link| | Track a velocity command on flat terrain with the Unitree A1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-unitree-a1| | |velocity-rough-unitree-a1-link| | Track a velocity command on rough terrain with the Unitree A1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-unitree-go1| | |velocity-flat-unitree-go1-link| | Track a velocity command on flat terrain with the Unitree Go1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-unitree-go1| | |velocity-rough-unitree-go1-link| | Track a velocity command on rough terrain with the Unitree Go1 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-flat-unitree-go2| | |velocity-flat-unitree-go2-link| | Track a velocity command on flat terrain with the Unitree Go2 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ | |velocity-rough-unitree-go2| | |velocity-rough-unitree-go2-link| | Track a velocity command on rough terrain with the Unitree Go2 robot | +------------------------------+----------------------------------------------+-------------------------------------------------------------------------+ .. |velocity-flat-anymal-b-link| replace:: `Isaac-Velocity-Flat-Anymal-B-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_b/flat_env_cfg.py>`__ .. |velocity-rough-anymal-b-link| replace:: `Isaac-Velocity-Rough-Anymal-B-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_b/rough_env_cfg.py>`__ .. |velocity-flat-anymal-c-link| replace:: `Isaac-Velocity-Flat-Anymal-C-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_c/flat_env_cfg.py>`__ .. |velocity-rough-anymal-c-link| replace:: `Isaac-Velocity-Rough-Anymal-C-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_c/rough_env_cfg.py>`__ .. |velocity-flat-anymal-d-link| replace:: `Isaac-Velocity-Flat-Anymal-D-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_d/flat_env_cfg.py>`__ .. |velocity-rough-anymal-d-link| replace:: `Isaac-Velocity-Rough-Anymal-D-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_d/rough_env_cfg.py>`__ .. |velocity-flat-unitree-a1-link| replace:: `Isaac-Velocity-Flat-Unitree-A1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_a1/flat_env_cfg.py>`__ .. |velocity-rough-unitree-a1-link| replace:: `Isaac-Velocity-Rough-Unitree-A1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_a1/rough_env_cfg.py>`__ .. |velocity-flat-unitree-go1-link| replace:: `Isaac-Velocity-Flat-Unitree-Go1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go1/flat_env_cfg.py>`__ .. |velocity-rough-unitree-go1-link| replace:: `Isaac-Velocity-Rough-Unitree-Go1-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go1/rough_env_cfg.py>`__ .. |velocity-flat-unitree-go2-link| replace:: `Isaac-Velocity-Flat-Unitree-Go2-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go2/flat_env_cfg.py>`__ .. |velocity-rough-unitree-go2-link| replace:: `Isaac-Velocity-Rough-Unitree-Go2-v0 <https://github.com/NVIDIA-Omniverse/orbit/blob/main/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go2/rough_env_cfg.py>`__ .. |velocity-flat-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_flat.jpg .. |velocity-rough-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_rough.jpg .. |velocity-flat-anymal-c| image:: ../_static/tasks/locomotion/anymal_c_flat.jpg .. |velocity-rough-anymal-c| image:: ../_static/tasks/locomotion/anymal_c_rough.jpg .. |velocity-flat-anymal-d| image:: ../_static/tasks/locomotion/anymal_d_flat.jpg .. |velocity-rough-anymal-d| image:: ../_static/tasks/locomotion/anymal_d_rough.jpg .. |velocity-flat-unitree-a1| image:: ../_static/tasks/locomotion/a1_flat.jpg .. |velocity-rough-unitree-a1| image:: ../_static/tasks/locomotion/a1_rough.jpg .. |velocity-flat-unitree-go1| image:: ../_static/tasks/locomotion/go1_flat.jpg .. |velocity-rough-unitree-go1| image:: ../_static/tasks/locomotion/go1_rough.jpg .. |velocity-flat-unitree-go2| image:: ../_static/tasks/locomotion/go2_flat.jpg .. |velocity-rough-unitree-go2| image:: ../_static/tasks/locomotion/go2_rough.jpg
NVIDIA-Omniverse/orbit/docs/source/deployment/cluster.rst
.. _deployment-cluster: Cluster Guide ============= Clusters are a great way to speed up training and evaluation of learning algorithms. While the Orbit Docker image can be used to run jobs on a cluster, many clusters only support singularity images. This is because `singularity`_ is designed for ease-of-use on shared multi-user systems and high performance computing (HPC) environments. It does not require root privileges to run containers and can be used to run user-defined containers. Singularity is compatible with all Docker images. In this section, we describe how to convert the Orbit Docker image into a singularity image and use it to submit jobs to a cluster. .. attention:: Cluster setup varies across different institutions. The following instructions have been tested on the `ETH Zurich Euler`_ cluster, which uses the SLURM workload manager. The instructions may need to be adapted for other clusters. If you have successfully adapted the instructions for another cluster, please consider contributing to the documentation. Setup Instructions ------------------ In order to export the Docker Image to a singularity image, `apptainer`_ is required. A detailed overview of the installation procedure for ``apptainer`` can be found in its `documentation`_. For convenience, we summarize the steps here for a local installation: .. code:: bash sudo apt update sudo apt install -y software-properties-common sudo add-apt-repository -y ppa:apptainer/ppa sudo apt update sudo apt install -y apptainer For simplicity, we recommend that an SSH connection is set up between the local development machine and the cluster. Such a connection will simplify the file transfer and prevent the user cluster password from being requested multiple times. .. attention:: The workflow has been tested with ``apptainer version 1.2.5-1.el7`` and ``docker version 24.0.7``. - ``apptainer``: There have been reported binding issues with previous versions (such as ``apptainer version 1.1.3-1.el7``). Please ensure that you are using the latest version. - ``Docker``: The latest versions (``25.x``) cannot be used as they are not compatible yet with apptainer/ singularity. We are waiting for an update from the apptainer team. To track this issue, please check the `forum post`_. Configuring the cluster parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ First, you need to configure the cluster-specific parameters in ``docker/.env.base`` file. The following describes the parameters that need to be configured: - ``CLUSTER_ISAAC_SIM_CACHE_DIR``: The directory on the cluster where the Isaac Sim cache is stored. This directory has to end on ``docker-isaac-sim``. This directory will be copied to the compute node and mounted into the singularity container. It should increase the speed of starting the simulation. - ``CLUSTER_ORBIT_DIR``: The directory on the cluster where the orbit code is stored. This directory has to end on ``orbit``. This directory will be copied to the compute node and mounted into the singularity container. When a job is submitted, the latest local changes will be copied to the cluster. - ``CLUSTER_LOGIN``: The login to the cluster. Typically, this is the user and cluster names, e.g., ``[email protected]``. - ``CLUSTER_SIF_PATH``: The path on the cluster where the singularity image will be stored. The image will be copied to the compute node but not uploaded again to the cluster when a job is submitted. - ``CLUSTER_PYTHON_EXECUTABLE``: The path within orbit to the Python executable that should be executed in the submitted job. Exporting to singularity image ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Next, we need to export the Docker image to a singularity image and upload it to the cluster. This step is only required once when the first job is submitted or when the Docker image is updated. For instance, due to an upgrade of the Isaac Sim version, or additional requirements for your project. To export to a singularity image, execute the following command: .. code:: bash ./docker/container.sh push [profile] This command will create a singularity image under ``docker/exports`` directory and upload it to the defined location on the cluster. Be aware that creating the singularity image can take a while. ``[profile]`` is an optional argument that specifies the container profile to be used. If no profile is specified, the default profile ``base`` will be used. .. note:: By default, the singularity image is created without root access by providing the ``--fakeroot`` flag to the ``apptainer build`` command. In case the image creation fails, you can try to create it with root access by removing the flag in ``docker/container.sh``. Job Submission and Execution ---------------------------- Defining the job parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The job parameters are defined inside the ``docker/cluster/submit_job.sh``. A typical SLURM operation requires specifying the number of CPUs and GPUs, the memory, and the time limit. For more information, please check the `SLURM documentation`_. The default configuration is as follows: .. literalinclude:: ../../../docker/cluster/submit_job.sh :language: bash :lines: 12-19 :linenos: :lineno-start: 12 An essential requirement for the cluster is that the compute node has access to the internet at all times. This is required to load assets from the Nucleus server. For some cluster architectures, extra modules must be loaded to allow internet access. For instance, on ETH Zurich Euler cluster, the ``eth_proxy`` module needs to be loaded. This can be done by adding the following line to the ``submit_job.sh`` script: .. literalinclude:: ../../../docker/cluster/submit_job.sh :language: bash :lines: 3-5 :linenos: :lineno-start: 3 Submitting a job ~~~~~~~~~~~~~~~~ To submit a job on the cluster, the following command can be used: .. code:: bash ./docker/container.sh job [profile] "argument1" "argument2" ... This command will copy the latest changes in your code to the cluster and submit a job. Please ensure that your Python executable's output is stored under ``orbit/logs`` as this directory will be copied again from the compute node to ``CLUSTER_ORBIT_DIR``. ``[profile]`` is an optional argument that specifies which singularity image corresponding to the container profile will be used. If no profile is specified, the default profile ``base`` will be used. The profile has be defined directlty after the ``job`` command. All other arguments are passed to the Python executable. If no profile is defined, all arguments are passed to the Python executable. The training arguments are passed to the Python executable. As an example, the standard ANYmal rough terrain locomotion training can be executed with the following command: .. code:: bash ./docker/container.sh job --task Isaac-Velocity-Rough-Anymal-C-v0 --headless --video --offscreen_render The above will, in addition, also render videos of the training progress and store them under ``orbit/logs`` directory. .. note:: The ``./docker/container.sh job`` command will copy the latest changes in your code to the cluster. However, it will not delete any files that have been deleted locally. These files will still exist on the cluster which can lead to issues. In this case, we recommend removing the ``CLUSTER_ORBIT_DIR`` directory on the cluster and re-run the command. .. _Singularity: https://docs.sylabs.io/guides/2.6/user-guide/index.html .. _ETH Zurich Euler: https://scicomp.ethz.ch/wiki/Euler .. _apptainer: https://apptainer.org/ .. _documentation: www.apptainer.org/docs/admin/main/installation.html#install-ubuntu-packages .. _SLURM documentation: www.slurm.schedmd.com/sbatch.html .. _forum post: https://forums.docker.com/t/trouble-after-upgrade-to-docker-ce-25-0-1-on-debian-12/139613
NVIDIA-Omniverse/orbit/docs/source/deployment/run_docker_example.rst
Running an example with Docker ============================== From the root of the ``orbit`` repository, the ``docker`` directory contains all the Docker relevant files. These include the three files (**Dockerfile**, **docker-compose.yaml**, **.env**) which are used by Docker, and an additional script that we use to interface with them, **container.sh**. In this tutorial, we will learn how to use the Orbit Docker container for development. For a detailed description of the Docker setup, including installation and obtaining access to an Isaac Sim image, please reference the :ref:`deployment-docker`. For a description of Docker in general, please refer to `their official documentation <https://docs.docker.com/get-started/overview/>`_. Building the Container ~~~~~~~~~~~~~~~~~~~~~~ To build the Orbit container from the root of the Orbit repository, we will run the following: .. code-block:: console ./docker/container.sh start The terminal will first pull the base IsaacSim image, build the Orbit image's additional layers on top of it, and run the Orbit container. This should take several minutes upon the first build but will be shorter in subsequent runs as Docker's caching prevents repeated work. If we run the command ``docker container ls`` on the terminal, the output will list the containers that are running on the system. If everything has been set up correctly, a container with the ``NAME`` **orbit** should appear, similar to below: .. code-block:: console CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 483d1d5e2def orbit "bash" 30 seconds ago Up 30 seconds orbit Once the container is up and running, we can enter it from our terminal. .. code-block:: console ./docker/container.sh enter On entering the Orbit container, we are in the terminal as the superuser, ``root``. This environment contains a copy of the Orbit repository, but also has access to the directories and libraries of Isaac Sim. We can run experiments from this environment using a few convenient aliases that have been put into the ``root`` **.bashrc**. For instance, we have made the **orbit.sh** script usable from anywhere by typing its alias ``orbit``. Additionally in the container, we have `bind mounted`_ the ``orbit/source`` directory from the host machine. This means that if we modify files under this directory from an editor on the host machine, the changes are reflected immediately within the container without requiring us to rebuild the Docker image. We will now run a sample script from within the container to demonstrate how to extract artifacts from the Orbit Docker container. The Code ~~~~~~~~ The tutorial corresponds to the ``log_time.py`` script in the ``orbit/source/standalone/tutorials/00_sim`` directory. .. dropdown:: Code for log_time.py :icon: code .. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py :language: python :emphasize-lines: 46-55, 72-79 :linenos: The Code Explained ~~~~~~~~~~~~~~~~~~ The Orbit Docker container has several `volumes`_ to facilitate persistent storage between the host computer and the container. One such volume is the ``/workspace/orbit/logs`` directory. The ``log_time.py`` script designates this directory as the location to which a ``log.txt`` should be written: .. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py :language: python :start-at: # Specify that the logs must be in logs/docker_tutorial :end-at: print(f"[INFO] Logging experiment to directory: {log_dir_path}") As the comments note, :func:`os.path.abspath()` will prepend ``/workspace/orbit`` because in the Docker container all python execution is done through ``/workspace/orbit/orbit.sh``. The output will be a file, ``log.txt``, with the ``sim_time`` written on a newline at every simulation step: .. literalinclude:: ../../../source/standalone/tutorials/00_sim/log_time.py :language: python :start-at: # Prepare to count sim_time :end-at: sim_time += sim_dt Executing the Script ~~~~~~~~~~~~~~~~~~~~ We will execute the script to produce a log, adding a ``--headless`` flag to our execution to prevent a GUI: .. code-block:: bash orbit -p source/standalone/tutorials/00_sim/log_time.py --headless Now ``log.txt`` will have been produced at ``/workspace/orbit/logs/docker_tutorial``. If we exit the container by typing ``exit``, we will return to ``orbit/docker`` in our host terminal environment. We can then enter the following command to retrieve our logs from the Docker container and put them on our host machine: .. code-block:: console ./container.sh copy We will see a terminal readout reporting the artifacts we have retrieved from the container. If we navigate to ``/orbit/docker/artifacts/logs/docker_tutorial``, we will see a copy of the ``log.txt`` file which was produced by the script above. Each of the directories under ``artifacts`` corresponds to Docker `volumes`_ mapped to directories within the container and the ``container.sh copy`` command copies them from those `volumes`_ to these directories. We could return to the Orbit Docker terminal environment by running ``container.sh enter`` again, but we have retrieved our logs and wish to go inspect them. We can stop the Orbit Docker container with the following command: .. code-block:: console ./container.sh stop This will bring down the Docker Orbit container. The image will persist and remain available for further use, as will the contents of any `volumes`_. If we wish to free up the disk space taken by the image, (~20.1GB), and do not mind repeating the build process when we next run ``./container.sh start``, we may enter the following command to delete the **orbit** image: .. code-block:: console docker image rm orbit A subsequent run of ``docker image ls``` will show that the image tagged **orbit** is now gone. We can repeat the process for the underlying NVIDIA container if we wish to free up more space. If a more powerful method of freeing resources from Docker is desired, please consult the documentation for the `docker prune`_ commands. .. _volumes: https://docs.docker.com/storage/volumes/ .. _bind mounted: https://docs.docker.com/storage/bind-mounts/ .. _docker prune: https://docs.docker.com/config/pruning/
NVIDIA-Omniverse/orbit/docs/source/deployment/docker.rst
.. _deployment-docker: Docker Guide ============ .. caution:: Due to the dependency on Isaac Sim docker image, by running this container you are implicitly agreeing to the `NVIDIA Omniverse EULA`_. If you do not agree to the EULA, do not run this container. Setup Instructions ------------------ .. note:: The following steps are taken from the NVIDIA Omniverse Isaac Sim documentation on `container installation`_. They have been added here for the sake of completeness. Docker and Docker Compose ~~~~~~~~~~~~~~~~~~~~~~~~~ We have tested the container using Docker Engine version 26.0.0 and Docker Compose version 2.25.0 We recommend using these versions or newer. * To install Docker, please follow the instructions for your operating system on the `Docker website`_. * To install Docker Compose, please follow the instructions for your operating system on the `docker compose`_ page. * Follow the post-installation steps for Docker on the `post-installation steps`_ page. These steps allow you to run Docker without using ``sudo``. * To build and run GPU-accelerated containers, you also need install the `NVIDIA Container Toolkit`_. Please follow the instructions on the `Container Toolkit website`_ for installation steps. Obtaining the Isaac Sim Container ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Get access to the `Isaac Sim container`_ by joining the NVIDIA Developer Program credentials. * Generate your `NGC API key`_ to access locked container images from NVIDIA GPU Cloud (NGC). * This step requires you to create an NGC account if you do not already have one. * You would also need to install the NGC CLI to perform operations from the command line. * Once you have your generated API key and have installed the NGC CLI, you need to log in to NGC from the terminal. .. code:: bash ngc config set * Use the command line to pull the Isaac Sim container image from NGC. .. code:: bash docker login nvcr.io * For the username, enter ``$oauthtoken`` exactly as shown. It is a special username that is used to authenticate with NGC. .. code:: text Username: $oauthtoken Password: <Your NGC API Key> Directory Organization ---------------------- The root of the Orbit repository contains the ``docker`` directory that has various files and scripts needed to run Orbit inside a Docker container. A subset of these are summarized below: * ``Dockerfile.base``: Defines the orbit image by overlaying Orbit dependencies onto the Isaac Sim Docker image. ``Dockerfiles`` which end with something else, (i.e. ``Dockerfile.ros2``) build an `image_extension <#orbit-image-extensions>`_. * ``docker-compose.yaml``: Creates mounts to allow direct editing of Orbit code from the host machine that runs the container. It also creates several named volumes such as ``isaac-cache-kit`` to store frequently re-used resources compiled by Isaac Sim, such as shaders, and to retain logs, data, and documents. * ``base.env``: Stores environment variables required for the ``base`` build process and the container itself. ``.env`` files which end with something else (i.e. ``.env.ros2``) define these for `image_extension <#orbit-image-extensions>`_. * ``container.sh``: A script that wraps the ``docker compose`` command to build the image and run the container. Running the Container --------------------- .. note:: The docker container copies all the files from the repository into the container at the location ``/workspace/orbit`` at build time. This means that any changes made to the files in the container would not normally be reflected in the repository after the image has been built, i.e. after ``./container.sh start`` is run. For a faster development cycle, we mount the following directories in the Orbit repository into the container so that you can edit their files from the host machine: * ``source``: This is the directory that contains the Orbit source code. * ``docs``: This is the directory that contains the source code for Orbit documentation. This is overlaid except for the ``_build`` subdirectory where build artifacts are stored. The script ``container.sh`` wraps around three basic ``docker compose`` commands. Each can accept an `image_extension argument <#orbit-image-extensions>`_, or else they will default to image_extension ``base``: 1. ``start``: This builds the image and brings up the container in detached mode (i.e. in the background). 2. ``enter``: This begins a new bash process in an existing orbit container, and which can be exited without bringing down the container. 3. ``copy``: This copies the ``logs``, ``data_storage`` and ``docs/_build`` artifacts, from the ``orbit-logs``, ``orbit-data`` and ``orbit-docs`` volumes respectively, to the ``docker/artifacts`` directory. These artifacts persist between docker container instances and are shared between image extensions. 4. ``stop``: This brings down the container and removes it. The following shows how to launch the container in a detached state and enter it: .. code:: bash # Launch the container in detached mode # We don't pass an image extension arg, so it defaults to 'base' ./docker/container.sh start # Enter the container # We pass 'base' explicitly, but if we hadn't it would default to 'base' ./docker/container.sh enter base To copy files from the base container to the host machine, you can use the following command: .. code:: bash # Copy the file /workspace/orbit/logs to the current directory docker cp orbit-base:/workspace/orbit/logs . The script ``container.sh`` provides a wrapper around this command to copy the ``logs`` , ``data_storage`` and ``docs/_build`` directories to the ``docker/artifacts`` directory. This is useful for copying the logs, data and documentation: .. code:: # stop the container ./docker/container.sh stop Python Interpreter ~~~~~~~~~~~~~~~~~~ The container uses the Python interpreter provided by Isaac Sim. This interpreter is located at ``/isaac-sim/python.sh``. We set aliases inside the container to make it easier to run the Python interpreter. You can use the following commands to run the Python interpreter: .. code:: bash # Run the Python interpreter -> points to /isaac-sim/python.sh python Understanding the mounted volumes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``docker-compose.yaml`` file creates several named volumes that are mounted to the container. These are summarized below: * ``isaac-cache-kit``: This volume is used to store cached Kit resources (`/isaac-sim/kit/cache` in container) * ``isaac-cache-ov``: This volume is used to store cached OV resources (`/root/.cache/ov` in container) * ``isaac-cache-pip``: This volume is used to store cached pip resources (`/root/.cache/pip`` in container) * ``isaac-cache-gl``: This volume is used to store cached GLCache resources (`/root/.cache/nvidia/GLCache` in container) * ``isaac-cache-compute``: This volume is used to store cached compute resources (`/root/.nv/ComputeCache` in container) * ``isaac-logs``: This volume is used to store logs generated by Omniverse. (`/root/.nvidia-omniverse/logs` in container) * ``isaac-carb-logs``: This volume is used to store logs generated by carb. (`/isaac-sim/kit/logs/Kit/Isaac-Sim` in container) * ``isaac-data``: This volume is used to store data generated by Omniverse. (`/root/.local/share/ov/data` in container) * ``isaac-docs``: This volume is used to store documents generated by Omniverse. (`/root/Documents` in container) * ``orbit-docs``: This volume is used to store documentation of Orbit when built inside the container. (`/workspace/orbit/docs/_build` in container) * ``orbit-logs``: This volume is used to store logs generated by Orbit workflows when run inside the container. (`/workspace/orbit/logs` in container) * ``orbit-data``: This volume is used to store whatever data users may want to preserve between container runs. (`/workspace/orbit/data_storage` in container) To view the contents of these volumes, you can use the following command: .. code:: bash # list all volumes docker volume ls # inspect a specific volume, e.g. isaac-cache-kit docker volume inspect isaac-cache-kit Orbit Image Extensions ---------------------- The produced image depends upon the arguments passed to ``./container.sh start`` and ``./container.sh stop``. These commands accept an ``image_extension`` as an additional argument. If no argument is passed, then these commands default to ``base``. Currently, the only valid ``image_extension`` arguments are (``base``, ``ros2``). Only one ``image_extension`` can be passed at a time, and the produced container will be named ``orbit``. .. code:: bash # start base by default ./container.sh start # stop base explicitly ./container.sh stop base # start ros2 container ./container.sh start ros2 # stop ros2 container ./container.sh stop ros2 The passed ``image_extension`` argument will build the image defined in ``Dockerfile.${image_extension}``, with the corresponding `profile`_ in the ``docker-compose.yaml`` and the envars from ``.env.${image_extension}`` in addition to the ``.env.base``, if any. ROS2 Image Extension ~~~~~~~~~~~~~~~~~~~~ In ``Dockerfile.ros2``, the container installs ROS2 Humble via an `apt package`_, and it is sourced in the ``.bashrc``. The exact version is specified by the variable ``ROS_APT_PACKAGE`` in the ``.env.ros2`` file, defaulting to ``ros-base``. Other relevant ROS2 variables are also specified in the ``.env.ros2`` file, including variables defining the `various middleware`_ options. The container defaults to ``FastRTPS``, but ``CylconeDDS`` is also supported. Each of these middlewares can be `tuned`_ using their corresponding ``.xml`` files under ``docker/.ros``. Known Issues ------------ Invalid mount config for type "bind" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you see the following error when building the container: .. code:: text ⠋ Container orbit Creating 0.0s Error response from daemon: invalid mount config for type "bind": bind source path does not exist: ${HOME}/.Xauthority This means that the ``.Xauthority`` file is not present in the home directory of the host machine. The portion of the docker-compose.yaml that enables this is commented out by default, so this shouldn't happen unless it has been altered. This file is required for X11 forwarding to work. To fix this, you can create an empty ``.Xauthority`` file in your home directory. .. code:: bash touch ${HOME}/.Xauthority A similar error but requires a different fix: .. code:: text ⠋ Container orbit Creating 0.0s Error response from daemon: invalid mount config for type "bind": bind source path does not exist: /tmp/.X11-unix This means that the folder/files are either not present or not accessible on the host machine. The portion of the docker-compose.yaml that enables this is commented out by default, so this shouldn't happen unless it has been altered. This usually happens when you have multiple docker versions installed on your machine. To fix this, you can try the following: * Remove all docker versions from your machine. .. code:: bash sudo apt remove docker* sudo apt remove docker docker-engine docker.io containerd runc docker-desktop docker-compose-plugin sudo snap remove docker sudo apt clean autoclean && sudo apt autoremove --yes * Install the latest version of docker based on the instructions in the setup section. WebRTC and WebSocket Streaming ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When streaming the GUI from Isaac Sim, there are `several streaming clients`_ available. There is a `known issue`_ when attempting to use WebRTC streaming client on Google Chrome and Safari while running Isaac Sim inside a container. To avoid this problem, we suggest using either the Native Streaming Client or WebSocket options, or using the Mozilla Firefox browser on which WebRTC works. Streaming is the only supported method for visualizing the Isaac GUI from within the container. The Omniverse Streaming Client is freely available from the Omniverse app, and is easy to use. The other streaming methods similarly require only a web browser. If users want to use X11 forwarding in order to have the apps behave as local GUI windows, they can uncomment the relevant portions in docker-compose.yaml. .. _`NVIDIA Omniverse EULA`: https://docs.omniverse.nvidia.com/platform/latest/common/NVIDIA_Omniverse_License_Agreement.html .. _`container installation`: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_container.html .. _`Docker website`: https://docs.docker.com/desktop/install/linux-install/ .. _`docker compose`: https://docs.docker.com/compose/install/linux/#install-using-the-repository .. _`NVIDIA Container Toolkit`: https://github.com/NVIDIA/nvidia-container-toolkit .. _`Container Toolkit website`: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html .. _`post-installation steps`: https://docs.docker.com/engine/install/linux-postinstall/ .. _`Isaac Sim container`: https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim .. _`NGC API key`: https://docs.nvidia.com/ngc/gpu-cloud/ngc-user-guide/index.html#generating-api-key .. _`several streaming clients`: https://docs.omniverse.nvidia.com/isaacsim/latest/installation/manual_livestream_clients.html .. _`known issue`: https://forums.developer.nvidia.com/t/unable-to-use-webrtc-when-i-run-runheadless-webrtc-sh-in-remote-headless-container/222916 .. _`profile`: https://docs.docker.com/compose/compose-file/15-profiles/ .. _`apt package`: https://docs.ros.org/en/humble/Installation/Ubuntu-Install-Debians.html#install-ros-2-packages .. _`various middleware`: https://docs.ros.org/en/humble/How-To-Guides/Working-with-multiple-RMW-implementations.html .. _`tuned`: https://docs.ros.org/en/foxy/How-To-Guides/DDS-tuning.html
NVIDIA-Omniverse/orbit/docs/source/deployment/index.rst
Container Deployment ==================== Docker is a tool that allows for the creation of containers, which are isolated environments that can be used to run applications. They are useful for ensuring that an application can run on any machine that has Docker installed, regardless of the host machine's operating system or installed libraries. We include a Dockerfile and docker-compose.yaml file that can be used to build a Docker image that contains Orbit and all of its dependencies. This image can then be used to run Orbit in a container. The Dockerfile is based on the Isaac Sim image provided by NVIDIA, which includes the Omniverse application launcher and the Isaac Sim application. The Dockerfile installs Orbit and its dependencies on top of this image. The following guides provide instructions for building the Docker image and running Orbit in a container. .. toctree:: :maxdepth: 1 docker cluster run_docker_example
NVIDIA-Omniverse/orbit/docs/source/refs/migration.rst
Migration Guide (Isaac Sim) =========================== Moving from Isaac Sim 2022.2.1 to 2023.1.0 brings in a number of changes to the APIs and the way the application is built. This document outlines the changes and how to migrate your code to the new APIs. Many of these changes attribute to the underlying Omniverse Kit upgrade from 104.2 to 105.1. The new upgrade brings the following notable changes: * Update to USD 22.11 * Upgrading the Python from 3.7 to 3.10 .. warning:: This document is a work in progress and will be updated as we move closer to the release of Isaac Sim 2023.1.0. Renaming of PhysX Flatcache to PhysX Fabric ------------------------------------------- The PhysX Flatcache has been renamed to PhysX Fabric. The new name is more descriptive of the functionality and is consistent with the naming convention used by Omniverse called `Fabric`_. Consequently, the Python module name has also been changed from :mod:`omni.physxflatcache` to :mod:`omni.physxfabric`. Following this, on the Isaac Sim side, various renaming have occurred: * The parameter passed to :class:`SimulationContext` constructor via the keyword :obj:`sim_params` now expects the key ``use_fabric`` instead of ``use_flatcache``. * The Python attribute :attr:`SimulationContext.get_physics_context().use_flatcache` is now :attr:`SimulationContext.get_physics_context().use_fabric`. * The Python function :meth:`SimulationContext.get_physics_context().enable_flatcache` is now :meth:`SimulationContext.get_physics_context().enable_fabric`. Renaming of the URDF and MJCF Importers --------------------------------------- Starting from Isaac Sim 2023.1, the URDF and MJCF importers have been renamed to be more consistent with the other asset importers in Omniverse. The importers are now available on NVIDIA-Omniverse GitHub as open source projects. Due to the extension name change, the Python module names have also been changed: * URDF Importer: :mod:`omni.importer.urdf` (previously :mod:`omni.isaac.urdf`) * MJCF Importer: :mod:`omni.importer.mjcf` (previously :mod:`omni.isaac.mjcf`) Deprecation of :class:`UsdLux.Light` API ---------------------------------------- As highlighted in the release notes of `USD 22.11`_, the ``UsdLux.Light`` API has been deprecated in favor of the new ``UsdLuxLightAPI`` API. In the new API the attributes are prefixed with ``inputs:``. For example, the ``intensity`` attribute is now available as ``inputs:intensity``. The following example shows how to create a sphere light using the old API and the new API. .. dropdown:: Code for Isaac Sim 2022.2.1 and below :icon: code .. code-block:: python import omni.isaac.core.utils.prims as prim_utils prim_utils.create_prim( "/World/Light/GreySphere", "SphereLight", translation=(4.5, 3.5, 10.0), attributes={"radius": 2.5, "intensity": 600.0, "color": (0.75, 0.75, 0.75)}, ) .. dropdown:: Code for Isaac Sim 2023.1.0 and above :icon: code .. code-block:: python import omni.isaac.core.utils.prims as prim_utils prim_utils.create_prim( "/World/Light/WhiteSphere", "SphereLight", translation=(-4.5, 3.5, 10.0), attributes={ "inputs:radius": 2.5, "inputs:intensity": 600.0, "inputs:color": (1.0, 1.0, 1.0) }, ) .. _Fabric: https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/usd_fabric_usdrt.html .. _`USD 22.11`: https://github.com/PixarAnimationStudios/OpenUSD/blob/release/CHANGELOG.md
NVIDIA-Omniverse/orbit/docs/source/refs/changelog.rst
Extensions Changelog ==================== All notable changes to this project are documented in this file. The format is based on `Keep a Changelog <https://keepachangelog.com/en/1.0.0/>`__ and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`__. Each extension has its own changelog. The changelog for each extension is located in the ``docs`` directory of the extension. The changelog for each extension is also included in this changelog to make it easier to find the changelog for a specific extension. omni.isaac.orbit ----------------- Extension containing the core framework of Orbit. .. include:: ../../../source/extensions/omni.isaac.orbit/docs/CHANGELOG.rst :start-line: 3 omni.isaac.orbit_assets ------------------------ Extension for configurations of various assets and sensors for Orbit. .. include:: ../../../source/extensions/omni.isaac.orbit_assets/docs/CHANGELOG.rst :start-line: 3 omni.isaac.orbit_tasks ---------------------- Extension containing the environments built using Orbit. .. include:: ../../../source/extensions/omni.isaac.orbit_tasks/docs/CHANGELOG.rst :start-line: 3
NVIDIA-Omniverse/orbit/docs/source/refs/issues.rst
Known Issues ============ .. attention:: Please also refer to the `Omniverse Isaac Sim documentation`_ for known issues and workarounds. Stale values after resetting the environment -------------------------------------------- When resetting the environment, some of the data fields of assets and sensors are not updated. These include the poses of links in a kinematic chain, the camera images, the contact sensor readings, and the lidar point clouds. This is a known issue which has to do with the way the PhysX and rendering engines work in Omniverse. Many physics engines do a simulation step as a two-level call: ``forward()`` and ``simulate()``, where the kinematic and dynamic states are updated, respectively. Unfortunately, PhysX has only a single ``step()`` call where the two operations are combined. Due to computations through GPU kernels, it is not so straightforward for them to split these operations. Thus, at the moment, it is not possible to set the root and/or joint states and do a forward call to update the kinematic states of links. This affects both initialization as well as episodic resets. Similarly for RTX rendering related sensors (such as cameras), the sensor data is not updated immediately after setting the state of the sensor. The rendering engine update is bundled with the simulator's ``step()`` call which only gets called when the simulation is stepped forward. This means that the sensor data is not updated immediately after a reset and it will hold outdated values. While the above is erroneous, there is currently no direct workaround for it. From our experience in using IsaacGym, the reset values affect the agent learning critically depending on how frequently the environment terminates. Eventually if the agent is learning successfully, this number drops and does not affect the performance that critically. We have made a feature request to the respective Omniverse teams to have complete control over stepping different parts of the simulation app. However, at this point, there is no set timeline for this feature request. Non-determinism in physics simulation ------------------------------------- Due to GPU work scheduling, there's a possibility that runtime changes to simulation parameters may alter the order in which operations take place. This occurs because environment updates can happen while the GPU is occupied with other tasks. Due to the inherent nature of floating-point numeric storage, any modification to the execution ordering can result in minor changes in the least significant bits of output data. These changes may lead to divergent execution over the course of simulating thousands of environments and simulation frames. An illustrative example of this issue is observed with the runtime domain randomization of object's physics materials. This process can introduce both determinancy and simulation issues when executed on the GPU due to the way these parameters are passed from the CPU to the GPU in the lower-level APIs. Consequently, it is strongly advised to perform this operation only at setup time, before the environment stepping commences. For more information, please refer to the `PhysX Determinism documentation`_. Blank initial frames from the camera ------------------------------------ When using the :class:`omni.isaac.orbit.sensors.Camera` sensor in standalone scripts, the first few frames may be blank. This is a known issue with the simulator where it needs a few steps to load the material textures properly and fill up the render targets. A hack to work around this is to add the following after initializing the camera sensor and setting its pose: .. code-block:: python from omni.isaac.orbit.sim import SimulationContext sim = SimulationContext.instance() # note: the number of steps might vary depending on how complicated the scene is. for _ in range(12): sim.render() Using instanceable assets for markers ------------------------------------- When using `instanceable assets`_ for markers, the markers do not work properly, since Omniverse does not support instanceable assets when using the :class:`UsdGeom.PointInstancer` schema. This is a known issue and will hopefully be fixed in a future release. If you use an instanceable assets for markers, the marker class removes all the physics properties of the asset. This is then replicated across other references of the same asset since physics properties of instanceable assets are stored in the instanceable asset's USD file and not in its stage reference's USD file. .. _instanceable assets: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gym_instanceable_assets.html .. _Omniverse Isaac Sim documentation: https://docs.omniverse.nvidia.com/isaacsim/latest/known_issues.html .. _PhysX Determinism documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.3.1/docs/BestPractices.html#determinism
NVIDIA-Omniverse/orbit/docs/source/refs/troubleshooting.rst
Tricks and Troubleshooting ========================== .. note:: The following lists some of the common tricks and troubleshooting methods that we use in our common workflows. Please also check the `troubleshooting page on Omniverse <https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/linux_troubleshooting.html>`__ for more assistance. Checking the internal logs from the simulator --------------------------------------------- When running the simulator from a standalone script, it logs warnings and errors to the terminal. At the same time, it also logs internal messages to a file. These are useful for debugging and understanding the internal state of the simulator. Depending on your system, the log file can be found in the locations listed `here <https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_faq.html#common-path-locations>`_. To obtain the exact location of the log file, you need to check the first few lines of the terminal output when you run the standalone script. The log file location is printed at the start of the terminal output. For example: .. code:: bash [INFO] Using python from: /home/${USER}/git/orbit/_isaac_sim/python.sh ... Passing the following args to the base kit application: [] Loading user config located at: '.../data/Kit/Isaac-Sim/2023.1/user.config.json' [Info] [carb] Logging to file: '.../logs/Kit/Isaac-Sim/2023.1/kit_20240328_183346.log' In the above example, the log file is located at ``.../logs/Kit/Isaac-Sim/2023.1/kit_20240328_183346.log``, ``...`` is the path to the user's log directory. The log file is named ``kit_20240328_183346.log`` You can open this file to check the internal logs from the simulator. Also when reporting issues, please include this log file to help us debug the issue. Using CPU Scaling Governor for performance ------------------------------------------ By default on many systems, the CPU frequency governor is set to “powersave” mode, which sets the CPU to lowest static frequency. To increase the maximum performance, we recommend setting the CPU frequency governor to “performance” mode. For more details, please check the the link `here <https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/power_management_guide/cpufreq_governors>`__. .. warning:: We advice not to set the governor to “performance” mode on a system with poor cooling (such as laptops), since it may cause the system to overheat. - To view existing ``scaling_governor`` value per CPU: .. code:: bash cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor - To change the governor to “performance” mode for each CPU: .. code:: bash echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor Observing long load times at the start of the simulation -------------------------------------------------------- The first time you run the simulator, it will take a long time to load up. This is because the simulator is compiling shaders and loading assets. Subsequent runs should be faster to start up, but may still take some time. Please note that once the Isaac Sim app loads, the environment creation time may scale linearly with the number of environments. Please expect a longer load time if running with thousands of environments or if each environment contains a larger number of assets. We are continually working on improving the time needed for this. When an instance of Isaac Sim is already running, launching another Isaac Sim instance in a different process may appear to hang at startup for the first time. Please be patient and give it some time as the second process will take longer to start up due to slower shader compilation. Receiving a “PhysX error” when running simulation on GPU -------------------------------------------------------- When using the GPU pipeline, the buffers used for the physics simulation are allocated on the GPU only once at the start of the simulation. This means that they do not grow dynamically as the number of collisions or objects in the scene changes. If the number of collisions or objects in the scene exceeds the size of the buffers, the simulation will fail with an error such as the following: .. code:: bash PhysX error: the application need to increase the PxgDynamicsMemoryConfig::foundLostPairsCapacity parameter to 3072, otherwise the simulation will miss interactions In this case, you need to increase the size of the buffers passed to the :class:`~omni.isaac.orbit.sim.SimulationContext` class. The size of the buffers can be increased by setting the :attr:`~omni.isaac.orbit.sim.PhysxCfg.gpu_found_lost_pairs_capacity` parameter in the :class:`~omni.isaac.orbit.sim.PhysxCfg` class. For example, to increase the size of the buffers to 4096, you can use the following code: .. code:: python import omni.isaac.orbit.sim as sim_utils sim_cfg = sim_utils.SimulationConfig() sim_cfg.physx.gpu_found_lost_pairs_capacity = 4096 sim = SimulationContext(sim_params=sim_cfg) Please see the documentation for :class:`~omni.isaac.orbit.sim.SimulationCfg` for more details on the parameters that can be used to configure the simulation. Preventing memory leaks in the simulator ---------------------------------------- Memory leaks in the Isaac Sim simulator can occur when C++ callbacks are registered with Python objects. This happens when callback functions within classes maintain references to the Python objects they are associated with. As a result, Python's garbage collection is unable to reclaim memory associated with these objects, preventing the corresponding C++ objects from being destroyed. Over time, this can lead to memory leaks and increased resource usage. To prevent memory leaks in the Isaac Sim simulator, it is essential to use weak references when registering callbacks with the simulator. This ensures that Python objects can be garbage collected when they are no longer needed, thereby avoiding memory leaks. The `weakref <https://docs.python.org/3/library/weakref.html>`_ module from the Python standard library can be employed for this purpose. For example, consider a class with a callback function ``on_event_callback`` that needs to be registered with the simulator. If you use a strong reference to the ``MyClass`` object when passing the callback, the reference count of the ``MyClass`` object will be incremented. This prevents the ``MyClass`` object from being garbage collected when it is no longer needed, i.e., the ``__del__`` destructor will not be called. .. code:: python import omni.kit class MyClass: def __init__(self): app_interface = omni.kit.app.get_app_interface() self._handle = app_interface.get_post_update_event_stream().create_subscription_to_pop( self.on_event_callback ) def __del__(self): self._handle.unsubscribe() self._handle = None def on_event_callback(self, event): # do something with the message To fix this issue, it's crucial to employ weak references when registering the callback. While this approach adds some verbosity to the code, it ensures that the ``MyClass`` object can be garbage collected when no longer in use. Here's the modified code: .. code:: python import omni.kit import weakref class MyClass: def __init__(self): app_interface = omni.kit.app.get_app_interface() self._handle = app_interface.get_post_update_event_stream().create_subscription_to_pop( lambda event, obj=weakref.proxy(self): obj.on_event_callback(event) ) def __del__(self): self._handle.unsubscribe() self._handle = None def on_event_callback(self, event): # do something with the message In this revised code, the weak reference ``weakref.proxy(self)`` is used when registering the callback, allowing the ``MyClass`` object to be properly garbage collected. By following this pattern, you can prevent memory leaks and maintain a more efficient and stable simulation. Understanding the error logs from crashes ----------------------------------------- Many times the simulator crashes due to a bug in the implementation. This swamps the terminal with exceptions, some of which are coming from the python interpreter calling ``__del__()`` destructor of the simulation application. These typically look like the following: .. code:: bash ... [INFO]: Completed setting up the environment... Traceback (most recent call last): File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 166, in <module> main() File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 126, in main actions = pre_process_actions(delta_pose, gripper_command) File "source/standalone/workflows/robomimic/collect_demonstrations.py", line 57, in pre_process_actions return torch.concat([delta_pose, gripper_vel], dim=1) TypeError: expected Tensor as element 1 in argument 0, but got int Exception ignored in: <function _make_registry.<locals>._Registry.__del__ at 0x7f94ac097f80> Traceback (most recent call last): File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__ File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 98, in destroy TypeError: 'NoneType' object is not callable Exception ignored in: <function _make_registry.<locals>._Registry.__del__ at 0x7f94ac097f80> Traceback (most recent call last): File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 103, in __del__ File "../orbit/_isaac_sim/kit/extscore/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py", line 98, in destroy TypeError: 'NoneType' object is not callable Exception ignored in: <function SettingChangeSubscription.__del__ at 0x7fa2ea173e60> Traceback (most recent call last): File "../orbit/_isaac_sim/kit/kernel/py/omni/kit/app/_impl/__init__.py", line 114, in __del__ AttributeError: 'NoneType' object has no attribute 'get_settings' Exception ignored in: <function RegisteredActions.__del__ at 0x7f935f5cae60> Traceback (most recent call last): File "../orbit/_isaac_sim/extscache/omni.kit.viewport.menubar.lighting-104.0.7/omni/kit/viewport/menubar/lighting/actions.py", line 345, in __del__ File "../orbit/_isaac_sim/extscache/omni.kit.viewport.menubar.lighting-104.0.7/omni/kit/viewport/menubar/lighting/actions.py", line 350, in destroy TypeError: 'NoneType' object is not callable 2022-12-02 15:41:54 [18,514ms] [Warning] [carb.audio.context] 1 contexts were leaked ../orbit/_isaac_sim/python.sh: line 41: 414372 Segmentation fault (core dumped) $python_exe "$@" $args There was an error running python This is a known error with running standalone scripts with the Isaac Sim simulator. Please scroll above the exceptions thrown with ``registry`` to see the actual error log. In the above case, the actual error is: .. code:: bash Traceback (most recent call last): File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 166, in <module> main() File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 126, in main actions = pre_process_actions(delta_pose, gripper_command) File "source/standalone/workflows/robomimic/tools/collect_demonstrations.py", line 57, in pre_process_actions return torch.concat([delta_pose, gripper_vel], dim=1) TypeError: expected Tensor as element 1 in argument 0, but got int
NVIDIA-Omniverse/orbit/docs/source/refs/bibliography.rst
Bibliography ============ .. bibliography::
NVIDIA-Omniverse/orbit/docs/source/refs/license.rst
.. _license: License ======== NVIDIA Isaac Sim is available freely under `individual license <https://www.nvidia.com/en-us/omniverse/download/>`_. For more information about its license terms, please check `here <https://docs.omniverse.nvidia.com/app_isaacsim/common/NVIDIA_Omniverse_License_Agreement.html#software-support-supplement>`_. The license files for all its dependencies and included assets are available in its `documentation <https://docs.omniverse.nvidia.com/app_isaacsim/common/licenses.html>`_. Orbit framework is open-sourced under the `BSD-3-Clause license <https://opensource.org/licenses/BSD-3-Clause>`_. .. code-block:: text Copyright (c) 2022-2024, The ORBIT Project Developers. All rights reserved. SPDX-License-Identifier: BSD-3-Clause Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
NVIDIA-Omniverse/orbit/docs/source/refs/contributing.rst
Contribution Guidelines ======================= We wholeheartedly welcome contributions to the project to make the framework more mature and useful for everyone. These may happen in forms of: * Bug reports: Please report any bugs you find in the `issue tracker <https://github.com/NVIDIA-Omniverse/orbit/issues>`__. * Feature requests: Please suggest new features you would like to see in the `discussions <https://github.com/NVIDIA-Omniverse/Orbit/discussions>`__. * Code contributions: Please submit a `pull request <https://github.com/NVIDIA-Omniverse/orbit/pulls>`__. * Bug fixes * New features * Documentation improvements * Tutorials and tutorial improvements .. attention:: We prefer GitHub `discussions <https://github.com/NVIDIA-Omniverse/Orbit/discussions>`_ for discussing ideas, asking questions, conversations and requests for new features. Please use the `issue tracker <https://github.com/NVIDIA-Omniverse/orbit/issues>`_ only to track executable pieces of work with a definite scope and a clear deliverable. These can be fixing bugs, new features, or general updates. Contributing Code ----------------- We use `GitHub <https://github.com/NVIDIA-Omniverse/orbit>`__ for code hosting. Please follow the following steps to contribute code: 1. Create an issue in the `issue tracker <https://github.com/NVIDIA-Omniverse/orbit/issues>`__ to discuss the changes or additions you would like to make. This helps us to avoid duplicate work and to make sure that the changes are aligned with the roadmap of the project. 2. Fork the repository. 3. Create a new branch for your changes. 4. Make your changes and commit them. 5. Push your changes to your fork. 6. Submit a pull request to the `main branch <https://github.com/NVIDIA-Omniverse/orbit/compare>`__. 7. Ensure all the checks on the pull request template are performed. After sending a pull request, the maintainers will review your code and provide feedback. Please ensure that your code is well-formatted, documented and passes all the tests. .. tip:: It is important to keep the pull request as small as possible. This makes it easier for the maintainers to review your code. If you are making multiple changes, please send multiple pull requests. Large pull requests are difficult to review and may take a long time to merge. Coding Style ------------ We follow the `Google Style Guides <https://google.github.io/styleguide/pyguide.html>`__ for the codebase. For Python code, the PEP guidelines are followed. Most important ones are `PEP-8 <https://www.python.org/dev/peps/pep-0008/>`__ for code comments and layout, `PEP-484 <http://www.python.org/dev/peps/pep-0484>`__ and `PEP-585 <https://www.python.org/dev/peps/pep-0585/>`__ for type-hinting. For documentation, we adopt the `Google Style Guide <https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html>`__ for docstrings. We use `Sphinx <https://www.sphinx-doc.org/en/master/>`__ for generating the documentation. Please make sure that your code is well-documented and follows the guidelines. Circular Imports ^^^^^^^^^^^^^^^^ Circular imports happen when two modules import each other, which is a common issue in Python. You can prevent circular imports by adhering to the best practices outlined in this `StackOverflow post <https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python>`__. In general, it is essential to avoid circular imports as they can lead to unpredictable behavior. However, in our codebase, we encounter circular imports at a sub-package level. This situation arises due to our specific code structure. We organize classes or functions and their corresponding configuration objects into separate files. This separation enhances code readability and maintainability. Nevertheless, it can result in circular imports because, in many configuration objects, we specify classes or functions as default values using the attributes ``class_type`` and ``func`` respectively. To address circular imports, we leverage the `typing.TYPE_CHECKING <https://docs.python.org/3/library/typing.html#typing.TYPE_CHECKING>`_ variable. This special variable is evaluated only during type-checking, allowing us to import classes or functions in the configuration objects without triggering circular imports. It is important to note that this is the sole instance within our codebase where circular imports are used and are acceptable. In all other scenarios, we adhere to best practices and recommend that you do the same. Type-hinting ^^^^^^^^^^^^ To make the code more readable, we use `type hints <https://docs.python.org/3/library/typing.html>`__ for all the functions and classes. This helps in understanding the code and makes it easier to maintain. Following this practice also helps in catching bugs early with static type checkers like `mypy <https://mypy.readthedocs.io/en/stable/>`__. To avoid duplication of efforts, we do not specify type hints for the arguments and return values in the docstrings. However, if your function or class is not self-explanatory, please add a docstring with the type hints. Tools ^^^^^ We use the following tools for maintaining code quality: * `pre-commit <https://pre-commit.com/>`__: Runs a list of formatters and linters over the codebase. * `black <https://black.readthedocs.io/en/stable/>`__: The uncompromising code formatter. * `flake8 <https://flake8.pycqa.org/en/latest/>`__: A wrapper around PyFlakes, pycodestyle and McCabe complexity checker. Please check `here <https://pre-commit.com/#install>`__ for instructions to set these up. To run over the entire repository, please execute the following command in the terminal: .. code:: bash ./orbit.sh --format # or "./orbit.sh -f" Contributing Documentation -------------------------- Contributing to the documentation is as easy as contributing to the codebase. All the source files for the documentation are located in the ``orbit/docs`` directory. The documentation is written in `reStructuredText <https://docutils.sourceforge.io/rst.html>`__ format. We use `Sphinx <https://www.sphinx-doc.org/en/master/>`__ with the `Book Theme <https://sphinx-book-theme.readthedocs.io/en/stable/>`__ for maintaining the documentation. Sending a pull request for the documentation is the same as sending a pull request for the codebase. Please follow the steps mentioned in the `Contributing Code`_ section. .. caution:: To build the documentation, we recommend creating a `virtual environment <https://docs.python.org/3/library/venv.html>`__ to install the dependencies. This can also be a `conda environment <https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html>`__. To build the documentation, run the following command in the terminal which installs the required python packages and builds the documentation using the ``docs/Makefile``: .. code:: bash ./orbit.sh --docs # or "./orbit.sh -d" The documentation is generated in the ``docs/_build`` directory. To view the documentation, open the ``index.html`` file in the ``html`` directory. This can be done by running the following command in the terminal: .. code:: bash xdg-open docs/_build/html/index.html .. hint:: The ``xdg-open`` command is used to open the ``index.html`` file in the default browser. If you are using a different operating system, you can use the appropriate command to open the file in the browser. To do a clean build, run the following command in the terminal: .. code:: bash rm -rf docs/_build && ./orbit.sh --docs Contributing assets ------------------- Currently, we host the assets for the extensions on `NVIDIA Nucleus Server <https://docs.omniverse.nvidia.com/nucleus/latest/index.html>`__. Nucleus is a cloud-based storage service that allows users to store and share large files. It is integrated with the `NVIDIA Omniverse Platform <https://developer.nvidia.com/omniverse>`__. Since all assets are hosted on Nucleus, we do not need to include them in the repository. However, we need to include the links to the assets in the documentation. The included assets are part of the `Isaac Sim Content <https://docs.omniverse.nvidia.com/isaacsim/latest/features/environment_setup/assets/usd_assets_overview.html>`__. To use this content, you need to download the files to a Nucleus server or create an **Isaac** Mount on a Nucleus server. Please check the `Isaac Sim documentation <https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_faq.html#assets-and-nucleus>`__ for more information on how to download the assets. .. attention:: We are currently working on a better way to contribute assets. We will update this section once we have a solution. In the meantime, please follow the steps mentioned below. To host your own assets, the current solution is: 1. Create a separate repository for the assets and add it over there 2. Make sure the assets are licensed for use and distribution 3. Include images of the assets in the README file of the repository 4. Send a pull request with a link to the repository We will then verify the assets, its licensing, and include the assets into the Nucleus server for hosting. In case you have any questions, please feel free to reach out to us through e-mail or by opening an issue in the repository. Maintaining a changelog ----------------------- Each extension maintains a changelog in the ``CHANGELOG.rst`` file in the ``docs`` directory. The file is written in `reStructuredText <https://docutils.sourceforge.io/rst.html>`__ format. It contains a curated, chronologically ordered list of notable changes for each version of the extension. The goal of this changelog is to help users and contributors see precisely what notable changes have been made between each release (or version) of the extension. This is a *MUST* for every extension. For updating the changelog, please follow the following guidelines: * Each version should have a section with the version number and the release date. * The version number is updated according to `Semantic Versioning <https://semver.org/>`__. The release date is the date on which the version is released. * Each version is divided into subsections based on the type of changes made. * ``Added``: For new features. * ``Changed``: For changes in existing functionality. * ``Deprecated``: For soon-to-be removed features. * ``Removed``: For now removed features. * ``Fixed``: For any bug fixes. * Each change is described in its corresponding sub-section with a bullet point. * The bullet points are written in the past tense and in imperative mode. For example, the following is a sample changelog: .. code:: rst Changelog --------- 0.1.0 (2021-02-01) ~~~~~~~~~~~~~~~~~~ Added ^^^^^ * Added a new feature. Changed ^^^^^^^ * Changed an existing feature. Deprecated ^^^^^^^^^^ * Deprecated an existing feature. Removed ^^^^^^^ * Removed an existing feature. Fixed ^^^^^ * Fixed a bug. 0.0.1 (2021-01-01) ~~~~~~~~~~~~~~~~~~ Added ^^^^^ * Added a new feature.
NVIDIA-Omniverse/PhysX/CONTRIBUTING.md
# Contributing to PhysX ## Did you find a bug? * Check in the GitHub [Issues](https://github.com/NVIDIA-Omniverse/PhysX/issues) if a report for your bug already exists. * If the bug has not been reported yet, open a new Issue. * Use a short and descriptive title which contains relevant keywords. * Write a clear description of the bug. * Document the environment including your operating system, compiler version, and hardware specifications. * Add code samples and executable test cases with instructions for reproducing the bug. ## Did you find an issue in the documentation? * Please create an [Issue](https://github.com/NVIDIA-Omniverse/PhysX/issues/) if you find a documentation issue. ## Did you write a bug fix? * Open a new [Pull Request](https://github.com/NVIDIA-Omniverse/PhysX/pulls) with your bug fix. * Write a description of the bug which is fixed by your patch or link to related Issues. * If your patch fixes for example Issue #33, write `Fixes #33`. * Explain your solution with a few words. ## Did you write a cosmetic patch? * Patches that are purely cosmetic will not be considered and associated Pull Requests will be closed. * Cosmetic are patches which do not improve stability, performance, functionality, etc. * Examples for cosmetic patches: code formatting, fixing whitespaces. ## Do you have a question? * Search the GitHub [Discussions](https://github.com/NVIDIA-Omniverse/PhysX/discussions/) for your question. * If nobody asked your question before, feel free to open a new discussion. * Once somebody shares a satisfying answer to your question, click "Mark as answer". * GitHub Issues should only be used for bug reports. * If you open an Issue with a question, we may convert it into a discussion. * You can also ask in the NVIDIA Omniverse #physics Discord Channel. Get an invite here: [https://discord.com/invite/XWQNJDNuaC](https://discord.com/invite/XWQNJDNuaC).
NVIDIA-Omniverse/PhysX/README.md
# NVIDIA PhysX Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NVIDIA CORPORATION nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## Introduction Welcome to the NVIDIA PhysX source code repository. This repository contains source releases of the PhysX, Flow, and Blast SDKs used in NVIDIA Omniverse. ## Documentation The user guide and API documentation are available on [GitHub Pages](https://nvidia-omniverse.github.io/PhysX). Please create an [Issue](https://github.com/NVIDIA-Omniverse/PhysX/issues/) if you find a documentation issue. ## Instructions Please see instructions specific to each of the libraries in the respective subfolder. ## Community-Maintained Build Configuration Fork Please see [the O3DE Fork](https://github.com/o3de/PhysX) for community-maintained additional build configurations. ## Support * Please use GitHub [Discussions](https://github.com/NVIDIA-Omniverse/PhysX/discussions/) for questions and comments. * GitHub [Issues](https://github.com/NVIDIA-Omniverse/PhysX/issues) should only be used for bug reports or documentation issues. * You can also ask questions in the NVIDIA Omniverse #physics [Discord Channel](https://discord.com/invite/XWQNJDNuaC).
NVIDIA-Omniverse/PhysX/LICENSE.md
BSD 3-Clause License Copyright (c) 2023, NVIDIA Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NVIDIA CORPORATION nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
NVIDIA-Omniverse/PhysX/physx/version.txt
5.3.1.e9cf8e18b
NVIDIA-Omniverse/PhysX/physx/CHANGELOG.md
# v5.3.1-105.1 ## General ### Changed * PxgDynamicsMemoryConfig::tempBufferCapacity will now be interpreted as a user-provided initial size, and will resize automatically if more memory is needed. ### Fixed * A bug that led to phantom collisions for convex-heightfield interactions on GPU has been fixed. * A bug that caused velocity and impulse updates of the GPU articulation solver (PGS and TGS) not to be propagated to subsequent iterations, causing slower convergence and potentially unstable collision responses between rigids and articulations. * Fixed binary serialization for GPU enabled triangle meshes and meshes with SDF support. * Several bugs with GPU aggregates have been fixed that could have led to missed and phantom collisions. The issues were mostly related to additions/removals of aggregate contents. * Gpu accelerated SDF cooking is now deterministic. * SDF snippet shows how to optionally store cooked data into files. * Small improvements to SDF collisions, especially when objects with wildly different size collide. * Creating objects from a PxInputData containing invalid data could lead to a confusing (and incorrect) error message about a "double deletion". This has been fixed. * Bugs in island management related to actors other than rigid bodies. * A bug that could lead to a crash when calling the PxTetMaker::validateTriangleMesh function with a mesh referencing more vertices than passed into the function. That defect is now reported as eTRIANGLE_INDEX_OUT_OF_RANGE. * A crash bug that appeared when releasing actors with externally-provided forces and torques has been fixed. [Issue #211](https://github.com/NVIDIA-Omniverse/PhysX/issues/211) * A bug that caused a memory corruption in the GPU solver when using D6 joints with rigid bodies and articulations has been fixed. ## Rigid Body ### Added * The extraction of an isosurface from a SDF can now use multiple CPU cores. ### Fixed * A crash happening when using contact report thresholds with point-friction (PxFrictionType::eONE_DIRECTIONAL / PxFrictionType::eTWO_DIRECTIONAL) has been fixed. * A "fear of the wireframe" issue in Sphere vs TriangleMesh collision when simulating on GPU is fixed. ## Articulations ### Fixed * Articulation joint velocity limits are respected when articulation joint drives are configured to push past the limit. * Spherical articulation joints could sometimes flip their position by 2 pi causing problems with joint limits. This has been fixed. ## Joints ### Fixed * The PxConstraintFlag::eENABLE_EXTENDED_LIMITS flag now works properly for D6 based revolute joints when the GPU pipeline with the TGS solver is active. ## Character controller ### Fixed * You can now only create one PxCreateControllerManager per PxScene. This avoids filtering-related issues when multiple controller managers are created for the same PxScene. ## Particles ### Added * PxParticleSystem::getParticleMaterials() to query materials that have been registered with phases. ### Fixed * PxParticleSystem::getNbParticleMaterials() always returned 1, instead of the materials referenced by phases. * Particle - Convex Shape collisions failing with spread out particles. * Particle phase references to PxPBDMaterial were broken when releasing (an unreferenced) PxPBDMaterial. ## Pvd ### Added * A way to get a thread safe OmniPvd writer from the PxOmniPvd interface through using acquireExclusiveWriterAccess() and releaseExclusiveWriterAccess(). ### Fixed * OmniPVD no longer breaks when running and recording multiple scenes in parallel. * Corrected mirroring of the inbountJoinDOF attribute of PxArticulationLink ## Extensions ### Fixed * A bug in custom cone/cylinder collision with triangle meshes. There was a gap between a cone/cylinder and a mesh, noticeable for centimeter-scale shapes. Note that the last position argument of e.g.: PxCustomGeometryExt::CylinderCallbacks::useSubstituteGeometry was removed from the API. # v5.3.0-105.1 ## Supported Platforms ### Runtime * Linux (tested on Ubuntu 20.04) * Microsoft Windows 10 or later (GPU acceleration: display driver and GPU supporting CUDA 11 / CUDA ARCH 3.0) ### Development * Microsoft Windows 10 or later * Microsoft Visual Studio 2017, 2019, 2022 ## General ### Changed * The method PxLineStripSkinning::evaluateInterpolatedVertices changed the transform argument from `PxReal*` to ` PxMat44*` to be more explicit about the underlying data that is expected. * The apply* and copy* functions in PxScene changed their event arguments from `void*` to `CUevent` to fix misunderstandings about the type of those arguments. This also fixes a bug where pointers to events where passed but not dereferenced when recording/awaiting them. * The TGS solver on CPU and GPU now computes the number of position and velocity iteration according to the requested numbers by the actors in each island, matching the behavior of the PGS solver. Previously TGS velocity iterations in excess of 4 were silently converted to position iterations. To preserve the old behavior any actor requesting more than 4 velocity iterations should convert excess velocity iteration counts to position iteration counts, e.g., formerly 10 position and 10 velocity iterations should become 16 position and 4 velocity iterations. * The `acquire()` and `release()` functions in `PxCudaContextManager` that manage the PhysX CUDA context now use push/pop semantics. This fixes bug that led to a wrong context being bound after `release()` when sharing an existing CUDA context with PhysX. * Calling `setCMassLocalPose()` on a rigid body when using the direct-GPU API is now allowed. Note that calling `updateArticulationsKinematic()` after updating CMassLocalPose but before the next call to `simulate()` will still use the old CMassLocalPose. ### Fixed * A memory leak has been fixed in the actor pairs management code. * A race condition was fixed that led to nondeterministic contact reports in some scenarios. * Fix FEM cloth attachment filtering bug * Fix FEM narrow phase collision crash * Sphere-Trianglemesh collision bug is fixed * A bug that led to aggregated shapes being processed as part of the regular broadphase when changing transforms using the direct-GPU API has been fixed. * A bug that led to missed collisions and phantom collisions when changing transforms using the direct-GPU API has been fixed. * A bug that led to incorrect and nondeterministic behaviour for convex-trianglemesh, convex-heightfield, sphere-trianglemesh, capsule-trianglemesh, sphere-heightfield and capsule-heightfield collisions on GPU has been fixed. * A bug that led to contact target velocities spilling over from one contact to other contacts in the same solver batch. * A bug that led to incorrect and nondeterministic behaviour for trianglemesh-trianglemesh collisions on GPU has been fixed. * A bug that led to incorrect materials being used for convex-convex collisions on GPU has been fixed. ### Removed * Context creation for CUDA/Graphics interoperability has been deprecated. interopMode has been removed from PxCudaContextManagerDesc. * PxSceneFlag::eFORCE_READBACK has been removed. There is no replacement. * PxSceneFlag::eSUPPRESS_READBACK was deprecated and has been removed. Use PxSceneFlag::eENABLE_DIRECT_GPU_API instead. ## Rigid Body ### Added * Possibility to use the GPU to cook an SDF making the process a lot faster. * Option to launch CUDA kernels synchronously when creating the CUDA Context Manager. This option is required to accurately determine the correct kernel that returns a CUDA error. ### Fixed * The torsional patch radius parameter (see PxShape::setTorsionalPatchRadius()) was potentially ignored when running the simulation on GPU. * Potential race condition related to activating/deactivating trigger pairs. * A small misalignment of SDFs with the triangle mesh. * A small error in the gradient calculation of SDFs. * A sphere could tunnel through the edge between two triangles in a triangle mesh. * Race condition in SDF computation cuda kernel is fixed. * Fixed invalid access problem when selecting the SDF contact handler. ### Deprecated * PxFrictionType::eONE_DIRECTIONAL has been deprecated and will be removed in the future. Please use ePATCH or eTWO_DIRECTIONAL instead. ## Articulations ### Changed * `PxScene::copyArticulationData()` and `PxScene::applyArticulationData()` do not allow reading write-only and writing read-only data anymore. Read/write properties are specified in the API doc of `PxArticulationGpuDataType`. ### Fixed * A bug that led to wrong joint targets being set when using the direct-GPU API has been fixed. * A bug that led to link constraint-force-mixing scale not being included in collision constraints when using GPU dynamics has been fixed. * Articulation drive did not produce the same force magnitude for drives with velocity biases that were equally positive and negative. This was true of the CPU and GPU solver pipelines. This has been fixed. * Articulation drive produced unphysically large forces when run in combination with PxSolverType::eTGS and non-zero velocity iteration count. This was true of the CPU and GPU solver pipelines. This has been fixed by no longer updating joint drive force during velocity iterations with PxSolverType::eTGS. The expectation is that there are sufficient position iterations such that the drive force that accumulated over the position iterations is an accurate force. This avoids numerical discrepancies arising from the difference in effective simulation timestep employed by the position and velocity iterations. This discrepancy was particularly acute with a large number of velocity iterations. * Articulation drive suffered from an unphysical damping term with all combinations of PxSolverType::eTGS/PxSolverType::ePGS/PxSceneFlag::eENABLE_GPU_DYNAMICS. This has been fixed. * Potential crashes due to reading uninitialized memory were fixed. * The function PxArticulationReducedCoordinate::setMaxCOMAngularVelocity() had no effect if called after the 1st sim step with PxSceneFlag::eENABLE_GPU_DYNAMICS raised. This has been fixed. * The function PxArticulationReducedCoordinate::setMaxCOMLinearVelocity() had no effect if called after the 1st sim step with PxSceneFlag::eENABLE_GPU_DYNAMICS raised. This has been fixed. * Raising or lowering PxArticulationFlag::eFIX_BASE had no effect if modified after the 1st sim step with PxSceneFlag::eENABLE_GPU_DYNAMICS raised. This has been fixed. * The root link acceleration was reported as {0} even when the root link was not fixed. This affected GPU only. The fix has been applied to PxArticulationReducedCoordinate::copyInternalStateToCache(), PxArticulationReducedCoordinate::getLinkAcceleration() and PxScene::copyArticulationData(). * Only half the expected friction force was applied in certain scenarios when using PxSolverType::eTGS, PxFrictionType::ePATCH, PxMaterialFlag::eIMPROVED_PATCH_FRICTION and running on CPU. ### Deprecated * The functions PxArticulationReducedCoordinate::setMaxCOMLinearVelocity(), PxArticulationReducedCoordinate::getMaxCOMLinearVelocity(), PxArticulationReducedCoordinate::setMaxCOMAngularVelocity(), PxArticulationReducedCoordinate::getMaxCOMAngularVelocity() have all been marked as deprecated and will be removed in a future release. ## Joints ### Deprecated * Px1DConstraintFlag::eDRIVE_ROW has been marked as deprecated and will be removed in a later release. It has been renamed to Px1DConstraintFlag::eDEPRECATED_DRIVE_ROW to signal the intention to remove this flag in a later release. ## Vehicles2 ### Added * A new snippet that shows an example of using a custom tire model has been added (see SnippetVehicle2CustomTire). ### Changed * The snippet SnippetVehicle2Customization has been renamed to SnippetVehicle2CustomSuspension. * PxVehicleCommandNonLinearResponseParams::nbSpeedRenponsesPerCommandValue was misspelled and now renamed to nbSpeedResponsesPerCommandValue. * More parameters get recorded by OmniPVD. As a consequence, PxVehiclePVDComponent and some other PVD related vehicle APIs changed. * It is now legal to set entries in PxVehicleTankDriveDifferentialParams::nbWheelsPerTrack to 0 or 1. * The APIs of some methods use more specific input parameters now to decrease dependency on certain data structures. See the migration guide for more details. This applies to the methods: PxVehicleTireDirsUpdate(), PxVehicleTireCamberAnglesUpdate() and PxVehicleTireGripUpdate(). ### Fixed * Nonlinear command responses were broken for negative steer command values. Now they are treated symmetrically as intended. * PxVehiclePhysXActorDestroy() triggered a warning if the articulation link was not a leaf link. ### Removed * PxVehicleTankDriveDifferentialParams::nbWheelsInTracks has been removed. The entries in ::nbWheelsPerTrack can be summed up to compute that value instead. ## Cooking ### Added * PxTriangleMeshCookingResult::eEMPTY_MESH has been added. This cooking result is output when the mesh cleaning process removes all the triangles of a mesh. * PxCookingParams::meshAreaMinLimit has been added. This is used in the mesh cleaning process to remove triangles whose area is too small. * PxCookingParams::meshEdgeLengthMaxLimit has been added. ### Changed * The requirements for convex meshes being GPU compatible have been tightened. Overly oblong meshes are now rejected by the cooking with an error message. Collision detection will fall back to CPU for these meshes. ### Fixed * Fixed out of memory crash when cooking a convex hull of a very high resolution mesh. ## Soft Body ### Added * Support for voxel meshes with 5 tetrahedra per voxel to counteract anisotropy in the mesh. ### Changed: * Defaults of PxConeLimitedConstraint::mLowLimit, mHighLimit have been changed to -1.0 indicating no limit. * Soft body sleep damping is improved to minimize an effect that looks like a soft body would lower its stiffness before it goes to sleep. ### Fixed * Overflow of the soft body contact buffer will result in a warning. ## Extensions ### Added * CCD support for PxCustomGeometryExt::CylinderCallbacks and PxCustomGeometryExt::ConeCallbacks. ### Changed * PxCustomGeometryExt::CylinderCallbacks and PxCustomGeometryExt::ConeCallbacks classes have their public member variables (height, radius, axis and margin) replaced with setter and getter member functions. ## Pvd ### Fixed * Better coverage in OVD of attribute mirroring for : PxActor, PxRigidActor, PxRigidBody, PxRigidStatic and PxRigidDynamic, specifically for initial values, user set functions and post simulation updates. # v5.2.0 & v5.2.1 ## Supported Platforms ### Runtime * Linux (tested on Ubuntu 20.04) * Microsoft Windows 10 or later (GPU acceleration: display driver and GPU supporting CUDA 11 / CUDA ARCH 3.0) ### Development * Microsoft Windows 10 or later * Microsoft Visual Studio 2017, 2019, 2022 ## General * PhysX GPU binaries built with CUDA toolkit 11.8. * Added compute capability 8.9 (Ada) and 9.0 (Hopper) * Removed compute capability 5.0 (Maxwell) * Enabled multi-threaded cuda kernel compilation ### Changed: * INVALID_FILTER_PAIR_INDEX has been moved out of the public API. It was incorrectly exposed to users. * The API for the filter callback changed slightly. The pairID parameter in PxSimulationFilterCallback::pairFound(), PxSimulationFilterCallback::pairLost() and PxSimulationFilterCallback::statusChange() is now a PxU64 instead of a PxU32. The filter callback will now be called from multiple threads. * Minimum required Windows OS version was changed from Windows XP to Windows 7 * Replaced all calls to `select` with calls to `poll` in the socket implementations * PxSceneFlag::eENABLE_DIRECT_GPU_API and its predecessor PxSceneFlag::eSUPPRESS_READBACK are now immutable. * CmakeModules is no longer an external dependency. It's now included in PhysX source. ### Fixed * A bug that produced duplicate broadphase pairs and led to rapidly increasing GPU memory consumption was fixed. * An immediate mode bug has been fixed. It was happening in the contact generation code, using persistent contacts, and could produce jittering. * An indexing error was corrected that caused the CPU PGS solver with point friction to skip velocity and impulse writebacks in some scenarios. * A thread synchronization issue was addressed that may have caused nondeterministic behavior in the CPU PGS solver. * A crash that appeared when overflowing the maximum amount of aggregate pairs in the GPU broadphase has been fixed. * A bug that generated broadphase pairs for removed shapes has been fixed. * A crash that occurred when using excessively small contact buffers and/or patch buffers on the GPU. Now, contacts that don't fit into the buffer are dropped, and an error is reported. * A bug when running generate_projects.bat if one of the parent directories contain a space. ### Deprecated * PxSceneFlag::eFORCE_READBACK is deprecated. There is no replacement. * PxSceneFlag::eSUPPRESS_READBACK is deprecated. The replacement is PxSceneFlag::eENABLE_DIRECT_GPU_API. ### Removed * PxBVHStructure has been removed. Use PxBVH. * PxBVHStructureDesc has been removed. Use PxBVHDesc. * PxPhysics::getBVHStructures() has been removed. Use PxPhysics::getBVHs() * PxGetAssertHandler() and PxSetAssertHandler() have been removed. * PxMassModificationProps has been removed. Use PxConstraintInvMassScale instead. * PxRegisterImmediateArticulations, PxRegisterArticulationsReducedCoordinate, PxRegisterHeightFields, PxCreateBasePhysics have been removed. Articulations and heightfields are now always enabled. * PxBuffer has been removed. There is no replacement. The soft body interface now exposes direct access to GPU buffers. * GpuExtension library has been removed. * The deprecated PxPhysicsInsertionCallback has been removed. Please use PxInsertionCallback instead. * The deprecated PxTaskType::Enum entries TT_CPU, TT_NOT_PRESENT and TT_COMPLETED have been removed. These entries were replaced with eCPU, eNOT_PRESENT and eCOMPLETED. * These deprecated immediate-mode types have been removed: PxFeatherstoneArticulationJointData, PxFeatherstoneArticulationLinkData, PxFeatherstoneArticulationData, PxMutableLinkData, PxLinkData. * The deprecated PxPhysics::createBVHStructure() and PxPhysics::getNbBVHStructures() functions have been removed. * A deprecated PxPhysics::createAggregate() function has been removed. * Deprecated passthrough functions in PxShape such as `getGeometryType()` and the specialized `get<geomType>Geometry()` were removed. Calls to these functions should be replaced by the accessing the underlying geometry directly with `getGeometry()`. * Context creation for CUDA/Graphics interoperability has been deprecated. interopMode has been removed from PxCudaContextManagerDesc. * No more Support for Microsoft Visual Studio 2013 and 2015. * All 32 bits presets are removed. ## Rigid Body ### Fixed * A crash involving static or kinematic aggregates used in combination with PxPairFilteringMode::eKILL has been fixed. * PxRigidDynamicLockFlags (especially the linear lock flags) did not work properly with PGS. This has been fixed. * A rare bug involving GPU aggregates, in which newly created actors could freely move through existing actors, has been fixed. * A crash with invalid setups, where multiple materials were set on a shape referencing a triangle mesh that had no per-triangle material indices, has been fixed. Additionally this invalid setup will now trigger an error message. * The convex-vs-mesh PCM contact generation is now more robust (CPU/GPU). Some jittering cases have been fixed. * The capsule-vs-mesh PCM contact generation is now more robust (GPU). Some jittering cases have been fixed. * A bug that produced jittering when contact modification was used has been fixed. It happened mainly for primitives-vs-mesh contacts, in cases where multiple contact patches were involved. * A bug in GPU box-box contact generation that caused memory overflows and nondeterministic behavior as a result. * A bug in the constraint solver that was using wrong indices to solve friction constraints. * A crash in the GPU broadphase with empty aggregates has been fixed. * Limited the maximum amount of memory that the SDF debug visualizer uses to avoid out-of-memory errors on high-resolution SDFs. * A sufficiently large number of contacts is now generated for a dynamic object with an SDF collider lying on a single, large static triangle represented by a triangle mesh collider. * Improved robustness to imperfect input when cooking SDFs; for example, duplicate triangles with opposite winding now produce a correct SDF. * Fixed a rare case where the SDF contact generation algorithm could get stuck on SDF singularities and produce incorrect contacts. * Resolved a crash that occurred when a sphere primitive collider comes into contact with an SDF collider. ## Articulations ### Added * A new feature that computes and reports the force applied by a joint to a child link has been added. The reported force is in the joint's child frame. A more detailed specification of the reported force may be found in the doxy for the newly added array PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCES. The force may be queried on CPU using the newly added flag PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCES in conjunction with the newly added array PxArticulationCache::linkIncomingJointForce and the pre-existing function PxArticulationReducedCoordinate::copyInternalStateToCache(). The equivalent with the direct GPU API is to use the newly added enumeration PxArticulationGpuDataType::eLINK_INCOMING_JOINT_FORCE in conjunction with the pre-existing function PxScene::copyArticulationData(). ### Fixed * A rare bug involving articulations in aggregates has been fixed. An internal counter was not correctly updated, and could lead to internal asserts and potential crashes. * Setting root link transforms or joint positions with the PxScene GPU API could result in incorrect collision behavior if an articulation contained links with no shapes. * Incorrect values for link acceleration were reported with PxSceneFlag::eENABLE_GPU_DYNAMICS raised and lowered and with PxSceneFlag::eSUPPRESS_READBACK raised and lowered. This affected PxArticulationReducedCoordinate::getLinkAcceleration(), PxArticulationCache::linkAcceleration and PxScene::copyArticulationData(). This bug has been fixed. * Incorrect values for joint acceleration were reported when PxSceneFlag::eENABLE_GPU_DYNAMICS was raised. This affected PxArticulationGpuDataType::eJOINT_ACCELERATION/PxScene::copyArticulationData() with PxSceneFlag::eSUPPRESS_READBACK raised and PxArticulationCacheFlag::eACCELERATION/PxArticulationReducedCoordinate::copyInternalStateToCache()/PxArticulationCache::jointAcceleration with PxSceneFlag::eSUPPRESS_READBACK lowered. This bug has been fixed. * Setting a target velocity on a modifiable contact of an articulation link was not working properly. This has been fixed. * A crash that appeared when adding an articulation was added and removed from a scene without running a sim step in-between has been fixed. * Articulation links with extremely large mass in excess of approximately 1e+7 mass units had a tendency to fall through the ground due to internal threshold guards. This affected all solver types running on CPU. This has been fixed. * A floating-point precision issue resulting in slower-than-expected moving prismatic joints under certain simulation conditions with the TGS solver on GPU has been fixed. ### Deprecated * PxArticulationSensor has been deprecated. Along with this, PxArticulationCache::sensorForces, PxArticulationCacheFlag::eSENSOR_FORCES, PxArticulationGpuDataType::eSENSOR_FORCE, and PxArticulationSensorFlag have also been deprecated. * PxArticulationCache::jointSolverForces has been deprecated. The replacement is PxArticulationCache::linkIncomingJointForces. Along with this, the PxArticulationFlag::eCOMPUTE_JOINT_FORCES is also deprecated. ### Removed * Deprecated PxArticulationJointReducedCoordinate::setLimit and PxArticulationJointReducedCoordinate::getLimit were removed. Use PxArticulationJointReducedCoordinate::setLimitParams and PxArticulationJointReducedCoordinate::getLimitParams instead. * Deprecated PxArticulationJointReducedCoordinate::setDrive and PxArticulationJointReducedCoordinate::getDrive were removed. Use PxArticulationJointReducedCoordinate::setDriveParams and PxArticulationJointReducedCoordinate::getDriveParams instead. ### Changed * Debug visualization of articulation links (body mass axes) will now show their sleeping state (similar to rigid bodies). ## Joints ### Changed * The debug visualization color of active limits has changed from red to yellow. ### Removed * Joint projection has been removed. * The joint's "contact distance" parameter has been removed. The limits are now always active. ### Fixed * The D6 joint's twist drive was using the wrong actor's axis (B instead of A). This has been fixed, and it could affect joint setups in existing scenes. To fix this in existing content it might be enough to flip the joint frames of involved actors, but this may not be possible depending on which other features (joint limits, etc) have been setup for the same joint. In the worst case it might be necessary to re-tune these joints. * D6 joints configured to act as fixed joints (i.e. all motions locked) between static actors or world and a floating articulation base link did not constrain the rotational degrees of freedom. ### Deprecated * PxContactJoint, PxJacobianRow and PxContactJointCreate() have all been marked as deprecated and will be removed in a later release. ## Scene queries ### Removed * Deprecated PxBVH::raycast(), PxBVH::sweep() and PxBVH::overlap() functions have been removed. Use the new versions with callbacks. * A deprecated PxQueryFilterCallback::postFilter() function has been removed. Use the similar function with a different signature. * The deprecated PxGeometryQuery::getWorldBounds() function has been removed. Please use PxGeometryQuery::computeGeomBounds() instead. * A deprecated PxGeometryQuery::raycast() function has been removed. Please use the other function with the same name but a different signature. ### Fixed * Overlap queries could still return a non-zero number of hits when all hits got filtered in the post-filter callback (e.g. using PxQueryHitType::eNONE). This has been fixed. ### Added * PxScene::evaluateSDFDistances() to evaluate sdf distances and gradients at given sample points for a batch of shapes ## Cooking ### Removed * The deprecated PxCooking class has been removed. Use the standalone "immediate cooking" functions instead (e.g. PxCookBVH, PxCreateBVH...) * PxCooking::cookBVHStructure() has been removed. Use PxCooking::cookBVH() * PxCooking::createBVHStructure() has been removed. Use PxCooking::createBVH() ### Deprecated * PxConvexFlag::eGPU_COMPATIBLE has been deprecated. Set PxCookingParams::buildGPUData to true to cook convex meshes that need to be GPU compatible. ### Fixed * When convex hull cooking hit the polygon limit, the coplanar faces merge step was not run. ## Serialization ### Changed: * Version mismatch checks etc. when deserializing binary data are now applied in profile and release build configurations too. PxSerialization::createCollectionFromBinary() will return NULL if the checks fail and error messages will get sent. ### Fixed: * When deserializing materials (any PxBaseMaterial-derived), their userData member was wrongly re-initialized to zero, overwriting the serialized value. ## Pvd ### Changed: * The OmniPVD API has been reworked to be more consistent and provide less room for confusion. Among the various changes are: * The "Set" attribute type has been renamed to "UniqueList". As a consequence, the OmniPvdWriter methods registerSetAttribute, addToSetAttribute.., removeFromSetAttribute.. have been renamed to registerUniqueListAttribute, addToUniqueListAttribute, removeFromUniqueListAttribute. The enum values eOmniPvdRegisterSetAttribute, eOmniPvdAddToSetAttribute, eOmniPvdRemoveFromSetAttribute have been renamed to eREGISTER_UNIQUE_LIST_ATTRIBUTE, eADD_TO_UNIQUE_LIST_ATTRIBUTE, eREMOVE_FROM_UNIQUE_LIST_ATTRIBUTE. * OmniPvdCommandEnum has been renamed to OmniPvdCommand and all enum values have been renamed too. * OmniPvdDataTypeEnum has been renamed to OmniPvdDataType * OmniPvdAttributeDataType has been removed and its usage in the API methods replaced with OmniPvdDataType::Enum * The OmniPvdWriter methods setAttributeShallow, addToSetAttributeShallow, removeFromSetAttributeShallow have been renamed to setAttribute, addToUniqueListAttribute, removeFromUniqueListAttribute and can be dinstinguished from the more generic versions with the same name by the argument list. * The order of the handleDepth and attributeHandles params has flipped in the OmniPvdWriter methods setAttribute, addToUniqueListAttribute, removeFromUniqueListAttribute (formerly called addToSetAttribute, removeFromSetAttribute) methods. * The order of the enumClassHandle and attributeName parameters has flipped in the OmniPvdWriter::registerFlagsAttribute() method. * OmniPvdReader::getCommandType() has been removed. The information is already available as part of the OmniPvdReader::getNextCommand() method. * The parameters in OmniPvdReader::startReading() have turned from pointers to references. * The stream parameters in OmniPvdWriter::setWriteStream() and OmniPvdReader::setReadStream() have turned from pointers to references. * The input parameters for the following functions have turned from pointers to references: destroyOmniPvdReaderFp, destroyOmniPvdWriterFp, destroyOmniPvdFileReadStreamFp, destroyOmniPvdFileWriteStreamFp, destroyOmniPvdMemoryStreamFp * Various input parameters in the methods of OmniPvdWriter, OmniPvdReadStream, OmniPvdWriteStream have changed from const to non-const. * The returned data pointers of the methods getClassName(), getAttributeName(), getObjectName(), getAttributeDataPointer() of OmniPvdReader are now const. * The OmniPVD snippet now aborts in release build configuration since PVD is not available in release. * Unit tests can now export single or series of automatically time stamped files, when the omnipvdfile command line parameter is set to a directory * Crash bugs in the contact reports fixed * OmniPVD now uses the OmniPVD API derived class support to stream debug data * Removes attribute duplication for shared base classes * Removed ambiguity about which class a certain object is part of * No need to have a class type attribute in streamed debug objects, the class is the type * As a consequece greatly simplifies object and class handling in the OmniPVD extension ## Vehicles2 ### Fixed: * When using sweeps for vehicle wheel vs. ground collision detection, PxVehiclePhysXRoadGeometryQueryUpdate() wrongly treated the case of an exactly zero hit distance (wheel touching ground with suspension being exactly at max compression) as no hit. * Undesired sleep/wake cycle for vehicles that are not moving while engines are revving. Applying throttle will keep vehicles awake now. * Negative suspension jounce (and an assert) could result in certain scenarios where PxVehicleSuspensionStateCalculationParams::limitSuspensionExpansionVelocity was set to true and gravity was pointing in the opposite direction of the suspension travel direction. * Various PVD related bugs. * If the wheel IDs in PxVehicleAxleDescription::wheelIdsInAxleOrder were shuffled, the wrong road geometry velocity information was used to compute the tire slip speeds. * When driving backwards, the thresholdForwardSpeedForWheelAngleIntegration parameter (see PxVehicleSimulationContext) was ignored. ### Changed: * PxVehiclePhysXRoadGeometryQueryParams has been adjusted to allow for wheel specific filter data. As a consequence, the method PxVehiclePhysXRoadGeometryQueryUpdate() has been adjusted too. See the migration guide for more details. * Only the engine drivetrain or direct drivetrain properties are recorded in PVD now (and not both for the same vehicle). * All the methods in PxVehiclePvdFunctions.h and PxVehiclePvdHelpers.h have been adjusted to use references to OmniPvdWriter, PxVehiclePvdObjectHandles or PxVehiclePvdAttributeHandles objects instead of pointers to make it even clearer that these parameters are required. * The PxVehiclePvdAttributeHandles parameter of the PxVehiclePvdObjectRelease() method has been removed. * The PxVehiclePvdAttributeHandles and OmniPvdWriter parameter of the PxVehiclePvdObjectCreate() method have been removed. * The OmniPvdWriter parameter of the PxVehiclePvdAttributesRelease() method has been removed. ## Soft Body ### Added: * Kinematic soft body feature * PxSoftBodyFlag::eKINEMATIC and PxSoftBodyFlag::ePARTIALLY_KINEMATIC. * PxSoftBody::setKinematicTargetBufferD function to set kinematic targets based on a device buffer. * PxConfigureSoftBodyKinematicTarget function to prepare kinematic targets for PxSoftBody::setKinematicTargetBufferD. * PxSoftBodyExt::relaxSoftBodyMesh function to repose a tetrahedral mesh from one configuration into another. * Optional outputVertexToInputTriangle, removeDisconnectedPatches parameters for PxTetMaker::simplifyTriangleMesh. * PxTetrahedronMeshExt::createPointsToTetrahedronMap function to associate points to their closest tetrahedon. * A snippet that shows how to set up and use a kinematic soft body. * constraintOffset parameter to PxSoftBody::addSoftBodyAttachment and PxSoftBody::addClothAttachment to specify an offset of the PxConeLimitedConstraint with respect to the PxConeLimitedConstraint::mAxis. ### Removed: * PxBuffer has been removed. Writing and reading the softbody simulation state is now done directly in GPU buffers. For examples, see SnippetSoftBody. ### Deprecated: * PxSoftBodyExt::commit() has been deprecated. The replacement is PxSoftBodyExt::copyToDevice(). ### Changed: * Renamed PxFEMSoftBodyMaterialModel::CO_ROTATIONAL, NEO_HOOKEAN to PxFEMSoftBodyMaterialModel::eCO_ROTATIONAL, eNEO_HOOKEAN. * PxSoftBodyDataFlag has been renamed to PxSoftBodyGpuDataFlag. * Default constructor of PxConeLimitedConstraint initializes PxConeLimitedConstraint::mAngle to -1.0 since 0.0f now indicates a 0.0 cone opening angle. * Soft body flags used to copy stress computation were changed. The stress computation can now be performed via the intermediate data that can be copied from the internal buffers. ### Fixed: * A bug that resulted in changes to PxSoftBodyFlags not being picked up has been fixed. * Fixed a case where particles colliding with soft bodies could lead to a crash. * Fixed a corner case where the mass of an internal node could become negative. * An index bug when rendering tetrahedra in the snippets. ## Particles ### Changed: * Renamed PxParticleRigidAttachment::mParams to mConeLimitParams * Added PxParticleRigidAttachment constructor to initialize with PxConeLimitedConstraint and localPose0. * Added PxConeLimitParams constructor to initialize with PxConeLimitedConstraint. * Added PxParticleRigidFilterPair constructor to initialize with rigid node ID and particle ID. ### Fixed: * A crash when using a large number of particles has been fixed. * A bug that resulted in changes to PxParticleFlag not being picked up has been fixed. # v5.1.3 ## General ### Added: * Support for Microsoft Visual Studio 2022 for Windows builds. ### Fixed * Changing the materials of a shape did not work when using GPU dynamics. * Fixed exclusive shape binary serialization. ### Deprecated * RepX/Xml serialization has been deprecated. ## Rigid Body ### Fixed * A rare bug involving GPU aggregates, in which newly created actors could freely move through existing actors, has been fixed. ## Joints ### Fixed * The D6 joint's twist drive was using the wrong actor's axis (B instead of A). This has been fixed, and it could affect joint setups in existing scenes. To fix this in existing content it might be enough to flip the joint frames of involved actors, but this may not be possible depending on which other features (joint limits, etc) have been setup for the same joint. In the worst case it might be necessary to re-tune these joints. ## Soft Body ### Fixed * Rendering for tetmeshes in snippets had some tet faces inverted. This has been fixed. * The voxel tetmesher won't crash anymore when called with zero elements as input. * A bug in collision computation between a soft body and a scaled triangle mesh has been fixed. ## Particles ### Fixed * The Poisson Sampler will not cause number overflows and crashes anymore when called with parameters that lead to too many samples. * PxParticleClothCooker fixes to support shearing and bending constraints. This will change the behavior of newly cooked cloth assets. ## Pvd ### Fixed * Fixed a potential crash bug when contact points are recorded through OmniPVD. # v5.1.2 ## General ### Fixed: * Binary serialization of materials' userData. * Fixed precision issue in index computation in Gu::HeightField::computeCellCoordinates [Issue #52](https://github.com/NVIDIA-Omniverse/PhysX/issues/52) * Performance for SnippetCustomGeometry is now much better, particularly on Linux * Compiler errors on Linux - [Issue #25](https://github.com/NVIDIA-Omniverse/PhysX/issues/25) ## Cooking ### Fixed * A bug that generated non-GPU compatible convex meshes even though GPU compatibility was requested. # v5.1.1 ## General ### Changed: * Be aware that due to reorganization of some virtual functions in the public interface the binary data layout has changed from v5.1.0. Linking code that includes the headers of v5.1.1 against binaries that have been built with an older version will likely cause problems. ### Added: * Support for spatial and fixed tendon serialization. ### Fixed: * Binary serialization of articulations had a bug, which got fixed. * Includes [PR #8: Download bootstrap packages using TLS](https://github.com/NVIDIA-Omniverse/PhysX/pull/8/) ## Rigid Body ### Fixed * A crash when colliding an SDF mesh against a sphere ## Particle Systems ### Fixed * Particle systems now support is<> type conversion. ### Removed * The PxParticlePhase class has been removed. It was unused. ## Vehicles2 ### Changed: * SnippetVehicle2Multithreading is now using custom profiling code to provide timings in release builds too. # v5.1.0 ## Supported Platforms ### Runtime * Linux (tested on Ubuntu 20.04) * Microsoft Windows 10 or later (GPU acceleration: display driver and GPU supporting CUDA 11 / CUDA ARCH 3.0) ### Development * Microsoft Windows 10 or later * Microsoft Visual Studio 2017, 2019 ## Overview * New SDF collisions! * New custom geometry! * New custom scene query system! * New GJK queries API! * New soft bodies! * New mesh-vs-mesh overlap queries! * New Vehicle SDK with customizable components and functionality! * New gyroscopic forces! * New gear joint and rack-and-pinion joint! ## General ### Added: * A new function PxSetMutexProtocol() has been added exclusively for Linux OS. This function affects the way in which shdfnd::Mutex sets flags that affect OS strategies to avoid thread priority inversion. The behavior was hard-coded to PTHREAD_PRIO_INHERIT but now can be set to any of PTHREAD_PRIO_INHERIT, PTHREAD_PRIO_PROTECT, PTHREAD_PRIO_NONE. A choice of PTHREAD_PRIO_NONE can lead to significant performance improvements with large thread counts but requires care to avoid priority inversion, a phenomena that occurs when a low priority thread holds a lock contended by higher priority threads. * A flag PxVisualizationParameter::eSIMULATION_MESH has been added to render the simulation mesh instead of the collision mesh for tetmeshes. * A flag PxVisualizationParameter::eSDF has been added to render the SDF of a mesh instead of the collision mesh for triangle meshes with SDFs. * PxPhysics has new functions related to the creation and retrieval of tetrahedral meshes. ### Deprecated: * PxPhysicsInsertionCallback is deprecated. Please use PxInsertionCallback instead. * The PxFlags::set() function has been removed. Please now use PxFlags::raise() to set a single flag, or operator= to set all flags. * The enum values of PxTaskType have been renamed for consistency reasons. See the corresponding API documentation for details. * The PxRegisterHeightFields, PxRegisterArticulationsReducedCoordinate and PxCreateBasePhysics functions are deprecated. * Binary data conversion and binary meta data have been deprecated. * PxBinaryConverter * PxConverterReportMode * PxGetPhysicsBinaryMetaData() * PxSerialization::serializeCollectionToBinaryDeterministic() * PxSerialization::dumpBinaryMetaData() * PxSerialization::createBinaryConverter() * PxBinaryMetaDataCallback * PxSerializationRegistry::registerBinaryMetaDataCallback() ### Fixed: * PxPhysics::getFoundation() and PxScene::getPhysics() did not return the correct references in scenarios where two or more dynamic libraries are built with static PhysX libraries. In such a scenario, PxPhysics or PxScene objects from dynamic library A would return the wrong references when queried inside dynamic library B. * Collision edges (PxVisualizationParameter::eCOLLISION_EDGES) were not properly rendered when PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE is used. Using this flag means that all edges are active, but none of them were rendered. The correct thing to do is to render all of them. * PxActorFlag::eVISUALIZATION was not properly used. Shapes of actors whose visualization flag is disabled will now get skipped as well. * Removed duplicate closing cross-thread event for Basic.narrowPhase event. * Replaced all custom offsetof expressions that appear to dereference a null pointer with the PX_OFFSET_OF_RT macro - implementing Github PR 396. * Debug visualization of face normals was incorrect for triangle meshes with negative scales. This has been fixed. ### Removed: * Scene double buffering has been completely removed. This means it is now illegal to call API write commands that make changes to the scene or to any actor or shape in a scene while the scene is simulating; that is, in-between PxScene::simulate() and PxScene::fetchResults(). Examples include PxRigidDynamic::setLinearVelocity() and PxScene::addActor(). Another example is PxShape::setLocalPose() for any shape attached to an actor that is in a scene currently being simulated. Removal of scene double buffering has similar consequences for API read commands: it is now illegal to read any property that will be modified during a simulation step. Examples include PxRigidActor::getGlobalPose() and PxConstraint::getForce(). Split simulation is slightly less restrictive in that some reads are allowed during PxScene::collide() and some writes allowed after PxScene::fetchCollision() but before PxScene::advance(). Examples include PxRigidActor::getWorldBounds() and PxArticulation::setWakeCounter(). However, it is important to note that the rules that apply to PxScene::simulate() apply equally to PxScene::advance(). In all build configs, any corresponding illegal API read or write will result in an error being issued to PxErrorStream and the illegal API call immediately returning without executing the function. A final comment is that API read operations in event callbacks remain legal. * PxVisualizationParameter::eDEPRECATED_COLLISION_PAIRS has been removed. * PxBroadPhaseCaps::maxNbObjects has been removed. It was unused. * PxSceneFlag::eADAPTIVE_FORCE has been removed. * The semi-advanced PhysX "Samples" are no longer provided. The "Snippets" continue to provide simple example code to illustrate how to use certain PhysX features. The physics demos in NVIDIA Omniverse offer more advanced samples now. * The deprecated PxScene::setFrictionType() method has been removed. Simply set the desired friction type in PxSceneDesc. ### Changed: * The Foundation types PxVec2, PxVec3, PxVec4, PxQuat, PxMat33, PxMat34, PxMat44 and PxTransform now have higher-accuracy implementations that use double instead of float. These are not currently used directly in the PhysX SDK but can be used by clients of the SDK if needed. * The previous snippet SnippetRaycastCCD has been replaced with SnippetCCD. This snippet illustrates how to use different types of CCD methods, including regular, raycast and speculative CCD. * PxDefaultCpuDispatcherCreate() has been modified to support different strategies to combat wasteful thread usage when there is no work to perform. * The PxSimulationEventCallback functions onTrigger(), onContact() and onConstraintBreak() have slightly different behavior in that api queries to the physx actors referenced by the callbacks now return the state of the actor after the simulate step rather than the state of the actor at the detection event. At the risk of a performance penalty, the flags PxPairFlag::ePRE_SOLVER_VELOCITY and PxPairFlag::eCONTACT_EVENT_POSE may be used to retrieve the poses and velocities of the actors prior to the simulation step in the implemented onContact() function. These poses and velocities represent the state of the actors when the contact was first detected during the simulation step. * PxCapsuleGeometry with halfHeight=0.0 are now legal. * PxNodeIndex is now a 64-bit index, with the upper 32-bits representing the rigid body/actor ID and the lower 31-bits representing the articulation link ID and 1 bit to indicate if this is an articulation link or a rigid body. However, due to GPU memory constraints, an articulation can only support a maximum of 65536 links. * Various PxScene::addXXX() functions now return a bool status (previously void) to detect errors more easily. * TGS solver is now the default, PGS can still be used by setting the scene flags accordingly. * The PxScene::addActor(), ::addActors(), ::addAggregate(), addCollection(), ::resetFiltering(), ::simulate(), ::advance(), ::collide() methods now return a boolean to denote success or failure. * Several immediate-mode structs have been renamed from FeatherStoneArticulation to ArticulationRC (the last letters are an acronym for reduced-coordinate) ## Rigid body ### Added: * A new flag PxConstraintFlag::eALWAYS_UPDATE has been added for constraints that should always be updated, i.e. the corresponding PxConstraintConnector::prepareData() function is called each frame automatically. * A new flag PxConstraintFlag::eDISABLE_CONSTRAINT has been added. The solver prep functions are not called when this flag is set, effectively disabling the constraint. * A userData parameter has been added to PxAggregate. * A userData parameter has been added to PxConstraint. * The PxPhysics::createAggregate() function has a new parameter. A deprecated wrapper for the previous function signature has been added. * A new flag PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES has been added. This introduces gyroscopic forces to rigid bodies to simulate effects like the Dzhanibekov Effect. * A new class PxCustomGeometry has been added. User can now create custom collision shapes by implementing a set of callback functions. * Two pre-made custom geometry implementations added in PxCustomGeometryExt extension - Cylinder and Cone. * A new set of API functions PxGjkQuery have been added. This is intended for spatial queries on custom shapes represented by their GJK Support Mapping. * PxMeshGeometryFlag::eTIGHT_BOUNDS has been added. This is similar to PxConvexMeshGeometryFlag::eTIGHT_BOUNDS, but for triangle meshes. * A new broadphase has been added (PxBroadPhaseType::ePABP). * A standalone broadphase interface has been added (see PxCreateBroadPhase and PxCreateAABBManager). * A compliant contact model has been added. Users can now customize spring-stiffness and damping for a soft contact response. * Triangle mesh colliders are now supported on dynamic rigid bodies if a SDF (Signed Distance Field) gets generated during cooking. * PxSceneDesc::frictionCorrelationDistance allows to configure the distance for merging contact points into a single anchor point. * PxSceneDesc::contactPairSlabSize can be used to define the size of the contact pool slabs. ### Removed: * PxSceneDesc::solverOffsetSlop has been removed and can now be set per rigid body (see PxRigidBody::setContactSlopCoefficient()). ### Changed: * PxShape::getGeometry() now returns a PxGeometry reference instead of a PxGeometryHolder. See the migration guide to 5.1 for details. The PxShape::getGeometryType() and PxShape::getXXXGeometry() functions have been deprecated as a result. * PxMaterialFlag::eIMPROVED_PATCH_FRICTION is now enabled by default. * PxRigidBody::setLinearVelocity() was removed and replaced with PxRigidDynamic::setLinearVelocity() * PxRigidBody::setAngularVelocity() was removed and replaced with PxRigidDynamic::setAngularVelocity() * PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD and PxRigidBodyFlag::eENABLE_CCD can now be enabled at the same time on a given body. In this hybrid CCD mode the linear part of the motion is handled by sweeps, and the angular part of the motion is handled by speculative contacts. ### Fixed: * Removing a shape from a sleeping dynamic rigid actor woke the actor up if it was touching a shape of a static rigid actor. * Removing a shape from a dynamic rigid actor, did not necessarily wake up touching actors even though wakeOnLostTouch was set to true in PxRigidActor::detachShape(). * A performance problem in PxScene::getActors() has been fixed. * Missing support for maxContactForces in the TGS solver has been added. * A rare crash due to reading past the boundaries of a memory pool has been fixed. * Deformable meshes using the BVH34 midphase structure did not handle collision edge flags correctly. This has been fixed. * Collision edge flags were sometimes incorrect for negative-scaled meshes, giving birth to invalid or missed contacts. This has been fixed. * The sphere-vs-mesh PCM contact generation had a bug that sometimes made the sphere go through the mesh due to a missed vertex contact. This has been fixed. * Performance and stability issues when simulating convexes colliding against many triangles in complex PxTriangleMesh geometries has been improved. * Attempting to apply a force to a kinematic rigid body will no longer lead to a crash in profile or release builds. * Triangle mesh negative scale support for GPU code path. * Switching a constrained dynamic body to kinematic no longer triggers an assert in debug mode. ## Joints ### Added: * New PxGearJoint and PxRackAndPinionJoint have been added. ### Fixed: * PxJoint::setActors() had a bug when called at runtime, that left an internal structure referencing the previous actors. As a result PxConstraintFlag::eCOLLISION_ENABLED was not properly handled between jointed actors. ### Deprecated: * PxJointLimitParameters::contactDistance is deprecated. * Joint projection is deprecated. ## Scene queries ### Removed: * Batched query support has been removed from the PhysX SDK. The deprecated structs/classes/callbacks PxBatchQuery, PxBatchQueryDesc, PxBatchQueryResult, PxRaycastQueryResult, PxSweepQueryResult, PxOverlapQueryResult, PxBatchQueryPreFilterShader and PxBatchQueryPostFilterShader have all been removed from the SDK. The deprecated function PxScene::createBatchQuery has also been removed. In place of PxBatchQuery, a new class PxBatchQueryExt has been added to the extensions library. This acts as a wrapper for the functions PxScene::raycast(), PxScene::sweep() and PxScene::overlap() and aims to preserve the core functionality of PxBatchQuery. PxBatchQueryExt instances are instantiated with the function PxCreateBatchQueryExt(). ### Added: * PxSceneDesc can now take an optional PxSceneQuerySystem parameter. If defined, all PxScene scene-query related calls will be re-routed to this interface. This allows users to potentially customize the implementation of all scene-query operations. An external implementation of this interface is available in the PxExtensions library, and can be created with the PxCreateExternalSceneQuerySystem function. * It is possible to further customize the scene-query system, e.g. using more than the two built-in pruning structures in PhysX. See PxCreateCustomSceneQuerySystem and SnippetMultiPruners. * The function PxCreateBatchQueryExt() has been added to the extension library. The purpose of this function is to instantiate a new class PxBatchQueryExt. This class acts as a replacement for the PxBatchQuery class of previous releases which has now been removed. PxBatchQueryExt allows queries to be added to a queue and then executed on command. * The flag PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR has been added to support PxBatchQueryExt and/or any other user replacement for PxBatchQuery. When this flag is raised, the PhysX SDK ignores an internal filter equation and guarantees that the PxQueryHitType returned by the corresponding PxQueryFilterCallback instance is used directly without any other logic being applied. * The function PxBatchQueryStatus::getStatus() has been added to the extensions library to determine if an overflow occurred during the execution of a batch with PxBatchQueryExt::execute(). Overflows occur when the touch buffer is insufficiently large to return all touches for all queries. * The function PxScene::overlap() now has an optional PxQueryCache pointer as function argument. This follows the pattern of the complementary raycast() and sweep() functions of the PxScene class. * The function PxGeometryQuery::pointDistance() now supports meshes when the PxMeshMidPhase::eBVH34 data structure is used. It has a new parameter to return the closest triangle index for meshes. * SnippetPointDistanceQuery, SnippetGeometryQuery, SnippetStandaloneBVH and SnippetPathTracing have been added. * The PxScene::raycast(), PxScene::overlap() and PxScene::sweep() functions have a new PxGeometryQueryFlags parameter. * The PxGeometryQuery::raycast(), PxGeometryQuery::overlap(), PxGeometryQuery::sweep(), PxGeometryQuery::computePenetration(), PxGeometryQuery::pointDistance() functions have a new PxGeometryQueryFlags parameter. * The PxMeshQuery::findOverlapTriangleMesh(), PxMeshQuery::findOverlapHeightField() and PxMeshQuery::sweep() functions have a new PxGeometryQueryFlags parameter. * PxBVH now has a culling function (PxBVH::cull()) that can be used to implement view-frustum culling. See SnippetFrustumQuery for an example. * PxBVH now has refit functions (PxBVH::refit(), PxBVH::partialRefit()) that can be used for dynamic trees. See SnippetStandaloneBVH for an example. * PxBVH now has a generic traversal function (PxBVH::traverse()) that can be used for arbitrary purposes, like e.g. debug-visualizing the tree bounds. See SnippetStandaloneBVH for an example. * There is a new PxFindOverlap function to find overlaps between two PxBVH objects. * The PxRigidActorExt::createBVHFromActor() helper function has been added. * PxSceneDesc::dynamicTreeSecondaryPruner has been added. The new PxDynamicTreeSecondaryPruner enum lets users choose which implementation to use in dynamic trees. * PxSceneDesc::staticBVHBuildStrategy and PxSceneDesc::dynamicBVHBuildStrategy have been added. This lets users control the build strategy of the static & dynamic pruning structures. * PxSceneDesc::staticNbObjectsPerNode and PxSceneDesc::dynamicNbObjectsPerNode have been added. This lets users control the number of objects per node for the static & dynamic pruning structures. * PxHitFlag::eANY_HIT has been added. It is similar to the previous PxHitFlag::eMESH_ANY flag, but this time for any geometry that contains multiple primitives - for example a PxCustomGeometry. * PxGeometryQuery::raycast, PxGeometryQuery::overlap and PxGeometryQuery::sweep now take an optional context parameter that is passed to the low-level functions, and in particular to the PxCustomGeometry callbacks. * PxGeometryQuery::overlap now supports triangle mesh vs triangle mesh. * A new PxMeshQuery::findOverlapTriangleMesh function has been added to compute triangle overlaps between two triangle meshes. ### Fixed: * The build code for BVH34 trees had an issue that could produce degenerate trees, leading to rare performance problems and even stack overflow during traversal. This has been fixed, but it made the build code slightly slower, which could be a problem for users cooking at runtime. Since the problem was rare, the previous/faster build code has been kept, available in PxBVH34BuildStrategy::eFAST. It is not enabled by default. * The scene query system was sometimes incorrectly updated for PxBVH structures. This has been fixed. * A crash has been fixed when doing a query against an empty scene while using PxPruningStructureType::eNONE for the dynamic structure. * The BVH34 codepath had a bug in the raycast-vs-mesh-with-multiple-hits case, where returned hits could be further away than defined max hit distance. This has been fixed. * A rare crash involving the compound pruner and the PxActorFlag::eDISABLE_SIMULATION flag has been fixed. * Fixed a rare scene-query issue happening with stabilization enabled (the SQ structures could miss updates, leading to incorrect SQ results). * In rare cases, PxTriangleMesh::refitBVH() could return an incorrect bounding box when using PxMeshMidPhase::eBVH34. This has been fixed. * In very rare cases, sweep tests using the eMTD flag and exactly touching a shape (impact distance == 0) could return an incorrect impact normal. This has been fixed. * The capsule-vs-heightfield overlap query (PxGeometryQuery::overlap) was not reporting hits in some cases. This has been fixed. * The convex-vs-heightfield overlap query (PxGeometryQuery::overlap) had a bug when using scaled convexes. This has been fixed. * The sphere-vs-mesh and capsule-vs-mesh sweeps sometimes returned slightly incorrect impact distances (especially with long sweeps), which resulted in swept shapes penetrating the meshes when moved to the impact positions. This has been fixed. * In rare cases the sphere-vs-mesh and capsule-vs-mesh sweeps could miss triangles entirely. This has been fixed. ### Changed: * The PxQueryHit struct does not contain touched actor & shape pointers anymore. They have been moved higher up to the PxRaycastHit, PxOverlapHit and PxSweepHit structs. Explicit padding has also been dropped for these classes. * The PxQueryFilterCallback::postfilter() function has changed. The hit actor and hit shape are now passed as extra arguments to the function. * PxGeometryQuery::raycast() now operates on PxGeomRaycastHit structures and takes an extra stride parameter. Similarly PxGeometryQuery::sweep() now uses a PxGeomSweepHit structure. ### Deprecated: * PxGeometryQuery::getWorldBounds() has been deprecated. Please use PxGeometryQuery::computeGeomBounds() instead. * PxHitFlag::eMESH_ANY has been deprecated. Please use PxHitFlag::eANY_HIT instead. * PxBVHStructure has been renamed to PxBVH. PxBVHStructureDesc has been renamed to PxBVHDesc. * The PxBVHStructure scene query functions have changed. The old API is deprecated, a new API has been added. ## Character controller ### Added: * A PxClientID parameter has been added to PxControllerDesc, to let users setup the owner client before the kinematic actor is added to the scene. ### Fixed: * The vertical displacement vector in the down pass was sometimes incorrect (larger than it should have been). This has been fixed. * Releasing an articulation link while a character was standing on it produced a crash. This has been fixed. ## Vehicles2 ### Added: * The Vehicle SDK has been refactored into a completely new form to allow rapid customization and prototyping. SnippetVehicle2Customization, SnippetVehicle2DirectDrive, SnippetVehicle2FourWheelDrive etc. demonstrate use of the new Vehicle SDK. The public API for the new Vehicle SDK may be found under "physxRoot/include/vehicle2". All functions, structs and classes in the new Vehicle SDK are inside the physx::vehicle2 namespace. A migration guide may be found in the PhysX 5.1 SDK Guide under the subsection "Migrating From PhysX SDK 4.0 to 5.1/Vehicles". ## Vehicles ### Deprecated: * All structs, classes and functions of the old Vehicle SDK have been marked as deprecated and will be removed in a later release. ### Changed: * Concurrent calls to PxVehicleUpdateSingleVehicleAndStoreTelemetryData() are now permitted if the additional parameter vehicleConcurrentUpdates is used. * The functions PxVehicleSuspensionSweeps() and PxVehicleSuspensionRaycasts() have been modified to accommodate the removal of PxBatchQuery and the addition of PxBatchQueryExt. The arguments of both functions have been modified with a PxBatchQueryExt pointer directly replacing a PxBatchQuery pointer. New functionality in PxBachQueryExt has allowed PxRaycastQueryResult/PxSweepQueryResult to be removed from the argument list of PxVehicleSuspensionRaycasts()/PxVehicleSuspensionSweeps(). This change much simplifies calls to PxVehicleSuspensionRaycasts() and PxVehicleSuspensionSweeps() and requires less user management of the various arrays involved. ### Added: * PxVehicleWheelsDynData::getConstraints() and PxVehicleWheelsDynData::getNbConstraints() have been added to potentially have vehicles use immediate mode for solving the vehicle rigid body constraints. * New method PxVehicleGraph::getRawData() to extract raw telemetry data. * New PxVehicleSteerFilter class, used in PxVehicleDrive4WSmoothDigitalRawInputsAndSetAnalogInputs & PxVehicleDrive4WSmoothAnalogRawInputsAndSetAnalogInputs to smooth the vehicle's steering angle when going from air to ground. * A new function PxVehicleWheelsDynData::setTireContacts() has been added to the PhysX Vehicle SDK. This function allows users to directly set tire contact plane and friction for all tires on the vehicle as an alternative to using PxVehicleSuspensionSweeps() or PxVehicleSuspensionRaycasts(). * A new function PxVehicleDrivableSurfaceToTireFrictionPairs::getSurfaceType(const PxMateria& surfaceMaterial), which returns the surface type associated with a PxMaterial instance. * A new function PxVehicleDrivableSurfaceToTireFrictionPairs::getTypePairFriction(const PxMaterial& surfaceMaterial, const PxU32 tireType), which returns the friction value associated with a specified combination of PxMaterial instance and tire type. * New complementary functions PxVehicleDrivableSurfaceToTireFrictionPairs::serializeToBinary() and PxVehicleDrivableSurfaceToTireFrictionPairs::deserializeFromBinary(), which allow friction tables to be serialized and deserialized. * A new structure PxVehicleContext has been introduced to allow, for example, to have a set of common settings for vehicles in scene A and a different set for vehicles in scene B. PxVehicleUpdates() is one of the methods where there is now the option to use this new structure. * The flag PxVehicleWheelsSimFlag::eDISABLE_SPRUNG_MASS_SUM_CHECK has been introduced to allow setting suspension sprung mass values that do not sum up to the mass of the vehicle rigid body. ### Fixed: * Vehicle wheel suspension sweeps used the wrong scale for the sweep geometry if the wheel shapes used PxConvexMeshGeometry with scale factors other than 1. ## Cooking ### Deprecated: * The PxCooking object is deprecated. Please use the new standalone cooking functions instead (in the cooking library) or the low-level cooking functions (in the GeomUtils library). * PxCooking::cookBVHStructure() is deprecated. Please use PxCookBVH() instead. ### Added: * Added PxBVH34BuildStrategy enum to PxBVH34MidphaseDesc. Users can now select a SAH-based build strategy for BVH34 trees. * BVH34 trees can now be quantized or not depending on PxBVH34MidphaseDesc::quantized. * Added remeshing and mesh simplification to preprocess meshes such that they can be used for softbody simulation. New API functions are PxTetMaker::simplifyTriangleMesh()/remeshTriangleMesh()/createTreeBasedTetrahedralMesh() * Added low-level cooking functions (GeomUtils), that can be used to cook objects without using the cooking library. See SnippetStandaloneQuerySystem for an example. The cooking library is still here though for backward compatibility. * Triangle mesh cooking supports the generation of a SDF (Signed Distance Field) to allow triangle mesh colliders on dynamic actors. ### Fixed: * Serialization of uncompressed BVH34 trees was broken (both for regular cooked files and binary serialization). This has been fixed. * PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE was not taken into account when PxCookingParams::buildTriangleAdjacencies was used. ### Changed: * PxMeshMidPhase::eBVH34 is now the default midphase structure. PxMeshMidPhase::eBVH33 has been deprecated. ## Pvd ### Added: * Adds the OmniPVD API - an object oriented serialization and deserialization library for debug data. The project is called PvdRuntime. * Adds the OmniPVDWriter exposing serialization through OmniPVDWriteStream, OmniPVDFileWriteStream. * Adds the OmniPVDReader exposing de-serialization through OmniPVReadStream, OmniPVDFileReadStream. * Adds an OmniPVD API user in the PhysX SDK, exposed through PxOmniPVD, which streams PhysX debug data into an OmniPVD API write stream. * PxOmniPVD is now an optional argument to the PxCreatePhysics() function, allowing for the parallel inclusion of both PVD and OVD debug streams. * Adds PxPhysics::getOmniPvd() which returns the PxOmnipVD instance used in the call to PxCreatePhysics() * Exports : Rigid Static, Rigid Dynamic, Joints, Articulations, Contacts and more into the OmniPVD stream. * Possibility to serialize and save out, as well as read and parse OVD files (through the usage of OmniPVD API), which constain an OmniPVD command stream of PhysX debug data. * Comes with a viewer in Omniverse Create, in the form of an extension called omni.physx.pvd also known as the OmniPVD extension. * Adds the ability to import and inspect OVD files using the USD interface ### Changed: * The file source/pvd/include/PxPvdRenderBuffer.h has been removed along with the structs it declared: pvdsdk::PvdDebugPoint, pvdsdk::PvdDebugLine, pvdsdk::PvdDebugTriangle and pvdsdk::PvdDebugText. Usage of these structs may be directly replaced with PxDebugPoint, PxDebugLine, PxDebugTriangle and PxDebugText, which are all declared in common/PxRenderBuffer.h. ## Articulations ### Deprecated: * PxArticulationJointReducedCoordinate::setLimit()/getLimit()/setDrive()/getDrive() functions are deprecated. New API has been added ### Added: * Armature was added to the articulation joints. This adds additional inertia to the joint degrees of freedom. * PxArticulationJointReducedCoordinate::dofScale was added. This scales the projection of a child's inertia onto the joint degrees of freedom, resulting in an implicit resistance to motion around the joint. This can improve simulation stability. * Sensors were added to PxArticulationReducedCoordinate to report forces and torques acting on links in articulations. * Fixed tendon support was added to articulations. * Spatial tendon support was added to articulations. * PxArticulationJointReducedCoordinate::setJointPosition/PxArticulationJointReducedCoordinate::getJointPosition was added. * PxArticulationJointReducedCoordinate::setJointVelocity/PxArticulationJointReducedCoordinate::getJointVelocity was added. * PxArticulationReducedCoordinate::getRootGlobalPose() was added. * PxArticulationReducedCoordinate::setRootLinearVelocity()/getRootLinearVelocity() was added. * PxArticulationReducedCoordinate::setRootAngularVelocity()/getRootAngularVelocity() was added. * PxArticulationReducedCoordinate::setMaxCOMLinearVelocity()/getMaxCOMLinearVelocity() was added. * PxArticulationReducedCoordinate::setMaxCOMAngularVelocity()/getMaxCOMAngularVelocity() was added. * PxArticulationReducedCoordinate::setStabilizationThreshold()/getStabilizationThreshold() was added. * PxArticulationReducedCoordinate::isSleeping()/wakeUp()/putToSleep() was added. * PxArticulationReducedCoordinate::setSleepThreshold()/getSleepThreshold() was added. * PxArticulationReducedCoordinate::setSolverIterationCounts()/getSolverIterationCounts() was added. * PxArticulationReducedCoordinate::setWakeCounter()/getWakeCounter() was added. * PxArticulationReducedCoordinate::updateKinematic() and corresponding PxArticulationKinematicFlags were added. The method allows updating link states after changing joint and root state through the respective PxArticulationReducedCoordinate and PxArticulationJointReducedCoordinate API calls. * PxArticulationLink::setCfmScale()/getCfmScale() was added. * Articulations in a GPU simulation may be updated/read directly from/to user-provided device buffers, see notes in GPU Rigid Bodies->Added. * PxArticulationReducedCoordinate::setLimitParams/getLimitParams/setDriveParams()/getDriveParams() was added. * Articulation system supports up to 65536 links per articulation. * PxScene::computeGeneralizedMassMatrices() was added for batch computation of articulations' mass matrices on GPU. ### Changed: * It is no longer possible to change the articulation structure while it is in a scene. However, the articulation retains its state through removal and re-adding to the scene, even when its configuration changes, so the application can remove the articulation from the scene, change its structure and re-add it to the scene in a straightforward way. Specifically, the following is no longer possible when an articulation is in a scene: * Adding or removing links, tendons, or sensors * Changing sensor flags and local poses * Changing joint type or motion configuration * PxArticulationReducedCoordinate::getCoefficientMatrixSize returns element size (i.e. number of PxReals) instead of Byte size, and returns 0xFFFFFFFF instead of 0 in case the articulation is not in a scene. * Removed PxArticulationReducedCoordinate::releaseCache function and introduced a release method with the PxArticulationCache. * Removed PxArticulationReducedCoordinate::releaseSpatialTendon function and introduced a release method with PxArticulationTendon. * Removed PxArticulationReducedCoordinate::releaseFixedTendon function and introduced a release method with PxArticulationTendon. * Removed PxArticulationSpatialTendon::releaseAttachment function and introduced a release method with PxArticulationAttachment. * Removed PxArticulationFixedTendon::releaseTendonJoint function and introduced a release method with PxArticulationTendonJoint. * Replaced PxArticulationFixedTendon::teleportRootLink function with PxArticulationReducedCoordinate::setRootGlobalPose. * Both PxArticulationReducedCoordinate::getDofs and PxArticulationReducedCoordinate::getCacheDataSize return 0xFFFFFFFF instead of 0 in case the articulation is not in a scene. ### Fixed: * Velocity drives on prismatic joints now consistent with rigid body prismatic joints. * Numerical integration has been improved to better conserve momentum. ### Removed: * The maximal coordinate articulations have been removed with the equivalent functionality exposed through the newer reduced coordinate articulations. * It is no longer possible to set a global pose on an articulation link. * It is no longer possible to set the linear velocity on an articulation link. * It is no longer possible to set the angular velocity on an articulation link. * PxArticulationReducedCoordinate::getLinkVelocity. Use PxArticulationLink::getLinearVelocity/getAngularVelocity or PxArticulationCache to read link velocities. ## GPU Rigid Bodies ### Added: * Support for GPU-accelerated aggregate broad phase collision detection has been added. * PxSceneFlag::eSUPPRESS_READBACK flag was added. This suppresses state readback from GPU to the CPU (e.g. rigid body transforms, velocities, articulation state), which significantly improves performance. However, in order to access or set state on rigid bodies/articulations, the application must use the new copy/apply GPU API to access this state, providing device buffers to read from/write to. * PxSceneFlag::eFORCE_READBACK flag was added to force GPU readback of articulation data even if PxSceneFlag::eSUPPRESS_READBACK is set. * PxScene::copyArticulationData was added to copy the state of a set of articulations from the internal buffers inside PhysX to a user-provided device buffer. * PxScene::applyArticulationData was added to apply the state of a set of articulations from a user-provided device buffer to the internal buffers inside PhysX. * PxScene::copyActorData was added to copy the PxRigidDynamic/PxRigidActor data from the internal buffers inside PhysX to a user-provided device buffer. * PxScene::applyActorData was added to apply the state of a set of PxRigidDynamic/PxRigidActor from a user-provided device buffer to the internal buffers inside PhysX. * PxScene::copySoftBodyData was added to copy the state of a set of soft bodies from the internal buffers inside PhysX to a user-provided device buffer. * PxScene::applySoftBodyData was added to apply the state of a set of soft bodies from a user-provided device buffer to the internal buffers inside PhysX. * PxScene::copyContactData was added to copy the contact data from the internal buffers inside PhysX to a user-provided device buffer. ### Changed: * Reworked PxgDynamicsMemoryConfig to simplify configuring GPU memory usage. This change can also significantly reduce GPU memory usage compared to PhysX 4. ### Fixed: * Speculative CCD support was added to GPU rigid bodies. ## Particle System ### Added: * A PBD (Position Based Dynamics) particle system capable of simulating fluids and granular materials * Interacts with all other supported actors (rigid bodies, soft bodies etc). * User buffer architecture to store particles. It simplifies adding and removing particles at runtime and eliminates the need to specify a maximal number of particles when setting up a particle system. * Supports multiple materials. Each particle can reference its own or a shared material. ## Softbodies ### Added: * FEM (Finite Element Method) based softbodies. * Interact with all other supported actors (rigid bodies, particles etc). * Generation of tetmeshes to create a softbody out of a triangle mesh. Different kinds of tetmeshes are supported to match different use cases (conforming and voxel based tetmeshes). * Per-tetrahedra materials support. * Attachment support including soft body vs soft body and soft body vs rigid body. # v4.1.2 April 2021 ## General ### Added: * Added SnippetTriggers to show how to emulate triggers using regular non-trigger shapes. This supports trigger-trigger notifications and CCD. * Added Android 64 bits target: * Added build preset for Android arm64-v8a architecture. * Using ANDROID ABI as part of the Android output folder to avoid name collisions between 32 and 64 bit binaries. * Ignoring strict-aliasing warning on Android. * Fixed compilation error on Android debug armv8: Not inlining computeDriveInertia function to fix "conditional branch out of range" error. * Added support to build iOS with dynamic libraries: * The changes are copied from macOS makefiles, now iOS makefiles are in line with macOS ones. * Update toolchain cmake file to only generate 64 bits target on iOS (as its preset suggests because it's called "ios64"). * Added support to build Android with dynamic libraries. * The changes are copied from iOS makefiles, now Android makefiles are in line with iOS ones. * Modified cmake files of PhysXCharacterKinematic and PhysXExtension projects for Mac/iOS/Android so they add the suffix "_static" like the other platforms. ### Fixed * Some profile zones did not properly setup the "context" parameter. This has been fixed. * Removed duplicate closing cross-thread event for Basic.narrowPhase event. * Fixed buffer over-read in CmPool.h * Replaced all custom offsetof expressions that seem to dereference a null pointer with the PX_OFFSET_OF_RT macro. * Replaced run-time assert on sizeof(PxHeightFieldSample::height) with compile-time assert in physx::Gu::HeightFieldUtil constructor. * Various minor issues (doc typos, const correctness, compilation warnings, etc) reported on GitHub have been fixed. ## Rigid body ### Changed: * PxScene::setFrictionType() has been marked as deprecated due to its strong limitations. Simply set the desired friction type in PxSceneDesc. * It is now legal to set the number of velocity iterations to zero. In some difficult configurations involving large mass ratios, the TGS solver's convergence can be negatively impacted by velocity iterations. ### Fixed * The PxContactSet::ignore() function was not working properly and has been fixed. This may have caused issues in PxVehicleModifyWheelContacts. * The debug visualization code could crash when using PxVisualizationParameter::eCOLLISION_COMPOUNDS. This has been fixed. * Fixed a crash in the reduced-coordinates articulation system when the application removes the articulation from the scene and reinserts it back into the scene. * Improved stacking quality with TGS solver simulating stacks of articulations. * Fixed TGS solver stability issue constraining a rigid body to a kinematic actor. * Fixed typo with ang dominance in CPU block solver. * Fixed rare crash destroying a contact manager during CCD. * Fixed buffer over-write when simulating a convex mesh with more than 64 vertices in a single face. ### Added * PxRigidBodyFlag::eFORCE_KINE_KINE_NOTIFICATIONS and PxRigidBodyFlag::eFORCE_STATIC_KINE_NOTIFICATIONS have been added. ## Cooking ### Fixed: * The number of bytes allocated for vertices by the convex hull builder was incorrect. This has been fixed. ## Serialization ### Fixed: * A performance problem in PxBinaryConverter when converting large collections has been fixed. ## Vehicles ### Added: * PxVehicleWheelsDynData::getConstraints() and PxVehicleWheelsDynData::getNbConstraints() have been added to potentially have vehicles use immediate mode for solving the vehicle rigid body constraints. * New method PxVehicleGraph::getRawData() to extract raw telemetry data. * An inflation parameter has been added to PxVehicleSuspensionSweeps. * New flags PxVehicleWheelsSimFlag::eDISABLE_INTERNAL_CYLINDER_PLANE_INTERSECTION_TEST and PxVehicleWheelsSimFlag::eDISABLE_SUSPENSION_FORCE_PROJECTION have been added. ### Changed: * Concurrent calls to PxVehicleUpdateSingleVehicleAndStoreTelemetryData() are now permitted if the additional parameter vehicleConcurrentUpdates is used. ### Fixed: * A null pointer dereference bug has been fixed. The bug occurred if the vehicle's rigid body actor was asleep and the vehicle relied on cached tire contact planes rather than the results of a fresh suspension query. ## Character controller ### Fixed: * The prefilter & postfilters callback were called all the time, ignoring the PxQueryFlag::ePREFILTER and PxQueryFlag::ePOSTFILTER flags. This has been fixed. ## Scene queries ### Fixed: * The BVH34 codepath had a bug in the raycast-vs-mesh-with-multiple-hits case, where returned hits could be further away than defined max hit distance. This has been fixed. # v4.1.1 August 2019 ## General ### Added: * Support for Visual Studio 2019 has been added, cmake 3.14 is required. ### Changed: * Android binary output directory name contains Android ABI string. ## Vehicles ### Added: * PxVehicleWheelsSimFlags and corresponding set/get methods have been added to PxVehicleWheelsSimData. The flag eLIMIT_SUSPENSION_EXPANSION_VELOCITY can be used to avoid suspension forces being applied if the suspension can not expand fast enough to push the wheel onto the ground in a simulation step. This helps to reduce artifacts like the vehicle sticking to the ground if extreme damping ratios are chosen. ### Fixed: * The PxVehicleDrive::setToRestState() was not clearing all cached data, which could sometimes make vehicles misbehave after calls to this function. ## Cooking ### Added: * Added error message when not at least four valid vertices exist after vertices cleanup. ## Serialization ### Fixed: * Binary serialization of kinematic rigid dynamic actors was failing unless they were part of a scene. ## Rigid body ### Fixed * Out of shared memory failure with GPU articulations. * Inconsistent results when setting joint drive targets with GPU articulations compared to CPU articulations. * Assert when simulating a scene with > 64k rigid bodies and joints. * Error in PxActor::getConnectors() method when there are multiple connector types. * Setting joint positions on articulations did not update world-space link poses and velocities. * Improved TGS articulation joint drive solver. * Improved robustness of articulation spherical joints. * Joint forces/positions/velocities set through the PxArticulationCache are correctly applied when using GPU articulations. * Fixed rare crash in MBP when the system contains out-of-bounds objects. * Fixed a crash in the reduced-coordinates articulation system when the application removes the articulation from the scene and reinserts it back into the scene. # v4.1.0 March 2019 ## Overview ### Immediate mode support for reduced-coordinates articulations and the temporal Gauss Seidel solver. ### GPU acceleration for reduced-coordinates articulations. ## General ### Added: * Added support for UWP, note that cmake 3.13.4 is required for uwp arm64. ### Fixed: * PhysXGpu DLLs are now standalone, so they will now work with both static and dynamic PhysX libraries. * PhysX delay loading code is disabled for the static library configuration. ### Changed: * Removed PxGpuDispatcher class. Instead of querying the GPU dispatcher with PxCudaContextManager::getGpuDispatcher() and providing it to the PxScene with PxSceneDesc::gpuDispatcher, please provide the CUDA context manager directly using PxSceneDesc::cudaContextManager. * PxCreateCudaContextManager does have an additional parameter PxProfilerCallback, that is required in order to get profiling events from the GPU dll. * FastXml project is now compiled as OBJECT on win platforms and is linked into PhysXExtensions library. * Removed PxArticulationBase::getType(), PxArticulationBase::eReducedCoordinate, PxArticulationBase::eMaximumCoordinate and added PxConcreteType::eARTICULATION_REDUCED_COORDINATE, PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE. ## Rigid Bodies ### Added: * Immediate mode API for reduced-coordinates articulations. * Immediate mode API for the temporal Gauss Seidel (TGS) solver . * Compute dense Jacobian matrix for the reduced-coordinates articulations. * GPU acceleration for reduced-coordinates articulations with PGS solver. * GPU acceleration for reduced-coordinates articulations with TGS solver (experimental). ### Changed: * PxSimulationStatistics::nbDynamicBodies does not include kinematics any longer. Instead they are covered in new nbKinematicBodies counter. ### Fixed: * Fixed speculative CCD optimization with sleeping bodies. * Fixed the overlap termination condition in the GJK code for sphere primitive. * Fixed a bug in the face selection algorithm for paper thin box overlapped with capsule. * Fixed a contact recycling issue with PCM contact gen. * Fixed an issue with articulation when removing and adding links to the articulation. ## Serialization ### Added: * PxSerialization::serializeCollectionToBinaryDeterministic, convenience function to post-process binary output with PxBinaryConverter for determinism. For achieving determinism, the checked build needs to be used. * Support for binary and xml serialization for PxArticulationReducedCoordinate. ### Fixed: * PxBinaryConverter can now produce deterministic output, independent of the runtime environment the objects have been serialized in. For achieving determinism, the checked build needs to be used for serializing collections. ### Changed: * PX_BINARY_SERIAL_VERSION has been changed to a global unique identifier string. PX_PHYSICS_VERSION is no longer part of binary data versioning. # v4.0.0.25635910 January 2019 ## General ### Fixed: * Fixed issue in PxBinaryConverter::convert that could corrupt platform re-targeting of convex meshes with more than 127 vertices. * GenerateProject scripts should now also work when not called from PhysX directory. * GenerateProject script will now create correct compiler/ directory on Linux based systems. * Removed /Wall from MSVC compilers. * Fixed CMake install, added missing cudacontextmanager files. * Fixed binary serialization of actors in aggregates without serialization of the containing aggregate. ### Removed: * CharacterKinematic API export/import macros have been removed. ### Added: * Support for Linux samples has been added. * PxConfig.h include file will be generated during generate projects script. Including this file in your project will ensure that required defines (like PX_PHYSX_STATIC_LIB) are set. ### Changed: * PX_FOUNDATION_API was moved to PhysX and uses PX_PHYSX_STATIC_LIB define as the rest of the SDK. * PxAssertHandler moved from PxShared to PhysX and marked as deprecated. * PxShared does use PX_SHARED_ASSERT instead of PX_ASSERT which is used just in the PhysX SDK and uses PxAssertHandler. # v4.0 December 2018 ## Supported Platforms <table cellspacing=3> <tr> <th width="24" /> <th align="left">Runtime</th> <th width="18" /> <th align="left">Development</th> </tr> <tr> <td /> <td>Apple iOS (tested on 12.1)</td> <td /> <td>Xcode (tested with 10.1)</td> </tr> <tr> <td /> <td>Apple macOS (tested on 10.13)</td> <td /> <td>Xcode (tested with 10.1)</td> </tr> <tr> <td /> <td>Google Android ARM (tested with API Level 19 - KITKAT)</td> <td /> <td>NDK r13b</td> </tr> <tr> <td /> <td>Linux (tested on Ubuntu 16.04), GPU acceleration: display driver and GPU supporting CUDA 10 / CUDA ARCH 3.0</td> <td /> <td>Clang (tested with 3.8)</td> </tr> <tr> <td /> <td>Microsoft Windows, GPU acceleration: display driver and GPU supporting CUDA 10 / CUDA ARCH 3.0</td> <td /> <td>Microsoft Visual Studio 2013, 2015, 2017</td> </tr> <tr> <td /> <td>Microsoft XBox One*</td> <td /> <td></td> </tr> <tr> <td /> <td>Nintendo Switch*</td> <td /> <td></td> </tr> <tr> <td /> <td>Sony Playstation 4*</td> <td /> <td></td> </tr> </table> \* Console code subject to platform NDA not available on GitHub. Developers licensed by respective platform owners please contact NVIDIA for access. ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ## General ### Added: * New Temporal Gauss Seidel (TGS) solver offering a new level of simulation accuracy. * New Reduced Coordinate Articulation feature with no relative positional error and realistic actuation. * New automatic multi-broadphase (ABP) providing better out of the box performance for many use cases. * New BVH structure supporting better performance for actors with many shapes. ### Removed: * PhysX Particle feature. * PhysX Cloth feature. * The deprecated active transforms feature has been removed. Please use active actors instead. * The deprecated multi client behavior feature has been removed. * The deprecated legacy heightfields have been removed. ### Changed: * The PhysX SDK build system is now based on CMake generated build configuration files. For more details, please refer to the PhysX SDK 4.0 Migration Guide. * The Linux build has been changed to produce static as opposed to shared libraries. The compiler was switched from GCC to Clang. * The PxShared library contains functionality shared beyond the PhysX SDK. It has been streamlined to a minimal set of headers. The PxFoundation singleton has been moved back to the PhysX SDK, as well as the task manager, CUDA context manager and PhysX Visual Debugger (PVD) functionality. * PhysXDelayLoadHook and PhysXGpuLoadHook have been simplified, and PxFoundationDelayLoadHook has been removed. ## Rigid Bodies ### Added: * A new broadphase implementation has been added. See PxBroadPhaseType::eABP for details. This is now the default broadphase implementation. * TGS: A new rigid body solver, which can produce improved convergence compared to the default rigid body solver. * Optional torsional friction model to simulate rotational friction when there is just a single point of contact. * A flag to enable friction constraints to be processed every frame has been added * PxContactJoint added to represent contacts in inverse dynamics. Not intended for use in simulation. * A missing PxShape::getReferenceCount() function has been added. * A new flag has been added to PxMaterial to improve friction accuracy. The flag is disabled by default to maintain legacy behavior. ### Removed: * PxVisualizationParameter::eDEPRECATED_BODY_JOINT_GROUPS has been removed. * PxSceneDesc::maxNbObjectsPerRegion has been removed. * PxRigidActor::createShape() has been removed. Please use PxPhysics::createShape() or PxRigidActorExt::createExclusiveShape() instead * The deprecated mass parameter in PxTolerancesScale has been removed. * PxSceneFlag::eDEPRECATED_TRIGGER_TRIGGER_REPORTS has been removed. ### Changed: * Aggregates can now contain more than 128 actors. * Switching a kinematic object to dynamic does not automatically wake up the object anymore. Explicit calls to PxRigidDynamic::wakeUp() are now needed. * Switching a kinematic object to dynamic re-inserts the object into the broadphase, producing PxPairFlag::eNOTIFY_TOUCH_FOUND events instead of PxPairFlag::eNOTIFY_TOUCH_PERSISTS events. * PxConvexMeshGeometryFlag::eTIGHT_BOUNDS is now enabled by default for PxConvexMeshGeometry. * The default max angular velocity for rigid bodies has been changed, from 7 to 100. ## Extensions ### Added: * PxD6Joint now supports per-axis linear limit pairs. * Added PxSphericalJoint::getSwingYAngle and PxSphericalJoint::getSwingZAngle. * Added PxD6Joint distance limit debug visualization. * Added PxD6JointCreate.h file with helper functions to setup the D6 joint in various common configurations. * Added pyramidal swing limits to the D6 joint. ### Removed: * PxComputeHeightFieldPenetration has a new signature. * PxComputeMeshPenetration has been removed. Use PxComputeTriangleMeshPenetration instead. ### Changed: * PxRevoluteJoint now properly supports a -PI*2 to +PI*2 range for its limits, and the accuracy of limits has been improved. In order to use extended limit ranges, PxConstraintFlag::eENABLE_EXTENDED_LIMITS must be raised on the constraint. * PxD6Joint now properly supports a -PI*2 to +PI*2 range for its twist limit, and the accuracy of the twist limit has been improved. In order to use extended limit ranges, PxConstraintFlag::eENABLE_EXTENDED_LIMITS must be raised on the constraint. * The accuracy of the D6 joint swing limits has been improved. * PxDistanceJoint does now always insert constraint row, this change does increase the limit precision. * PxDistanceJoint::getDistance does not anymore return squared distance. * PxD6Joint::setDriveVelocity, PxD6Joint::setDrivePosition and PxRevoluteJoint::setDriveVelocity have now additional parameter autowake, which will wake the joint rigids up if true (default behavior). * Joint shaders now take a bool to define whether to use extended joint limits or not. * Joint shaders must now provide the cA2w and cB2w vectors, defining the world-space location of the joint anchors for both bodies. ### Deprecated: * PxD6Joint::getTwist() has been deprecated. Please use PxD6Joint::getTwistAngle() now. * The previous PxD6Joint::setLinearLimit() and PxD6Joint::getLinearLimit() functions (supporting a single linear limit value) have been deprecated. Please use PxD6Joint::setDistanceLimit() and PxD6Joint::getDistanceLimit() instead. Or you can also use the new PxD6Joint::setLinearLimit() and PxD6Joint::getLinearLimit() functions, which now support pairs of linear limit values. ## Articulations ### Added: * New reduced coordinate articulation implementation, supporting a wider range of joint types, more accurate drive model, inverse dynamics and joint torque control. * PxArticulationJoint::getParentArticulationLink and PxArticulationJoint::getChildArticulationLink has been added. ## Scene queries ### Removed: * PxHitFlag::eDISTANCE has been removed. * The PxVolumeCache feature has been removed. * The PxSpatialIndex feature has been removed. * The deprecated PxSceneFlag::eSUPPRESS_EAGER_SCENE_QUERY_REFIT has been removed. ## Cooking ### Added: * PxBVHStructure added, it computes and stores BVH structure for given bounds. The structure can be used for actors with large amount of shapes to perform scene queries actor centric rather than shape centric. For more information please see guide or snippets. ### Removed: * PxPlatform enum has been removed. PhysX supported platforms all share the same endianness * The deprecated PxCookingParams::meshCookingHint and PxCookingParams::meshSizePerformanceTradeOff parameters have been removed. * The deprecated PxGetGaussMapVertexLimitForPlatform has been removed, use PxCookingParams::gaussMapLimit instead. * The deprecated PxConvexMeshCookingType::eINFLATION_INCREMENTAL_HULL and PxCookingParams::skinWidth have been removed. * PxBVH34MidphaseDesc::numTrisPerLeaf has been renamed to PxBVH34MidphaseDesc::numPrimsPerLeaf # v3.4.2.25354359 December 2018 ## General ### Changed: * Changed GitHub distribution to BSD license. ## Supported Platforms <table cellspacing=3> <tr> <th width="24" /> <th align="left">Runtime</th> <th width="18" /> <th align="left">Development</th> </tr> <tr> <td /> <td>Apple iOS (tested on 12.1)</td> <td /> <td>Xcode (tested with 10.1)</td> </tr> <tr> <td /> <td>Apple macOS (tested on 10.13)</td> <td /> <td>Xcode (tested with 10.1)</td> </tr> <tr> <td /> <td>Google Android ARM (tested with API Level 16, Android 4.1 - JELLY_BEAN)</td> <td /> <td>NDK r13b-win32</td> </tr> <tr> <td /> <td>Linux (tested on Ubuntu 16.04, GPU acceleration: NVIDIA Driver version R361+ and CUDA ARCH 3.0)</td> <td /> <td>GCC (tested with 4.8)</td> </tr> <tr> <td /> <td>Microsoft Windows XP or later (NVIDIA Driver version R304 or later is required for GPU acceleration)</td> <td /> <td>Microsoft Visual Studio 2012, 2013, 2015</td> </tr> <tr> <td /> <td>Microsoft XBox One*</td> <td /> <td></td> </tr> <tr> <td /> <td>Nintendo Switch*</td> <td /> <td></td> </tr> <tr> <td /> <td>Sony Playstation 4*</td> <td /> <td></td> </tr> </table> \* Console code subject to platform NDA not available on GitHub. Developers licensed by respective platform owners please contact NVIDIA for access. # v3.4.2.25256367 November 2018 ## General ### Changed: * A couple of serialization write functions have been optimized. * Rtree cooking has been slightly optimized. * Renamed PxSerializer::requires to PxSerializer::requiresObjects due to an erroneous clash with C++20 keyword with apple-clang. ### Fixed: ### Moved external vector math includes out of PhysX namespaces. ## Rigid Bodies ### Fixed: * Fixed an incorrect trigger behavior when a trigger was removed and inserted within the same frame. ## Scene query ### Fixed: * Fixed a bug in BVH34. Raycasts could fail on binary deserialized BVH34 triangle meshes. # v3.4.2.24990349 September 2018 ## General ### Fixed: * PxMeshQuery::getTriangle adjacency information for heightfield geometry fixed. * Removed PxSetPhysXGpuDelayLoadHook from API. Delay loaded dynamically linked library names are now provided through PxSetPhysXDelayLoadHook. * Fixed a source of non-determinism with GPU rigid bodies. ## Rigid Bodies ### Fixed: * Fixed a divide by zero bug when gjk is trying to calculate the barycentric coordinate for two identical/nearly identical points. * Fixed an incorrect mesh index reported in contact buffer when stabilization flag was used. # v3.4.2.24698370 August 2018 ## Rigid Bodies ### Fixed: * Fixed a crash bug when EPA's edge buffer overflow. * GPU rigid bodies fixed for Volta GPUs. ### Added: * Aggregate broad phase now runs in parallel ## Cooking ### Fixed: ### Added: * PxHeightField::getSample has been added. ## Character controller ### Fixed: * Capsule controller with a very small height could degenerate to spheres (with a height of exactly zero) far away from the origin, which would then triggers errors in Debug/Checked builds. This has been fixed. * The triangle array growing strategy has been changed again to prevent performance issues when tessellation is used. Memory usage may increase in these cases. * Some internal debug visualization code has been disabled and a crash in it has been fixed. ## Scene query ### Fixed: * Fixed possible buffer overrun when PxPruningStructure was used. * Raycasts against a heightfield may have missed if a large distance was used. * Sq raycasts against heightfield or triangle mesh could return a mildly negative values, this has been fixed. # v3.4.2.24214033 May 2018 ## General ### Fixed: * Fixed clang 7 unionCast issues. * Fixed the binary meta data in PhysX_3.4/Tools/BinaryMetaData for conversion of vehicles. ## Rigid Bodies ### Deprecated: * PxSceneFlag::eENABLE_KINEMATIC_STATIC_PAIRS and PxSceneDesc::eENABLE_KINEMATIC_PAIRS have been deprecated. Use the new PxPairFilteringMode parameters in PxSceneDesc instead. ### Fixed: * A sequence of shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false) / shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true) without simulation calls in-between could produce errors in the broadphase. This has been fixed. * Fixed a bug in the broadphase (SAP) that got recently introduced in SDK 3.4.1.23933511. It should only have generated a few false positives (more overlaps than strictly necessary). * Fixed a bug in PxShape::checkMaterialSetup. * Fixed intermittent crash with GPU rigid bodies when materials were destroyed. * Fixed bug where setting maxImpulse to 0 on CCD contact modification meant contact was not reported in the frame's contact reports. ## Cooking ### Fixed: * Big convex mesh serialization used together with insertion callback stored incorrect memory for big convex data. This has been fixed. ## Scene query ### Fixed: * Fixed a bug in extended bucket pruner, when a pruning structure was added and immediatelly released. # v3.4.1.23933511 April 2018 ## General ### Added: * Added snippet for deformable meshes, added section in the guide for them. ## Rigid Bodies ### Fixed: * PxTriangleMesh::refitBVH() was crashing with PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE. This has been fixed. * SQ-only shapes contained in aggregates could result in crashes or memory corruption when removed from the aggregate. This has been fixed. * Assert no longer fired if a dynamic body contacting a static is converted to kinematic with kinematic-static pairs enabled. * Assert reporting broad phase as being "inconsistent" could fire when using speculative CCD when sleeping objects were activated. ## Cooking ### Fixed: * Convex hull cooking could have produced hulls with vertices too far from convex hull planes, this has been fixed. ### Changed: * PxCooking::createTriangleMesh does now take additional output parameter PxTriangleMeshCookingResult::Enum. * PxCooking::createConvexMesh does now take additional output parameter PxConvexMeshCookingResult::Enum. ## Scene query ### Changed: * PxSceneFlag::eSUPPRESS_EAGER_SCENE_QUERY_REFIT has been marked as deprecated. Was replaced with PxSceneQueryUpdateMode enum, if this new enum is set the flag gets ignored. ### Added: * PxSceneQueryUpdateMode was added to control work done during fetchResults. * PxScene::sceneQueriesUpdate, PxScene::checkQueries and PxScene::fetchQueries were added to run separate scene query update, see manual for more details. # v3.4.1.23584284 February 2018 ## General ### Fixed: * PhysX sometimes froze in a spinlock after certain sequences of read & write locks. This has been fixed. ## Scene queries ### Fixed: * Raycasts against heightfields were sometimes missing hits for vertical rays were located exactly at the heightfield's boundaries. This has been fixed. ## Rigid Bodies ### Fixed: * Avoid edge-face collisions on boundary edges when eNO_BOUNDARY_EDGES flag is raised on heightfield when using PCM and unified HF collision. # v3.4.1.23472123 January 2018 ## General ### Added: * Visual Studio 2017 15.5.1 and newer is now supported. Samples are currently not supported with Visual Studio 2017. ### Removed: * Visual Studio 2012 support is discontinued. ## Cooking ### Fixed: * Cooked mesh structures contained a mix of little-endian and big-endian data (the midphase structures were always saved as big-endian). This made loading of cooked files slower than necessary. This has been fixed. ## Scene queries ### Fixed: * Buffered moves were sometimes not properly taken into account by scene queries, leading to invalid results for one frame. This has been fixed. * Pruning structure failed to build when actor had more shapes. This has been fixed. # v3.4.1.23173160 November 2017 ## Extensions ### Fixed: * An issue with CCD sweeps against meshes that could potentially lead to the earliest impact not being detected has been fixed. # v3.4.1.23131702 November 2017 ## General ### Fixed: * A bug in the management of internal interaction objects has been fixed. ## Extensions ### Fixed: * A regression in prismatic constraint stability introduced in PhysX 3.4.1 has been fixed. * PxRevoluteJoint::getAngle(), PxD6Joint::getTwist(), PxD6Joint::getSwingYAngle() and PxD6Joint::getSwingZAngle() did not always return the correct angle. This problem has been fixed. * The "double cone" case of the D6 joint had errors both in the debug visualization and the code dealing with limits. This has been fixed. * The debug visualization of the D6 joint in the twist case did not properly color-code the angular limits. This has been fixed. * The debug visualization of distance joints has been fixed. * The debug visualization of prismatic joints has been fixed. * The debug visualization of revolute joints has been fixed. It now renders active limits properly (in red when the limit is active, grey otherwise). * Proper visualization flags are now passed to the PxConstraintVisualize function. Previously all available flags were active, even if PxVisualizationParameter::eJOINT_LOCAL_FRAMES and/or PxVisualizationParameter::eJOINT_LIMITS were set to zero. * PxRevoluteJoint::getVelocity has been fixed. ## Scene queries ### Fixed: * Sweep queries using the eMTD flag could generate incorrect normals in sphere/sphere, sphere/capsule or capsule/capsule cases, when the objects were exactly overlapping each-other. This has been fixed. * Sweep convex mesh vs heightfield queries using the eMTD flag did not fill correctly returned faceIndex. This has been fixed. # v3.4.1 September 2017 ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ## General ### Deprecated: * The PhysX cloth feature has been deprecated. ### Changed: * The meaning of PxVisualizationParameter::eCULL_BOX has changed. It is now used to visualize the current culling box, while it was previously used to enable or disable the feature. Please simply use PxScene::setVisualizationCullingBox() to enable the feature from now on. * PxVisualizationParameter::eBODY_JOINT_GROUPS has been deprecated. * Performance of setCMassLocalPose function has been improved. ### Added: * PhysXGpu: Added warnings for the case when the dynamic gpu library fails to load. ## Rigid Bodies ### Fixed: * A potential crash when calling detachShape has been fixed. * Fixed assert that fired if application switched a body from dynamic to kinematic, then queried kinematic target without setting one. This assert only fired if the modifications overlapped simulation so were buffered. * PxArticulation::getStabilizationThreshold() and PxArticulation::setStabilizationThreshold() were accessing the sleep threshold instead of the stabilization threshold. This has been fixed. * Fixed an internal edge bug in PCM sphere vs mesh code * Make sure sphere vs sphere and sphere vs box in PCM contact gen generate contacts consistently on the second body when the sphere center is contained in the other shape ### Changed: * Improved convex vs mesh contact generation when using GPU rigid bodies. Requires the mesh to be recooked. * Improved convex vs convex contact generation when using GPU rigid bodies. * Reduced memory footprint of GPU triangle meshes significantly. Requires the mesh to be recooked. ### Added: * Support for modifying friction and restitution coefficients has been added to contact modification. * Added PxRigidBodyFlag::eENABLE_CCD_MAX_CONTACT_IMPULSE to enable maxContactImpulse member of PxRigidBody to be used in CCD. This is disabled by default. It is useful in some circumstances, e.g. shooting a small ball through a plate glass window and triggering it to break, but it can also result in behavioral artifacts so it is disabled by default. * Added PxSceneDesc::solverOffsetSlop. This is defaulted to a value of 0. A positive, non-zero value defines a tolerance used in the solver below which a contacts' offset from the COM of the body is negligible and therefore snapped to zero. This clamping occurs in a space tangential to the contact or friction direction. This is aimed at pool or golf simulations, where small numerical imprecision in either contact points or normals can lead to balls curving slightly when there are relatively high angular velocities involved. * Added PxConvexMeshGeometry::maxMargin. This allows the application to tune the maximum amount by which PCM collision detection will shrink convex shapes in contact generation. This shrinking approach leads to some noticeable clipping around edges and vertices, but should not lead to clipping with face collisions. By default, the mesh is shrunk by an amount that is automatically computed based on the shape's properties. This allows you to limit by how much the shape will be shrunk. If the maxMargin is set to 0, then the original shape will be used for collision detection. ## Scene queries ### Fixed: * A rare invalid memory read that could lead to incorrect sweep results in case of an initial overlap has been fixed. ## Serialization ### Fixed: * Binary serialization didn't preserve PxConstraintFlags, e.g. projection flags. * Xml serialization failed if a shape referencing a PxTriangleMesh was added to another (dependent) collection. # v3.4.0.22387197 June 2017 ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ## Cooking ### Fixed: * Fixed issue when PxConvexFlag::e16_BIT_INDICES was used together with PxConvexFlag::eCOMPUTE_CONVEX. * Fixed issue in convex hull cooking when postHullMerge was not executed. * Fixed crash in CCD when using bodies with 0 mass. ## Rigid Bodies ### Fixed: * Fixed behavioral differences when comparing the results of a given scene to the results when simulating a subset of the islands in that scene. In order for this case to be deterministic, it is necessary to raise PxSceneFlag::eENABLE_ENHANCED_DETERMINISM. ### Added: * Introduced maxBiasCoefficient in PxSceneDesc to be able to limit the coefficient used to scale error to produce the bias used in the constraint solver to correct geometric error. The default value is PX_MAX_F32 and, therefore, a value of 1/dt will be used. This value can be useful to reduce/remove jitter in scenes with variable or very small time-steps.</i> # v3.4.0.22121272 May ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ## Rigid Bodies ### Fixed: * Fixed a bug in convex vs convex PCM contact gen code. There were cases in which full contact gen should have been triggered but was not. * Fixed a jittering bug on both GPU/CPU codepath in PCM contact gen code. This is due to the contact recycling condition not considering the toleranceLength. * Fixed a bug causing simulation to behave incorrectly when greater than 65536 bodies were simulated. ## Scene queries ### Fixed: * A rare crash that could happen with sphere overlap calls has been fixed. * Fixed a stack corruption in CCD contact modification callback. * Fixed a bug where external forces were not cleared correctly with PxArticulations. ## Cooking ### Changed: * Convex hull cooking now reuses edge information, perf optimization. * PxCooking API is now const if possible. # v3.4.0.22017166 April 2017 ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ## General ### Added: * PxConvexMeshGeometry::maxMargin has been added. This will let the application limit how much the shape is shrunk in GJK when using by PCM contact gen ## Rigid Bodies ### Fixed: * Fixed a bug with joint breaking where sometimes joints would not break as expected. * Fix a race condition between cloth/particle/trigger interactions and the parallel filtering of rigid body interaction. * GPU rigid body feature now issues a performance warning in checked build if feature is enabled but PCM contact gen is not. * Fixed a bug with applying external force/torque to a body in buffered insertion stage. * Fixed a bug with CCD involving rotated static mesh actors. * Fixed a memory leak in CCD. ### Changed: * Optimizations for GPU rigid body feature, including reduced memory footprint and improvements to performance spikes when many objects are woken in a single frame. ## Midphase ### Fixed: * Fix Crash in BV4 code (serialization bug). ## Cooking ### Fixed: * Fix endless loop in convex hull cooking. # v3.4.0.21821222 March 2017 ## Supported Platforms ## Runtime * Apple iOS * Apple Mac OS X * Google Android ARM (version 2.2 or later required for SDK, 2.3 or later required for snippets) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver version R304 or later is required for GPU acceleration) * Microsoft XBox One * Nintendo Switch * Sony Playstation 4 ## Development * Microsoft Windows XP or later * Microsoft Visual Studio 2012, 2013, 2015 * Xcode 8.2 ## Known Issues ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ## General ### Fixed: * A rare crash happening in the debug visualization code has been fixed. ## Rigid Bodies ### Fixed: * Fixed a bug in PCM capsule vs plane contact gen. * A crash happening with more than 64K interactions has been fixed. * Fixed an island management issue in CCD when using multiple CCD passes. * Fixed a bug with GPU rigid bodies with non-simulation scene query-only shapes. * Fixed a bug in convex vs convex PCM contact gen code. There were cases in which full contact gen should have been triggered but was not. * Fixed a jittering bug on both GPU/CPU codepath in PCM contact gen code. This is due to the contact recycling condition not considering the toleranceLength. ### Added: * getFrozenActors has been added to allow application queries the frozen actors * PxRigidDynamic::setKinematicSurfaceVelocity has been added, permitting the user to set a persistent velocity on a kinematic actor which behaves like a conveyor belt * PxSceneDesc::solverOffsetSlop added. This defines a threshold distance from a body's COM under which a contact will be snapped to the COM of the body inside the solver along any principal component axis ## Scene queries ### Fixed: * A bug in the BVH34 overlap code sometimes made PxMeshOverlapUtil::findOverlap assert (reporting an incorrect buffer overflow). This has been fixed. * Fix a bug in the case of two primitives just touching in sweep with eMTD flag on. # v3.4 February 2017 ## Supported Platforms ## Runtime * Apple iOS * Apple Mac OS X * Google Android ARM (version 2.2 or later required for SDK, 2.3 or later required for snippets) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver version R304 or later is required for GPU acceleration) * Microsoft XBox One * Nintendo Switch * Sony Playstation 4 ## Development * Microsoft Windows XP or later * Microsoft Visual Studio 2012, 2013, 2015 * Xcode 8.2 ## Known Issues ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ## General * Added: * nbAggregates, nbArticulations, nbDiscreteContactPairsTotal, nbDiscreteContactPairsWithCacheHits and nbDiscreteContactPairsWithContacts have been added to PxSimulationStatistics. * PxSceneLimits::maxNbBroadPhaseOverlaps has been added. * A new midphase has been added. See PxMeshMidPhase enum for details. * Midphase descriptor has been added. See PxMidphaseDesc for details. * PxHeightField::getTimestamp() has been added * PxCloneShape has been added to enable cloning of shapes. * acquireReference() has been added to increment the reference count of shapes, materials, triangle meshes, convex meshes heightfields and cloth fabrics. * The global filter shader data block can now be set through PxScene::setFilterShaderData(). * PxGpuLoadHook and PxSetPhysXGpuLoadHook has been added to support loading of GPU dll with a different name than the default. * A new profile zone has been added for debug visualization. * Changed: * PxMathUtils.h has moved from include/common to include/foundation * GPU support requires SM2.x (Fermi architecture, GeForce 400 series) or later hardware. SM1.x is no longer supported. * Windows XP 64-bit and Windows Vista no longer support GPU acceleration. Windows XP 32-bit still supports GPU acceleration. * PxTaskManager::createTaskManager requires error callback and does not accept SPU task manager. * PxCreatePhysics and PxCreateBasePhysics now take an optional pointer to an physx::PxPvd instance. * PxConstraintConnector::updatePvdProperties now takes an optional pointer to an physx::pvdsdk::PvdDataStream instance. * PxInitExtensions now takes an optional pointer to an physx::PxPvd instance. * Shared objects (triangle mesh, convex mesh, heightfield, material, shape, cloth fabric) no longer issue an eUSER_RELEASE event when their release() method is called * PxBase::isReleasable() is now a property only of the type of an object, not the object state. In particular, isReleasable() returns true for PxShape objects whose only counted reference belongs to their owning actor. * PxCollection::releaseObjects() now calls release() even on shapes whose only counted reference belongs to their owning actor. An optional parameter releaseExclusiveShapes, which defaults to true, has been added to this method to assist with common scenarios in which all shapes are created with the deprecated method PxRigidActor::createShape() or its replacement PxRigidActorExt::createExclusiveShape() * Negative mesh scale is now supported for PxTriangleMeshGeometry. Negative scale corresponds to reflection and scale along the corresponding axis. In addition to reflection PhysX will flip the triangle normals. * PxDelayLoadHook is now inherited from PxFoundationDelayLoadHook. PxFoundation dll and PxPvdSDK dll are now delay loaded inside the SDK, their names can be provided through the delay load hook. * Removed: * Sony Playstation 3 is not supported any longer. Any related APIs have been removed. * Microsoft XBox 360 is not supported any longer. Any related APIs have been removed. * Nintendo Wii U is not supported any longer. Any related APIs have been removed. * Sony Playstation Vita is not supported any longer. Any related APIs have been removed. * Visual Studio 2010 is not supported any longer. * Microsoft Windows RT is not supported any longer. * Google Android X86 is not supported any longer. * PhysX Samples are not supported anymore except on Microsoft Windows. * Linux 32-bit no longer support GPU acceleration. Linux 64-bit still supports GPU acceleration. * Fixed: * PxScene::setFlag() does now properly send error messages in CHECKED builds if a non-mutable scene flag gets passed in. * Fixed a bug in force threshold based contact reports, which caused events to be lost. * Fixed a bug in aggregates that led to a crash when rigid bodies are added to an aggregate after removing all rigid bodies from an aggregate. This only occurred with aggregates that were added to the scene and with rigid bodies that had shapes attached. * Fixed a bug where non-breakable joints could break, leading to a crash. * Fixed RepX load of kinematic rigid bodies with mesh shapes. * Fixed a divide by zero bug in SIMD distanceSegmentTriangle function. * Debug visualization for compound bounds (PxVisualizationParameter::eCOLLISION_COMPOUNDS) now works even when all the compounds' shapes have their debug viz flag (PxShapeFlag::eVISUALIZATION) disabled. * Double-buffering now works properly for the debug visualization culling box. * The default debug visualization culling box now works correctly with heightfields. * Rare crashes in PxShape::setGeometry() and PxShape::getMaterials() have been fixed. * A crash happening when doing an origin shift on a scene containing an empty aggregate has been fixed. * Deprecated: * PxSceneLimits::maxNbObjectsPerRegion has been deprecated. It is currently not used. * PxComputeHeightFieldPenetration has a new signature, and the old one has been deprecated * PxComputeMeshPenetration has been deprecated. Use PxComputeTriangleMeshPenetration. * The PhysX particle feature has been deprecated. * PxTolerancesScale::mass has been deprecated. It is currently not used. * PxActorClientBehaviorFlag has been marked as deprecated and will be removed in future releases. * Removed deprecated API: * PxPairFlag::eCCD_LINEAR removed. Use PxPairFlag::eDETECT_CCD_CONTACT | PxPairFlag::eSOLVE_CONTACT instead. * PxPairFlag::eRESOLVE_CONTACTS removed. Use PxPairFlag::eDETECT_DISCRETE_CONTACT | PxPairFlag::eSOLVE_CONTACT instead. * PxTriangleMeshFlag::eHAS_16BIT_TRIANGLE_INDICE removed. Use PxTriangleMeshFlag::e16_BIT_INDICES instead. * PxTriangleMeshFlag::eHAS_ADJACENCY_INFO removed. Use PxTriangleMeshFlag::eADJACENCY_INFO instead. * PxTriangleMeshDesc::convexEdgeThreshold removed. * PxSceneQueryFlag renamed to PxHitFlag. * PxHitFlag::eDIRECT_SWEEP renamed to PxHitFlag::ePRECISE_SWEEP. * PxHitFlag::eIMPACT renamed to PxHitFlag::ePOSITION. * PxSceneQueryHitType renamed to PxQueryHitType. * PxSceneQueryCache renamed to PxQueryCache. * PxSceneQueryFilterFlag renamed to PxQueryFlag. * PxSceneQueryFilterFlags renamed to PxQueryFlags. * PxSceneQueryFilterData renamed to PxQueryFilterData. * PxSceneQueryFilterCallback renamed to PxQueryFilterCallback. * PxScene::raycastAll,PxScene::raycastSingle,PxScene::raycastAny replaced by PxScene::raycast. * PxScene::overlapAll,PxScene::overlapAny replaced by PxScene::overlap. * PxScene::sweepAll,PxScene::sweepSingle,PxScene::sweepAny replaced by PxScene::sweep. * PxQuat, PxTranform, PxMat33, PxMat44 createIdentity and createZero removed. Use PxIdentity, PxZero in constructor. * PxJointType::Enum, PxJoint::getType() removed. Use PxJointConcreteType instead. * PxVisualDebugger removed. Use PxPvd instead. * PxControllerFlag renamed to PxControllerCollisionFlag. * PxCCTHit renamed to PxControllerHit. * PxCCTNonWalkableMode renamed to PxControllerNonWalkableMode. * PxControllerNonWalkableMode::eFORCE_SLIDING changed to PxControllerNonWalkableMode::ePREVENT_CLIMBING_AND_FORCE_SLIDING. * PxControllerDesc::interactionMode, groupsBitmask, callback removed. * PxController::setInteraction, getInteraction, setGroupsBitmask, getGroupsBitmask removed. * PxControllerManager::createController no longer needs PxPhysics and PxScene. * PxControllerFilters::mActiveGroups replaced with PxControllerFilters::mCCTFilterCallback. * PxSerialization::createBinaryConverter(PxSerializationRegistry&) changed to PxSerialization::createBinaryConverter(). * PxConstraintDominance renamed to PxDominanceGroupPair. * PxScene::flush renamed to PxScene::flushSimulation. * PxClothFabric::getPhaseType removed. * PxCollection::addRequired removed. * PxRigidActor::createShape discontinued support for initial transform. * PxShape::resetFiltering removed. * PxParticleBase::resetFiltering removed. * PxSceneDesc::meshContactMargin removed. * PxSceneDesc::contactCorrelationDistance removed. * Indexing operators taking signed integers in PxVec3, PxVec4, PxMat33, PxMat44, PxStrideIterator have been removed. * PxHitFlag::ePOSITION, PxHitFlag::eDISTANCE and PxHitFlag::eNORMAL are now supported in PxMeshQuery::sweep function. * PxClothFlag::eGPU renamed to PxClothFlag::eCUDA. * PxActorTypeSelectionFlag/PxActorTypeSelectionFlags. Use PxActorTypeFlag/PxActorTypeFlags instead. * PxConstraintFlag::eDEPRECATED_32_COMPATIBILITY flag removed. ## PxShared APEX 1.4 can now be used independently of PhysX. In order to achieve that a new shared code base was created called "PxShared". PhysX functionality such as common types, PxFoundation, the task infrastructure are now part of PxShared. ## Rigid Bodies * Added: * An alternative simulation API has been introduced. This makes use of the following new functions: PsScene:collide(), PxScene::fetchCollision() and PxScene::advance(). Expected usage of these functions is illustrated in a new snippet SnippetSplitSim. This feature is also described in the manual in Section Simulation->SplitSim. * PxSceneFlag::eDEPRECATED_TRIGGER_TRIGGER_REPORTS has been introduced to re-enable the legacy behavior of trigger shape pairs sending reports. This flag and the corresponding legacy behavior will be removed in version 4. * The active actors feature has been added. See PxSceneFlag::eENABLE_ACTIVE_ACTORS. * Functionality to compute and manipulate mass, inertia tensor and center of mass of objects has been exposed in the new class PxMassProperties. * The option to exclude kinematics from the active actors/transforms list has been added. See PxSceneFlag::eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS for details. * The integrated pose of dynamic rigid bodies can be accessed earlier in the pipeline through a new callback (see the API documentation for PxSimulationEventCallback::onAdvance() and PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW for details). * PxConvexMeshGeometryFlag::eTIGHT_BOUNDS has been added. See the user manual for details. * New split fetchResults methods introduced, see PxScene::fetchResultsBegin(), PxScene::fetchResultsFinish() and PxScene::processCallbacks(). This is intended to permit the application to parallelize the event notification callbacks. * New flag introduced to suppress updating scene query pruner trees inside fetchResults, see PxSceneFlag::eSUPPRESS_EAGER_SCENE_QUERY_REFIT. Instead, pruners will be updated during the next query. * Introduced GPU rigid body simulation support, see PxSceneFlag::eENABLE_GPU_DYNAMICS. GPU rigid body support requires SM3.0 or later. * Introduced a new GPU-accelerated broad phase. See PxBroadPhaseType::eGPU. GPU broad phase support requires SM3.0 or later. * Introduced a new enhanced determinism mode. See PxSceneFlag::eENABLE_ENHANCED_DETERMINISM. This provides additional levels of rigid body simulation determinism at the cost of some performance. * Introduced a new speculative contacts CCD approach. See PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD. This is a slightly cheaper, less robust solution to PxRigidBodyFlag::eENABLE_CCD. There is no need to turn CCD on the scene using PxSceneFlag::eENABLE_CCD or enable PxPairFlag::eDETECT_CCD_CONTACT with this CCD mode as it functions as an extension to the discrete time-stepping scheme. This form of CCD can be enabled on kinematic actors. * New "immediate mode" API has been added. This exposes access to the low-level contact generation and constraint solver, which allows the application to use these PhysX low-level components to perform its own simulations without needing to populate and simulate a PxScene. * RigidDynamic lock flags added which permit the application to disallow rotation/translation of PxRigidDynamics around specific axes. * Changed: * PxRigidStatic objects can now have zero shapes while being part of a scene. * PxContactPairFlag::eINTERNAL_HAS_FACE_INDICES is obsolete and has been removed. * PxConstraintFlag::eDEPRECATED_32_COMPATIBILITY was previously only implemented for spring constraints. It is now correctly implemented for equality constraints. * PxSceneFlag::eENABLE_PCM is enabled by default. This means PhysX uses PCM distance-based collision detection by default. * Calls to PxRigidDynamic::setWakeCounter() following PxScene::collide() do now explicitly get taken into account in the subsequent call to PxScene::advance(). * Calls to contact modification callbacks can be made from multiple threads simultaneously. Therefore, modification callbacks should must be thread-safe. * Unified heightfield contact generation is now the default heightfield contact generation approach. This approach offers similar performance and behavior to contact generation with triangle meshes. Unified heightfields have no thickness because contact generation operates on triangles so objects may tunnel if CCD is not enabled. * When unified heightfield contact generation is in use, the bounds of heightfield shapes are no longer extruded by "thickness". * PxArticulationJoint::setTwistLimit and PxArticulationJoint::getTwistLimit were incorrectly documented with zLimit and yLimit in the wrong order. The behavior of both functions remains unchanged but now they are correctly documented with zLimit and yLimit in the correct order. This is simply a clarification of the existing function behavior. * Removed: * The deprecated class PxFindOverlapTriangleMeshUtil has been removed. Please use PxMeshOverlapUtil instead. * The deprecated flag PxConstraintFlag::eREPORTING has been removed. Force reports are now always generated. * The following deprecated simulation event flags have been removed: PxContactPairHeaderFlag::eDELETED_ACTOR_0, ::eDELETED_ACTOR_1, PxContactPairFlag::eDELETED_SHAPE_0, ::eDELETED_SHAPE_1, PxTriggerPairFlag::eDELETED_SHAPE_TRIGGER, ::eDELETED_SHAPE_OTHER. Please use the following flags instead: PxContactPairHeaderFlag::eREMOVED_ACTOR_0, ::eREMOVED_ACTOR_1, PxContactPairFlag::eREMOVED_SHAPE_0, ::eREMOVED_SHAPE_1, PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER, ::REMOVED_SHAPE_OTHER. * The deprecated method PxPhysics::createHeightField(const PxHeightFieldDesc&) has been removed. Please use PxCooking::createHeightField(const PxHeightFieldDesc&, PxPhysicsInsertionCallback&) instead. The insertion callback can be obtained through PxPhysics::getPhysicsInsertionCallback(). * Deprecated: * PxRigidActor::createShape() has been deprecated in favor of PxRigidActorExt::createExclusiveShape() * Trigger notification events for trigger-trigger pairs have been deprecated and will be omitted by default. See the 3.4 migration guide for more information. * The active transforms feature (PxSceneFlag::eENABLE_ACTIVETRANSFORMS) has been deprecated. Please use PxSceneFlag::eENABLE_ACTIVE_ACTORS instead. * PxRegisterHeightFields has been modified to register unified heightfields, which are now the default implementation. PxRegisterLegacyHeightFields() has been added to register the legacy (deprecated) heightfield contact gen approach. * PxHeightFieldDesc::thickness has been deprecated, as the new unified height field (see PxRegisterUnifiedHeightFields()) does not support thickness any longer. * Fixed: * The capsule-vs-heightfield contact generation had a rare bug where a vertical capsule standing exactly on a shared edge could fall through a mesh. This has been fixed. * The bounding box of a shape was not always properly updated when the contact offset changed. * Fixed a bug in the GJK sweep caused by lost precision in the math * Calls to PxScene::shiftOrigin() can crash when PxRigidDynamic actors with PxActorFlag::eDISABLE_SIMULATION are present. * Fixed a bug when PxShape::setMaterials was called with less materials than shape had before. * Fixed a bug in CCD that could lead to a hang in the simulation. * Fixed a bug in PCM mesh edge-edge check for the parallel case. * Fixed a bug in CCD where contact modify callbacks could be called when the CCD did not detect a contact. * Fixed a bug with applying external force/torque to a body in buffered insertion stage. * A rare capsule-vs-mesh contact generation bug has been fixed. * A rare crash due to an invalid assert in the MBP broad-phase has been fixed. This error only affected debug & checked builds; release & profile builds were unaffected. ## Particles * Gpu: Maxwell Optimizations * The PhysX particle feature has been deprecated. * Fixed particle collision issue with PxParticleBaseFlag::ePER_PARTICLE_COLLISION_CACHE_HINT (on by default). When particles collided against very dense triangle mesh areas an assert would be triggered or particles would leak through the triangle mesh. A workaround was to disable PxParticleBaseFlag::ePER_PARTICLE_COLLISION_CACHE_HINT. ## Cloth * Continuous collision (PxClothFlag::eSWEPT_CONTACT) behavior has been optimized to reduce cloth sticking to collision shape. * Added air resistance feature (see PxCloth::setWindVelocity(PxVec3), PxCloth::setWindDrag(PxReal), PxCloth::setWindLift(PxReal), PxClothFabricDesc::nbTriangles, PxClothFabricDesc::triangles. ## Serialization * Fixed: * PxTriangleMesh instances with adjacency information were not correctly initialized when created with cooking.createTriangleMesh. This caused a crash when converting the binary serialized triangle mesh data. ## Character controller * Added: * Profile zones have been added for the character controller. * Added PxControllerDesc::registerDeletionListener boolean defining if deletion listener for CCT should be registered. * Fixed: * Character controllers cannot stand on dynamic triggers anymore. * Fixed: the capsule-vs-sphere sweep now returns a normal in the correct direction. * Fixed a bug where CCT shapes initially overlapping static geometry would be moved down by an incorrect amount (the length of the step offset). * The overlap recovery module now works against kinematic objects. ## Vehicles * Added: * Anti-roll suspension has been added. The class PxVehicleAntiRollBar and the functions PxVehicleWheelsSimData::setAntiRollBar, PxVehicleWheelsSimData::getAntiRollBar, PxVehicleWheelsSimData::getNbAntiRollBars allow anti-roll bars to be configured and queried. * A new function PxVehicleSuspensionSweeps has been introduced. This sweeps the PxShape that represents the wheel along the suspension direction. The hit planes resulting from the sweep are used as driving surfaces similar to those found by PxVehicleSuspensionRaycasts. * A new snippet SnippetVehicleContactMod has been added. This snippet demonstrates how to use sweeps and contact modification to allow the wheel's volume to fully interact with the environment. * A new function PxVehicleModifyWheelContacts has been introduced. This function analyses contact in the contact modification callback and rejects contact points that represent drivable surfaces. * A new function PxVehicleSetMaxHitActorAcceleration has been introduced. This function sets the maximum acceleration experienced by a PxRigidDynamic that finds itself under the wheel of a vehicle. * Changed: * In checked build the functions PxVehicleDrive4W::allocate, PxVehicleDriveNW::allocate, PxVehicleDriveTank::allocate, PxVehicleNoDrive::allocate all return NULL and issue a warning if called before PxInitVehicleSDK. * Tire width is no longer accounted for when computing the suspension compression from raycasts (PxVehicleSuspensionRaycasts). Instead, tire width is incorporated into the suspension compression arising from swept wheels (PxVehicleSuspensionSweeps). It is recommended to use PxVehicleSuspensionSweeps if there is a strict requirement that the inside and outside of the wheel don't visibly penetrate geometry. * Fixed: * Suspension force calculation now applies an extra force perpendicular to the spring travel direction. This force is calculated to satisfy the constraint that the sprung mass only has motion along the spring travel direction. This change mostly affects vehicles with suspension travel directions that are not vertical. * PxVehicleWheelsSimData::mThresholdLongitudinalSpeed and PxVehicleWheelsSimData::mMinLongSlipDenominator are now given default values that reflect the length scale set in PxTolerancesScale. * Unphysically large constraint forces were generated to resolve the suspension compression beyond its limit when the suspension direction and the hit normal under the wheel approach perpendicularity. This has been fixed so that the constraint force approaches zero as the angle between the hit normal and suspension direction approaches a right angle. ## Scene queries * Added: * PxPruningStructure was introduced as an optimization structure to accelerate scene queries against large sets of newly added actors. * PxScene::addActors(PxPruningStructure& ) has been added. * PxMeshQuery::sweep now supports PxHitFlag::eMESH_ANY. * PxHitFlag::eFACE_INDEX was introduced to reduce the perf cost for convex hull face index computation. In order to receive face index for sweeps against a convex hull, the flag PxHitFlag::eFACE_INDEX has to be set. Note that the face index can also be computed externally using the newly introduced method PxFindFaceIndex from the extensions library. * PxGeometryQuery::isValid was added to check provided geometry validity. * Changed: * Raycasts against triangle meshes with PxHitFlag::eMESH_MULTIPLE flag now return all hits, code for discarding hits close to each other has been removed. * PxPruningStructure enum has been renamed to PxPruningStructureType * Deprecated: * PxHitFlag::eDISTANCE has been deprecated. * The batched query feature has been deprecated. * Volume cache feature has been deprecated. * Spatial index feature has been deprecated. * Fixed: * PxScene::sweep now properly implements PxHitFlag::eMESH_BOTH_SIDES (returned normal follows the same convention as for raycasts). * Raycasts against heightfields now correctly return multiple hits when PxHitFlag::eMESH_MULTIPLE flag is used. * PxSweepHit.faceIndex was computed incorrectly for sweep tests initially overlapping convex objects. The face index is now set to 0xffffffff in these cases. * Convex vs convex sweeps in PxGeometryQuery::sweep() do now correctly return the face index of the convex mesh that gets passed in as parameter geom1 (and not the one from geom0). * PxMeshQuery::sweep now supports PxHitFlag::eMESH_ANY. * Deprecated definition PxSceneQueryHit has been removed. Please use PxQueryHit instead. * PxGeometryQuery::computePenetration with convex geometries. * On Android platforms, the eDYNAMIC_AABB_TREE pruning structure could pass already released objects into the scene query filter callback. ## Cooking * Added: * PxTriangleMeshCookingResult added, cookTriangleMesh now does return additional PxTriangleMeshCookingResult. Please see the manual for more information. * New convex hull generator added. It is now possible to switch between a new quickhull implementation and the legacy inflation based hull. Quickhull is the default algorithm. * Convex hulls can now be directly inserted in PxPhysics as triangle meshes and height fields. * A separate convex hull validation function has been added, it is now possible to create hulls without validation. * Convex hull generator vertex limit has two different algorithms - plane shifting and OBB slicing. * PxConvexFlag::eFAST_INERTIA_COMPUTATION added. When enabled, the inertia tensor is computed faster but with less precision. * PxConvexFlag::eGPU_COMPATIBLE added. When enabled convex hulls are created with vertex limit set to 64 and vertex limit per face is 32. * PxConvexFlag::eSHIFT_VERTICES added. When enabled input points are shifted to be around origin to improve computation stability. * PxCookingParams::gaussMapLimit has been added. The limit can now be fully user-defined. Please refer to the migration guide and best practices sections of the manual. * Changed: * The performance of convex creation from polygons has been improved. * Deprecated: * The PxPlatform enum and the PxGetGaussMapVertexLimitForPlatform function have been deprecated. * Removed: * The deprecated flags PxMeshPreprocessingFlag::eREMOVE_UNREFERENCED_VERTICES and ::eREMOVE_DUPLICATED_TRIANGLES have been removed. Meshes get cleaned up by default unless PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH is set. * Fixed: * Mesh cooking was sometimes crashing for meshes with less than 4 triangles. This has been fixed. * Cooking convex mesh from a flat input mesh produced incorrect large mesh. ## Extensions * Added: * PxRaycastCCD has been added, to improve the visibility of the raycast-based CCD solution, which was previously only available in the Sample framework. This is a simpler and potentially cheaper alternative to the SDK's built-in continuous collision detection algorithm. * PxFindFaceIndex has been added. The function computes the closest polygon on a convex mesh from a given hit point and direction. * Changed: * Memory churn of PxDefaultMemoryOutputStream has been reduced. * The signatures for the PxComputeMeshPenetration and PxComputeHeightFieldPenetration functions have changed. ## Profiling * Changed: * Profiling information is now available only in debug, checked and profile configuration. * PxProfileZoneManager::createProfileZoneManager now takes PxAllocatorCallback as input parameter instead of PxFoundation. ## Physx Visual Debugger * PhysXVisualDebuggerSDK, PvdRuntime projects replaced with PxPvdSDK. * PxPvdSceneClient::drawPoints now takes physx::pvdsdk::PvdDebugPoint as input parameter instead of PxDebugPoint. drawLines, drawTriangles, drawText and so on. * The SDK's Debug visualization data is not sent to PVD anymore in ePROFILE mode. * PxPvdSceneFlag::eTRANSMIT_CONTACTS (instead of PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS) was sometimes incorrectly used to control the transmission of constraint-related data. This has been fixed. In addition, the PxPvdSceneFlag flags are now consistently ignored when PxPvdInstrumentationFlag::eDEBUG is not set. ## Aggregates ## Snippets * Snippet profile zone has been removed. # v3.3.4 October 2015 ## Supported Platforms ## Runtime * Apple iOS * Apple Mac OS X * Google Android ARM & x86 (version 2.2 or later required for SDK, 2.3 or later required for samples) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver version R304 or later is required for GPU acceleration) * Microsoft Windows RT (formerly known as Windows on ARM) (SDK only, no samples yet) * Microsoft XBox One (SDK only, no samples) * Microsoft XBox 360 * Nintendo Wii U * Sony Playstation 3 * Sony Playstation 4 (SDK only, no samples) * Sony Playstation Vita ## Development * Microsoft Windows XP or later * Microsoft Visual Studio 2012, 2013 and 2015 * Xcode 6.3 ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ## General * Added support for Microsoft Visual Studio 2015 for Windows builds. Note that the GPU features are not currently supported with Visual Studio 2015. * Removed support for Microsoft Visual Studio 2010 * Added support for Android platform API Level 16 and removed support for platform API Level 8 and 9. * Fixed: * Fixed a bug in aggregates that led to a crash when rigid bodies are added to an aggregate after removing all rigid bodies from an aggregate. This only occurred with aggregates that were added to the scene and with rigid bodies that had shapes attached. ## Rigid Bodies * Fixed: * Creating a PxConstraint or using PxConstraint::setActors() could cause a crash in situations where one of the two newly connected actors was part of a previously simulated graph of connected constraints (with some of them having projection enabled, i.e., PxConstraintFlag::ePROJECT_TO_ACTOR0 or ::ePROJECT_TO_ACTOR1 set). * PxD6Joint::getTwist(), getSwingY(), getSwingZ() returned incorrect angle values when the corresponding components of the quaternion were negative * The thickness of a heightfield was incorrectly applied when the heightfield transform had a non-identity quaternion. * PxD6Joint angular projection now functions correctly when there is one free axis and it is not the twist axis. * The bounding box of a shape was not always properly updated when the contact offset changed. * Fixed an edge case bug in PCM contact gen that could result in a QNAN reported as the contact point. * Fixed an uninitialized variable bug in the GJK algorithm resulting in uninitialized closest points reported. * Fixed an edge case in which the constraint solver could access invalid memory in constraint partitioning. * Fixed a bug in capsule vs heightfield contact generation that could produce incorrect penetration depths. * Fixed a bug in Unified MTD code path which transformed the normal twice for the polygon index calculation. * Fixed a crash in height fields when a capsule collided with an edge whose shared triangles had a hole material. ## Serialization * Fixed: * PxTriangleMesh instances with adjacency information were not correctly initialized when created with cooking.createTriangleMesh. This caused a crash when converting the binary serialized triangle mesh data. ## Scene Queries * Fixed: * Sweeps against scaled meshes. ## Cooking * Fixed: * Mesh cooking was sometimes crashing for meshes with less than 4 triangles. This has been fixed. # v3.3.3 January 2015 ## Supported Platforms ## Runtime * Apple iOS * Apple Mac OS X * Google Android ARM & x86 (version 2.2 or later required for SDK, 2.3 or later required for samples) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver version R304 or later is required for GPU acceleration) * Microsoft Windows RT (formerly known as Windows on ARM) (SDK only, no samples yet) * Microsoft XBox One (SDK only, no samples) * Microsoft XBox 360 * Nintendo Wii U * Sony Playstation 3 * Sony Playstation 4 (SDK only, no samples) * Sony Playstation Vita ## Development * Microsoft Windows XP or later * Microsoft Visual Studio 2010, 2012 and 2013 * Xcode 6.2 ## Known Issues * The combination of releasing an actor and reassigning the actors of any affected joint so that the joint no longer references the released actor will lead to a crash if these operations are performed as buffered calls ie after simulate but before fetchResults. ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ## General * Added support for Microsoft Visual Studio 2013 and removed support for Microsoft Visual Studio 2008. * Where applicable, mutexes on Unix flavored platforms now inherit priority to avoid priority inversion. This is a default behavior of Windows mutexes. * Added arm64 support for the iOS version of the PhysX SDK. * Removed samples from the iOS version of the PhysX SDK. * Fixed: * x64 samples running on Windows 8. * Concurrent calls to PxPhysics::(un)registerDeletionListener() and PxPhysics::(un)registerDeletionListenerObjects() were not safe. * PxGeometryQuery::pointDistance() could sometimes read uninitialized memory. This has been fixed. * The SDK will not crash anymore if an object is involved in more than 65535 interactions. Instead, it will emit an error message and the additional interactions will be ignored. * The PxPhysics::getMaterials() function did not work with a non-zero 'startIndex' parameter. This has been fixed. * The following static Android libs are now packed into a single library called PhysX3: LowLevel, LowLevelCloth, PhysX3, PhysXProfileSDK, PhysXVisualDebuggerSDK, PvdRuntime, PxTask, SceneQuery and SimulationController. This fixes cyclic dependencies between these libraries. * FSqrt(0), V4Sqrt(0), V4Length(0) and V3Length(0) will return 0 instead of QNan in Android and iOS. ## Rigid Bodies * Fixed: * The Prismatic joint limit now acts correctly when its frame is not the identity. * Calling PxRigidDynamic::setGlobalPose() with the autowake parameter set to true could result in an assert when the rigid body got released and had the PxActorFlag::eDISABLE_SIMULATION flag set. * Added errors on misuse of PxRegister[Unified]Heightfields() function, and documented it. * PxConstraint has a eDISABLE_PREPROCESSING flag and minResponseThreshold attribute to assist in stabilizing stiffness caused by infinite inertias or mass modification. * Island manager performance in the presence of large numbers of kinematic actors has been improved. * Using PxConstraint::setActors() or PxJoint::setActors() could cause a crash if the new actors resulted in the constraint/joint being removed from the scene. * The functions PxRigidActor::setGlobalPose and PxShape::setLocalPose failed to update cached contact data internal to PhysX. This led to contacts being generated with transforms that were no longer valid. Similarly, contacts could be missed due to transforms being invalid. This defect affected the classes PxRigidStatic and PxRigidDynamic, though it was more immediately noticeable with the PxRigidStatic class. * The sphere-vs-mesh contact generation code has been improved. It could previously generate wrong contacts. This has been fixed. * The capsule-vs-convex contact generation had a bug that could lead to rare invalid contacts. This has been fixed. * The mesh contact generation had a bug on PS3 that could lead to invalid contacts. This has been fixed. * The PxRigidBody::clearForce() and PxRigidBody::clearTorque() were not properly decoupled - they both cleared the force and the torque. This has been fixed. * Repeatedly calling PxRigidActor::attachShape and PxRigidActor::detachShape in between calls to simulate resulted in a memory leak. This has been fixed. * Added: * Enabling CCD on kinematic actors is now disallowed. When the kinematic flags are raised on a CCD-enabled actor, CCD is automatically disabled. ## Particles * Fixed: * Consistency between GPU and CPU particles has been improved in the case of a spatial date structure overflow. The positions and velocities of particles that have the PxParticleFlag::eSPATIAL_DATA_STRUCTURE_OVERFLOW set are now updated also for CPU particles. * Fixed potential deadlocks from occurring in the GPU particle kernels running on GM204 and above GPUs. * Fixed fluid simulation crash on Titan X. ## Cloth * Fixed: * A bug related to hitting the sphere or plane limit while world collision is enabled has been fixed. * PxCloth::getParticleAccelerations() implementation was fixed for GPU cloth. ## Character controller * Fixed: * Character controllers cannot stand on dynamic triggers anymore. * Added: * added lockingEnabled parameter to PxCreateControllerManager(), to support thread-safe release of objects while the character controller's move() routine is executing. ## Scene Queries * Fixed: * Raycasts against triangle meshes with large scales potentially failed to register a hit. * Overlaps against height field meshes with the flag eNO_BOUNDARY_EDGES potentially failed to register a hit. * Sweeps using shapes modelled around a space significantly offset from their geometric center could fail to register a hit. ## Vehicles * Fixed: * Sticky tire friction was unreliable with more than one substep but is now fixed. This defect led to vehicles sliding down slopes where the sticky friction should have held firm. * An error in the jounce speed calculation that led to lift force at high forward speeds has been fixed. This defect led to instabilities at high speed. * Improved documentation for PxVehicleSuspsensionData::mSprungMass. ## Cooking * Fixed: * Convex meshes generated from PhysX 3.2 were not able to load inside PhysX 3.3. # v3.3.2 September 2014 ## Supported Platforms ### Runtime * Apple iOS * Apple Mac OS X * Google Android ARM & x86 (version 2.2 or later required for SDK, 2.3 or later required for samples) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver version R304 or later is required for GPU acceleration) * Microsoft Windows RT (formerly known as Windows on ARM) (SDK only, no samples yet) * Microsoft XBox One (SDK only, no samples) * Microsoft XBox 360 * Nintendo Wii U * Sony Playstation 3 * Sony Playstation 4 (SDK only, no samples) * Sony Playstation Vita ### Development * Microsoft Windows XP or later * Microsoft Visual Studio 2008, 2010, 2012 (Windows RT only) * Xcode 4.6|5.0|5.0.1 ## Known Issues * The combination of releasing an actor and reassigning the actors of any affected joint so that the joint no longer references the released actor will lead to a crash if these operations are performed as buffered calls ie after simulate but before fetchResults. ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ### General #### Added: * The PhysXCommon/64.dll, nvcuda.dll and PhysXUpdateLoader/64.dll are loaded and checked for the NVIDIA Corporation digital signature. The signature is expected on all NVIDIA Corporation provided dlls. The application will exit if the signature check fails. * Added the PxDefaultBufferedProfiler extension for simplified SDK profile events extraction. * PxSceneDesc::sanityBounds allows a bounding box to be set for validating the position coordinates of inserted or updated rigid actors and articulations. * Linux: Now supports GPU PhysX. * Added set/getRunProfiled() for PxDefaultCpuDispatcher to control profiling at task level. * Android: Support for x86 based devices was added. * PxProfileEventHandler::durationToNanoseconds() added. Translates event duration in timestamp (cycles) into nanoseconds. * Added SnippetProfileZone to show how to retrieve profiling information. * Added SnippetCustomJoint to better illustrate custom joint implementation, and removed SnippetExtension. * Added SnippetStepper to demonstrate kinematic updates while substepping with tasks. #### Fixed: * PxTask::runProfiled() now takes threadId as a parameter. * The static pruner now issues a performance warning in debug and checked configurations when a tree rebuild occurs and the tree is not empty. * PxSceneDesc::staticStructure now defaults to PxPruningStructure::eDYNAMIC_AABB_TREE. * Linux: Switched to shared libraries. * Profile zone event names changed to match function calls. * Overlapping read/write errors will now issue a PxErrorCode::eINVALID_OPERATION rather than PxErrorCode::eDEBUG_INFO. * Improved SnippetToleranceScale to better demonstrate the intended use case. * Increased 126 characters limit for warnings on unix platforms, 1k limit on all platforms. * PhysXCommon dll load within PhysX dll now respects dll name. Please see the manual's PhysXCommon DLL load section. * Significant revision of the user's guide. Both structure and most content have been modified. * Fixed search function of user's guide. * Foundation math classes now have in-place arithmetic operators (+= etc). * PxScene::checkResults() no longer counts as a read API method. Hence it is now possible to call this method in blocking mode without causing all writes to block until it returns. #### Deprecated: * Indexing operators taking signed integers in PxVec3, PxVec4, PxMat33, PxMat44, PxStrideIterator have been deprecated. ### Rigid Bodies #### Fixed: * A minor bug in contact generation between capsules and triangle meshes has been fixed, reducing the amount of tunneling cases when CCD is not used. * Discrete contact reports are no longer produced for pairs without PxPairFlag::eDETECT_DISCRETE_CONTACT raised in the filter shader. Previously, discrete contact generation would always have been performed regardless of the presence of the PxPairFlag::eDETECT_DISCRETE_CONTACT flag. This change potentially improves performance when using specific shapes for CCD-only collision, which would have previously generated discrtete contacts and then ignored them in the solver. * Trigger reports are no longer produced for pairs without PxPairFlag::eDETECT_DISCRETE_CONTACT raised in the filter shader. PxPairFlag::eTRIGGER_DEFAULT has been modified to include the PxPairFlag::eDETECT_DISCRETE_CONTACT flag. * An incorrect PX_DEPRECATED annotation on the default constructor for PxD6JointDrive has been removed. * PxRigidDynamic::getKinematicTarget() returned a wrong transform if the actor center of mass pose was different from the actor global pose. * Switching a PxRigidDynamic from dynamic to kinematic did not properly suppress existing pairs which turned into kinematic-kinematic or kinematic-static pairs. * PxRigidDynamic::isSleeping() did not return the correct value on the frame the object got inserted if PxScene::addActors() was used and if the object was awake. * PxSceneFlag::eDISABLE_CONTACT_CACHE now correctly works on PS3/SPU. * If an object was added to the scene, put asleep and had overlap with another sleeping object then contact points for that pair might not have been reported once the object woke up. * Potential crash when calling PxScene::resetFiltering() multiple times for the same actor while the simulation was running has been fixed. * Potential crash when using PxScene::resetFiltering() with shapes that were just added while the simulation was running has been fixed. * A crash in MBP when deleting an object that just went out of broad-phase bounds has been fixed. * A new drive mode has been added to drive articulation joints using rotation vectors. * In contact and trigger reports, the shape references in PxTriggerPair and PxContactPair might not have been properly marked as removed shapes if the removal took place while the simulation was running. * PxPairFlag::eSOLVE_CONTACT is now properly observed if the flag is not set on a contacting pair. A consequence of this fix is that sleeping actors will no longer be woken up due to contact or lost contact with awake actors if PxPairFlag::eSOLVE_CONTACT is not set for the pair. This also affects kinematic-kinematic pairs if one kinematic of the pair moves out of contact with the other. Behaviour is unaffected for any pair that has PxPairFlag::eSOLVE_CONTACT set. * A memory leak with buffered shape and actor removal has been fixed. The memory leak occurred when the release of an actor's shapes was followed by the release of the actor, all in-between simulate() and fetchResults(). * A bug was fixed which caused incorrect force reports to sometimes be reported. * Fixed a bug where incorrect normals were reported when using PCM contact gen. * Fixed some issues with scaled convex hulls in the PCM contact gen code path. * The accuracy of capsule collision code has been improved. * An isValid() method has been added to constraints, that is satisfied if and only if at least one actor is a dynamic body or articulation link * A check has been added to prevent constraint construction or modification that would leave the constraint invalid. * In checked builds the PxScene methods addActor(), addActors(), addAggregate() and addCollection() will warn and return if an invalid constraint would be added to the scene #### Deprecated: * The following flags have been renamed and deprecated because the name did not properly reflect the root cause. * PxContactPairHeaderFlag * eDELETED_ACTOR_0 (use eREMOVED_ACTOR_0 instead) * eDELETED_ACTOR_1 (use eREMOVED_ACTOR_1 instead) * PxContactPairFlag * eDELETED_SHAPE_0 (use eREMOVED_SHAPE_0 instead) * eDELETED_SHAPE_1 (use eREMOVED_SHAPE_1 instead) * PxTriggerPairFlag * eDELETED_SHAPE_TRIGGER (use eREMOVED_SHAPE_TRIGGER instead) * eDELETED_SHAPE_OTHER (use eREMOVED_SHAPE_OTHER instead) ### Vehicles #### Added: * In profile config the functions PxVehicleUpdates, PxVehiclePostUpdates and PxVehicleSuspensionRaycasts are now tracked with profile events (provided that a PxProfileZoneManager instance was passed to PxCreatePhysics). These profile events can be viewed in profile view in pvd, where the names of the profile events match the names of the tracked vehicle functions. #### Fixed: * In checked config PxVehicleDriveTank::allocate enforces the rule that only tanks with even numbers of wheels are legal and warns when this rule is broken. * In checked config PxVehicleDrive4W::allocate enforces the rule that only vehicles with 4 wheels or more are legal and warns when this rule is broken. * PxWheelQueryResult::localPose was incorrectly only set when the vehicle had a corresponding PxShape, as described by PxVehicleWheelsSimData::setWheelShapeMapping. The localPose is now properly set independent of the mapping between wheel and shape. * Wheels resting on moving actors now properly observe the relative speed of the two actors when their relative speed is small. This fixes a bug where at small relative speeds the velocity of the other actor was assumed to be zero. * Repx serialization failed to serialize PxVehicleWheelsSimData::setMinLongSlipDenominator, PxVehicleWheelsSimData::setSubStepCount, PxVehicleWheelsSimData::disableWheel, PxVehicleWheelsSimData::enableWheel and the number of entries in the engine torque curve. These have now been fixed. * PxVehicleConcreteType used for vehicle serialization is now in the public API and has been moved to PxVehicleSDK.h. * Very small longitudinal and lateral slip angles could lead to numerical instabilities in some circumstances. A threshold has been introduced to reject very small slip angles by setting them to zero when they are below the threshold. * Vehicles now account for rigid bodies that have been given a zero inertia component in order to lock rotation around the corresponding axis. * Fixed a bug where the sticky wheel constraints sometimes didn't function correctly. ### Cloth #### Fixed: * The version number written to the fabric stream changed from PX_PHYSICS_VERSION to 1. A fabric can be created from streams written with version 3.3.0 and later until the stream format changes. Previously, the version of the producer and the consumer of the stream needed to match. * GPU cloth friction against convexes has been fixed. * A crash resulting from deleting a shape in proximity of a cloth with scene collision enabled has been fixed. ### Scene Queries #### Fixed: * PxMeshQuery::sweep now respects PxHitFlag::eMESH_BOTH_SIDES, and supports double-sided input triangles. * PxRigidBodyExt::linearSweepSingle and PxRigidBodyExt::linearSweepMultiple now correctly use query filter data instead of simulation filter data if filter data is not provided. * The spec for raycasts whose origin is located inside a solid object (sphere, box, capsule, convex) has changed back to what it was in 3.3.0. It was accidentally changed in 3.3.1. See the manual for details. * Convex sweeps against heightfields worked only when the heightfield had the identity transform. This has now been fixed to support arbitrary transforms again. ### Cooking #### Added: * Using PxMeshPreprocessingFlag::eFORCE_32BIT_INDICES will always cook meshes with 32-bit triangle indices. #### Fixed: * Convex hull cooking fix. Some input points could be ignored during cooking, fixed. * Inserted triangle meshes now respect 16 bit indices flag. ### Geometry #### Fixed: * PxHeightFieldDesc::thickness is now limited to [-PX_MAX_BOUNDS_EXTENTS, PX_MAX_BOUNDS_EXTENTS range]. (Previously unbounded). ### Particles #### Fixed: * Setting PxParticleReadDataFlag::eREST_OFFSET_BUFFER on a PxParticleBase instance that was not created with the per particle rest offset option (see PxPhysics::createParticleSystem, PxPhysics::createParticleFluid and PxParticleBaseFlag::ePER_PARTICLE_REST_OFFSET) is not supported. The unsupported configuration may have resulted in crashes. The SDK now rejects this configuration on calling PxParticleBase::setParticleBaseFlag and issues an appropriate warning to the error stream. * Performance improvements on Kepler and above GPUs running SPH. * In rare cases particle systems could access released memory when all interactions with a rigid body shape were lost. ### Serialization #### Fixed: * PxBinaryConverter::convert potentially failed in checked mode with allocators that don't set 0xcd pattern. This has been fixed now. # v3.3.1 December 2013 ## Supported Platforms ### Runtime * Apple iOS * Apple Mac OS X * Google Android (version 2.2 or later for SDK, 2.3 or later required for samples) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver version R304 or later is required for GPU acceleration) * Microsoft Windows RT (formerly known as Windows on ARM) (SDK only, no samples yet) * Microsoft XBox One * Microsoft XBox 360 * Nintendo Wii U * Sony Playstation 3 * Sony Playstation 4 (SDK only, no samples) * Sony Playstation Vita ### Development * Microsoft Windows XP or later * Microsoft Visual Studio 2008, 2010, 2012 (Windows RT only) * Xcode 4.6|5.0|5.0.1 ## Known Issues ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ### General #### Added: * The friction model can now be changed after scene instantiation with PxScene::setFrictionType. The friction model can also be queried with PxScene::getFrictionType. #### Changed: * PxDefaultSimulationFilterShader now supports particles and cloth as well. * PxSimulationFilterCallback: the provided actor and shape pointers are now defined as const. Note: this is no behavior change, it was never allowed to write to those objects from within the callback. * The PxTriangleMeshFlag::eHAS_16BIT_TRIANGLE_INDICES and PxTriangleMeshFlag::eHAS_ADJACENCY_INFO enums have been deprecated. Please use PxTriangleMeshFlag::e16_BIT_INDICES and PxTriangleMeshFlag::eADJACENCY_INFO instead. * Removed following functions from the API for platforms which do not support CUDA: PxGetSuggestedCudaDeviceOrdinal, PxCreateCudaContextManager, PxLoadPhysxGPUModule. #### Fixed: * Fixed concurrency issue on windows. Calling PxScene::simulate on multiple scenes concurrently may have caused a deadlock. This only happened if the scenes shared a single PxCpuDispatcher and the dispatcher was configured to use one worker thread only. ### Rigid Bodies #### Added: * The projection direction for constraints can now be specified through the flags PxConstraintFlag::ePROJECT_TO_ACTOR0, ::ePROJECT_TO_ACTOR1. * A parameter has been added to PxRigidBodyExt::updateMassAndInertia() and ::setMassAndUpdateInertia() to optionally take non-simulation shapes into account for computing the mass and the inertia tensor of a rigid body. * It is now possible to retrieve additional information in contact reports. See the API documentation of PxContactPairHeader.extraDataStream, PxPairFlag::ePRE_SOLVER_VELOCITY, ::ePOST_SOLVER_VELOCITY, ::eCONTACT_EVENT_POSE for details. * The contact report system has been extended to support multiple notification events if the same two objects collide multiple times in multipass CCD scenarios. See the API documentation of PxPairFlag::eNOTIFY_TOUCH_CCD for details. #### Changed: * If touching objects were added to the scene asleep and one of them got woken up, then all contact pairs of the touching objects which contained a static rigid body were resolved with a delay of one simulation step. Now these pairs get resolved without delay in the next simulation step. * If touching objects were added to the scene asleep, eNOTIFY_TOUCH_FOUND contact reports were sent out for pairs of dynamic rigid bodies if requested. These reports will not be sent at the end of the simulation step after insertion anymore but rather at the end of the simulation step after the touching objects have been woken up. * Rigid bodies now permit zeroes in passed to setMass and setMassSpaceInertiaTensor. Zeroes are interpreted to indicate infinite mass or infinite moment of inertia around a given principal axis of inertia. Previously, zeroes were illegal values to these methods. Note that zeroes are still illegal for instances of PxArticulationLink. #### Fixed: * Reading back the kinematic target in the PxSimulationEventCallback::onContact() callback through PxRigidDynamic::getKinematicTarget() will now work. * Contact reports are no longer generated for contact pairs involving two sleeping kinematic actors or for pairs involving a sleeping kinematic actor in contact with a static actor. This fixes a bug that was introduced in 3.3.0. * No PxPairFlag::eNOTIFY_TOUCH_LOST event was sent in contact reports if a pair of sleeping rigid bodies got woken up after setting the pose on one of them (with autowake parameter set to false) and if the bounding boxes of the two objects still overlapped. * No PxPairFlag::eNOTIFY_TOUCH_PERSISTS event was sent in contact reports during the first simulation step after a pair of sleeping rigid bodies got woken up. * The inertia tensor computation for convex meshes has been adjusted to be more stable in certain cases where floating point precision issues arise. Furthermore, a fallback routine has been added to use an approximation if the diagonalized inertia tensor still ends up with invalid entries. * PxRigidBody::clearForce() and ::clearTorque() did not properly clear the respective properties if used with force mode PxForceMode::eIMPULES or PxForceMode::eVELOCITY_CHANGE. * Setting PxSceneFlag::eENABLE_KINEMATIC_STATIC_PAIRS also enabled PxSceneFlag::eENABLE_KINEMATIC_PAIRS internally and vice versa. * Missing validation checks for some joint set() methods have been added. Similarly to other API calls, when validation fails in the checked build PhysX will report an error and return without updating the joint. * Switching a kinematic rigid body to dynamic could lead to a crash in a subsequent simulation step, if the kinematic was moved and connected to another kinematic through a breakable PxConstraint/PxJoint. * Deleting a breakable PxConstraint/PxJoint while the simulation is running could lead to a crash if the PxConstraint/PxJoint broke in the same simulation step. * A bug in the PxScene::addBroadPhaseRegion() function, that could lead to a crash when using 'populateRegion=true', has been fixed. ### Particles #### Added: * Added triangle mesh cache statistics for GPU particles. Triangle mesh cache statistics are also captured by PVD as part of simulation statistics. * Added new option to query approximate particle velocities relative to colliding rigid actors. This can be used for debris rotation on moving objects. Enable with PxParticleReadDataFlag::eCOLLISION_VELOCITY_BUFFER and read from PxParticleReadData::collisionVelocityBuffer. #### Fixed: * Fixed a bug which might lead to GPU particle pipeline failures on low end GPUs. * Enabled warning when a spatial data structure overflow occurred for GPU particles (see the guide for more information). ### Cloth #### Fixed: * PxFilterFlag::eSUPPRESS was ignored for collision pairs that involved a PxCloth object. This does work now, however, please note that PxFilterFlag::eSUPPRESS is treated as PxFilterFlag::eKILL for pairs with a PxCloth object. ### Serialization #### Added: * Support for binary compatibility between different sdk releases and patches has been added (PX_BINARY_SERIAL_VERSION). The current sdk version can load binary data of the older sdk versions listed in the documentation of PX_BINARY_SERIAL_VERSION. * SnippetLoadCollection has been added. It illustrates loading repx or binary serialized collections and instantiating the objects in a scene. It only compiles and runs on authoring platforms (windows, osx and linux). * SnippetConvert has been added. It illustrates how to convert PhysX 3 serialized binary files from one platform to another. It only compiles and runs on authoring platforms (windows, osx and linux). #### Deprecated: * Method PxCollection::addRequire is deprecated, use PxCollection::add and PxCollection::contains instead. * Method PxCollection::createBinaryConverter(PxSerializationRegistry&) is deprecated, use PxCollection::createBinaryConverter() instead. ### Character controller #### Added: * PxControllerManager::setPreventVerticalSlidingAgainstCeiling() has been added, to control the behaviour of characters against ceilings. ### Vehicles #### Added: * Vehicles may now be updated concurrently through the addition of a new function PxVehiclePostUpdates and passing a PxVehicleConcurrentUpdateData array to PxVehicleupdates. * A new snippet SnippetVehicleMultiThreading has been added to show the operation of concurrent vehicle updates. * PxVehicleDriveTankControl and PxVehicleDriveTankControlModel now have improved doxy comments. * A new function PxVehicleUpdateCMassLocalPose has been added to help update a vehicle after the center of mass pose of the vehicle's actor has been modified. * PxWheelQueryResult now records the local pose of the wheel. #### Changed: * PxVehcicleDrive4W::setup now tests that at least 4 wheels are specified and returns wtih an error message if numWheels < 4. It is only possible to create a PxVehicleDrive4W instance with less than 4 active wheels by disabling wheels after instantiating a 4-wheeled car. * In debug and checked build configurations PxVehicleComputeSprungMasses now reports whether the sprung masses were successfully computed. Warnings are passed to the error stream in checked configuration if the function does not complete successfully. Apart from error checking the operation of the function is unchanged. #### Fixed: * The doxy comment describing the default setting for PxVehicleWheelsSimData::setWheelShapeMapping was incorrect. This now correctly documents the default mapping as PxVehicleWheelsSimData::setWheelShapeMapping(i,i). * Suspensions raycasts that start inside geometry are ignored for all geometry types. Prior to this release this was true for all geometry types except for heightfields and triangle meshes. This inconsistency has now been fixed so that all geometry types obey the rule that suspension raycasts starting inside geometry are neglected. ### Scene queries #### Added: * Added eMTD flag. If an initial overlap is detected, this flag triggers the sweep to compute the MTD (Minimum Translation Direction), which can be used to de-penetrate the query shape from the shape with which an initial overlap was found. In this case, the distance reported will be negative. This negative distance can be used to scale the reported normal to generate the translation vector required to de-penetrate the query shape. * Added PxTriangle::pointFromUV. #### Fixed: * A rare ray-capsule intersection bug has been fixed, when the capsule's height is close to zero. * A capsule-capsule distance bug has been fixed, when the tested capsules are large and parallel. * Raycasts against heightfields now correctly return triangle UVs. #### Changed: * PxBatchQuery::raycast, overlap and sweep previously had an incorrect const modifier indicating that these methods were safe to call from multiple threads simultaneously. This has been removed. Multiple batch queries can still be executed (via PxBatchQuery::execute()) in parallel. ### Cooking #### Added: * PxCookingParams::meshSizePerformanceTradeOff parameter can be used to make the mesh smaller at the expense of reduced simulation and scene query performance (or the other way around). * PxCookingParams::meshCookingHint parameter can be used to specify mesh hierarchy construction preference (cooking speed or simulation speed). * PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH disables mesh clean process. Vertices duplicities are not searched, huge triangles test is not done. Vertices welding is not done. Does speed up the cooking. * PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE disables vertex edge precomputation. Makes cooking faster but slow up contact generation. * PxPhysicsInsertionCallback adds the support for inserting cooked triangle mesh or height field directly into PxPhysics without the stream serialization. * PxCooking::createTriangleMesh creates triangle mesh and inserts it to PxPhysics without using the stream serialization. * PxCooking::createHeightField creates height field and inserts it to PxPhysics without using the stream serialization. * PxCooking::validateTriangleMesh validates mesh in separate function before it can be cooked without the mesh cleaning. * PxConvexFlag::eCHECK_ZERO_AREA_TRIANGLES checks and removes almost zero-area triangles during the computation of the convex hull. * PxCookingParams::areaTestEpsilon triangle area size was added. This epsilon is used for the zero-area test in the computation of the convex hull. #### Changed: * PxCooking::computeHullPolygons does now return also vertices used by the polygons. Redundant vertices are removed. * PxCooking::cookConvexMesh now returns a PxConvexMeshCookingResult::Enum with additional error information. ### Aggregates #### Added: * PxSceneLimits has a new member variable maxNbAggregates. Setting this value to a good approximation of the peak number of aggregates will avoid the need for internal run-time allocations that can occur when aggregates are added to the scene. #### Fixed: * PxScene::removeActor will auotmatically remove that actor from all PxAggregate instances that contain the removed actor. Likewise, PxScene::removeArticulation will automatically remove all articulation links from all relevant aggregates. This fix upholds the rule that all actors of an aggregate must be in same scene. * The condition of an internal assert that triggered after calling PxScene::addAggregate has been corrected. This assert triggered when an aggregate was added to the scene after removal of all aggregates from the scene. The operation of the function PxScene::addAggregate is unchanged apart from the asserted condtition. ### Samples #### Changed: * Starting with Release 302 drivers, application developers can direct the Optimus driver at runtime to use the High Performance Graphics to render any application - even those applications for which there is no existing application profile. The samples now make use of this feature to enable High Performance Graphics by default. # v3.3 September 2013 ## Release Highlights * Added PhysXDevice/64.dll to the PC packages. See the Windows readme for details. * Added support for the NVIDIA Kepler GPU architecture. * Added support for the Nintendo Wii U console. * Added support for Windows 8 Modern UI applications (ARM and x86). * Ported our SIMD library to the ARM NEON architecture. * Multi Box Pruning (MBP) is offered as an alternative broad phase algorithm to Sweep And Prune (SAP). MBP shows improved performance when most objects are moving or when inserting large numbers of objects. SAP can be faster in scenarios with few moving (many sleeping) objects. * Significant performance and stability optimizations for rigid body solver. * New function to compute the minimum translational distance and direction to separate two overlapping geometry objects. * New 'PCM' contact generation mode which is often faster and more robust than the still available legacy path. * Improved performance of scene queries and contact reports. * Improved behavior and performance of Continuous Collision Detection (CCD). * Reduced memory footprint of rigid body classes. * Added support for sharing shapes among rigid bodies. * Significantly improved cloth behavior and GPU performance. * Added support for cloth colliding against itself, other cloth instances, and scene geometry. * Improved useability of binary and xml serialization. * Memory can be saved for objects that do not participate in the simulation and are used for scene queries only. For details see the new flag PxActorFlag::eDISABLE_SIMULATION. ## Supported Platforms ### Runtime * Apple iOS * Apple Mac OS X * Google Android (version 2.2 or later for SDK, 2.3 or later required for samples) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver version R304 or later is required for GPU acceleration) * Microsoft Windows RT (formerly known as Windows on ARM) (SDK only, no samples yet) * Microsoft XBox One * Microsoft XBox 360 * Nintendo Wii U * Sony Playstation 3 * Sony Playstation 4 (SDK only, no samples yet) * Sony Playstation Vita ### Development * Microsoft Windows XP or later * Microsoft Visual Studio 2008, 2010, 2012 (Windows RT/PS4/XboxOne only) * Xcode 4.6 ## Known Issues * PxSimulationOrder::eSOLVE_COLLIDE feature is not implemented in this release. Calls to PxScene::solve() and PxScene::collide() will be ignored with a warning added to the error stream * Reading back the kinematic target through PxRigidDynamic::getKinematicTarget() in the PxSimulationEventCallback::onContact() callback will fail. * Cloth self-collision without rest position is not supported on GPUs with SM capability lower than 2.0. ## Changes and Resolved Issues <i>Note: Platform specific issues and changes can be found in the readme file of the corresponding platform.</i> ### General #### Added: * PxScene::setLimits: Hint to preallocate capacities of various data structures. See PxSceneLimits. * Scalar constructors PxQuat(r), PxMat33(r), PxMat33(r). * identity constructors for PxMat33, PxMat44, PxQuat, PxTransform - e.g. PxTransform(PxIdentity). * zero constructors for PxMat33, PxMat44, PxVec3 - e.g. PxMat33(PxZero). * PxTransform(x, y, z) constructor was added as a shortcut for PxTransform(PxVec3(x,y,z)). * The GPU code uses CUDA version 5.0 and supports Kepler GPUs (SM version 3.0 and 3.5). * Helper method PxContactPair::bufferContacts() has been added to copy the contact pair data stream into a user buffer. * PxGeometryQuery::computePenetration() has been added, to compute the Minimum Translational Distance between geometry objects. * Ability for APEX and other PhysX extensions to change the PhysX Visual Indicator. * Reporting allocation names can now be enabled or disabled (see PxFoundation::setReportAllocationNames). When enabled, some platforms allocate memory through 'malloc'. * The scene origin can now be shifted to better support big world scenarios. See PxScene::shiftOrigin() for details. * PxAssertHandler got extended with a boolean parameter to support ignoring specific asserts. See windows implementation of DefaultAssertHandler. * Added new PxPairFlags - PxPairFlag::eSOLVE_CONTACT and PxPairFlag::eDETECT_DISCRETE_CONTACT. #### Removed: * The obsolete PxConvexFlag::eUSE_UNCOMPRESSED_NORMALS flag has been removed. * The PxSceneFlag::eDISABLE_SSE was obsolete, and has now been removed. * The obsolte PxPtrArray has been removed #### Changed: * Mesh BVH construction was significantly improved for meshes with a mix of large and small triangles. Mesh sizes are now slightly increased, but traversals are substantially faster. As a side effect, cooked mesh format has changed. This requires meshes to be recooked! * The specification for valid PxBounds3 representations has changed. See the API documentation for details (especially the newly introduced PxBounds3::isValid() method). * PxBounds3::transform(), ::scale() and ::fatten() have been split into a fast and a safe version to avoid unnecessary checks and improve stability for empty bounds respectively. * PxBounds3::setInfinite() has been renamed to PxBounds3::setMaximal() to better fit the actual behavior. * PxTask: PVD profile events for tasks are now only emitted in profile builds (all platforms). * Platform mutex implementations now verify that lock/unlock come from correct thread in debug builds. * PxWindowsDelayLoadHook.h has been moved from Include/foundation/windows to Include/common/windows. * API instances of 'Num' as in 'maxNum' and 'getNum' have changed uniformly to 'Nb'. * The following classes have been renamed: * PxSceneQueryHit to PxQueryHit * PxSceneQueryFlags to PxHitFlags * PxSceneQueryHitType to PxQueryHitType * PxSceneQueryFilterData to PxQueryFilterData * PxSceneQueryFilterCallback to PxQueryFilterCallback * PxSceneQueryFilterFlags to PxQueryFlags * PxSceneQueryCache to PxQueryCache * PxCCTNonWalkableMode to PxControllerNonWalkableMode * PxControllerFlags to PxControllerCollisionFlags * PxCCTHit to PxControllerHit * PxConstraintDominance to PxDominanceGroupPair * PxActorTypeSelectionFlags to PxActorTypeFlags * PxFindOverlapTriangleMeshUtil to PxMeshOverlapUtil * The previous names have been retained for compatibility but are deprecated. * PX_SLEEP_INTERVAL has been replaced with the new parameter PxSceneDesc::wakeCounterResetValue to specify the wake counter value to set when wakeUp() gets called on dynamic objects. * PxClientBehaviorBit has been renamed PxClientBehaviorFlag, PxActorClientBehaviorBit has been renamed PxActorClientBehaviorFlag. Names of related functions have also changed. * queryClient parameter in raycast(), sweep(), overlap() functions was moved inside of PxQueryFilterData struct. * The PxObserver/PxObservable system has been replaced by the PxDeletionListener API. The supported object types have been extended from PxActor to all core objects inheriting from PxBase. Furthermore, two kinds of deletion events are now distinguished: user release and memory release. Please read the API documentation for details. * Deprecated PxPairFlag::eRESOLVE_CONTACT. Use PxPairFlag::eDETECT_DISCRETE_CONTACT and PxPairFlag::eSOLVE_CONTACT instead. * Number of materials per shape is now PxU16 instead of PxU32, contact material information also now returns PxU16. * Maximum number of touching hits in batched queries is now PxU16 instead of PxU32. * SweepEpsilonDistance has been replaced by meshContactMargin and marked as deprecated. Please read the API documentation for details. * PxShape::resetFiltering() and PxParticleBase::resetFiltering() have been deprecated. Please use one of the new overloaded methods PxScene::resetFiltering() instead. * The pxtask namespace has been removed and it's types have been added to the physx namespace with a Px* prefix * The delay load hook PxDelayLoadHook::setPhysXInstance has been renamed to PxSetPhysXDelayLoadHook and PxDelayLoadHook::setPhysXCookingInstance has been renamed to PxSetPhysXCookingDelayLoadHook #### Fixed: * Calling Thread::setAffinityMask() before the thread has been started is now supported. * PxDefaultSimulationFilterShader ignored the value of the second filter constant in the collision filtering equation and used the value of the first filter constant instead. #### Deprecated: * The PxScene::flush() method has been deprecated, please use PxScene::flushSimulation(). * PxRigidDynamicFlag has been deprecated and replaced with PxRigidBodyFlag to allow flags to be shared between PxArticulationLink and PxRigidDynamic. * PxTransform::createIdentity(), PxQuat::createIdentity(), PxMat33::createIdentity(), PxMat44::createIdentity(), PxMat33::createZero(), PxMat44::createZero() ### Character controller #### Added: * The PxControllerBehaviorFlag::eCCT_USER_DEFINED_RIDE flag has been added. * A new helper function PxController::resize() has been added to facilitate character controller resizing. * A new runtime tessellation feature has been added that can help reducing FPU accuracy issues in the sweep tests. * PxControllerFilterCallback has been added to make CCT-vs-CCT filtering more flexible. * An overlap recovery module has been added. See PxControllerManager::setOverlapRecoveryModule * PxObstacle notifications has been added to handle touched obstacles. * PxObstacleContext::getObstacleByHandle has been added. * The origin of character controllers and obstacles can now be shifted to stay in sync when the origin of the underlying PxScene is shifted. See PxControllerManager::shiftOrigin() for details. #### Changed: * The PxControllerManager is now tightly coupled to a PxScene which has to be provided on creation. See PxCreateControllerManager(). * The PxObstacleContext instances of a PxControllerManager will now get released automatically when the manager is released. * PxController::reportSceneChanged() has been renamed to PxController::invalidateCache(). * PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT is not the default behavior anymore. * PxCCTNonWalkableMode::eFORCE_SLIDING has been renamed to PxCCTNonWalkableMode::ePREVENT_CLIMBING_AND_FORCE_SLIDING. * PxCCTInteractionMode has been renamed PxControllerInteractionMode * PxCCTNonWalkableMode has been renamed PxControllerNonWalkableMode * PxCCTHit has been renamed PxControllerHit * Touched PxObstacle has been replaced by touched ObstacleHandle. * PxControllerInteractionMode and PxControllerFilters::mActiveGroups have been removed. Please use the new PxControllerFilterCallback instead. #### Fixed: * Bugs with respect to deleting shapes from a touching actor have been fixed. * Touched actor's scene is checked in CCT::move before rideOnTouchedObject is called to ensure that the touched shape is valid. * Touched shape's scene query flag is checked in CCT::move before rideOnTouchedObject is called to ensure that the touched shape is valid. * Touched shape's user CCT filtering is triggered in CCT::move before rideOnTouchedObject is called to ensure that the touched shape is valid. * The PxControllerBehaviorCallback was not called when a PxUserControllerHitReport was not defined. * It is not possible anymore to create a CCT whose contact offset is zero. The doc has always said a non-zero value was expected, but corresponding check was missing. * Box & capsule controllers' resize function now properly take the up direction into account ### CCD #### Added: * Introduced PxRigidBodyFlag::eENABLE_CCD_FRICTION to control whether friction is applied inside CCD on a given body. This is disabled by default. In general, disabling friction in CCD improves the behavior of high-speed collisions. * Introduced PxSceneDesc::ccdMaxPasses field, which controls the maximum number of CCD passes. Each CCD pass will advance each object to its next TOI. By default, we use 1 pass. Increasing the number of passes can reduced the likelihood of time being dropped inside the CCD system at the cost of extra CCD procesing overhead. * Introduced per-body value to control how far past the initial time of impact the CCD advances the simulation. Advancing further can improve fluidity at the increased risk of tunneling. * CCD now has limited support contact modification. It supports disabling response to contacts by setting max impulse to 0. It does not yet support target velocity, non-zero max impulse values or scaling mass or inertia. * Introduced new PxPairFlag eDETECT_CCD_CONTACT. This flags is used to control whether CCD performs sweep tests for a give pair. Decision over whether any collisions are responded to is made by the presence of the flag eSOLVE_CONTACT. #### Removed: * CCD is now enabled per-body instead of per-shape. As a result, PxShapeFlag::eUSE_SWEPT_BOUNDS has been removed and replaced with PxRigidBodyFlag::eENABLE_CCD. #### Changed: * API attributes previously named SWEPT_INTEGRATION have now been renamed 'ccd': specifically PxSceneFlag::eENABLE_SWEPT_INTEGRATION, PxSceneFlag::eSWEPT_INTEGRATION_LINEAR, PxSceneDesc::sweptIntegrationLinearSpeedFactor, PxSceneDesc::sweptIntegrationAngularSpeedFactor, PxPairFlag::eENABLE_SWEPT_INTEGRATION * PxPairFlag::eCCD_LINEAR has been deprecated. Use (PxPairFlag::eDETECT_CCD_CONTACT | PxPairFlag::eSOLVE_CONTACT) instead. #### Fixed: * Updated CCD algorithm which improves the fluidity of motion of the CCD system while reducing the processing overhead significantly. * Contact notification is now reliable in CCD. CCD contacts are appended to the end of the contact list for a given pair so that both discrete and continuous contacts are reported * CCD contact notification now reports applied forces. These contacts will be correctly filtered by force thresholds. ### Serialization #### Added: * Added extension PxSerialization::isSerializable method to query whether a collection is serializable. * Added extension PxSerialization::complete which allows to prepare a collection for serialization. * Added extension PxSerialization::createNames which adds reference names to serializables. * Added extension PxCollectionExt::remove which removes all serializables of a certain type and optionally adds them to another collection. * Added extension function PxCollectionExt::releaseObjects to remove and release objects from a collection * Added class PxSerializationRegistry for handling custom serializable types. * Added PxSerialization::serializeCollectionToXml and PxSerialization::createCollectionFromXml * Included pre-built binary meta data with SDK at [path to installed PhysX SDK]/Tools/BinaryMetaData * Added class PxSerializer to provide serialization specific functionality to serializable classes. * Added classes PxSerializationContext and PxDeserializationContext to provide functionality for serialization and deserialization operations. #### Removed: * Removed PxUserReferences class and PxPhysics::createUserReferences. * Removed RepX.h and unified serialization interfaces for xml and binary serialization. #### Changed: * PxCollection was reworked to improve reference management rendering PxUserReferences obsolete. PxCollection was also decoupled more from Serialization/Deserialization functionality. Serialization of incomplete collections fails now early at serialization as opposed to late at deserialization. * Replaced PxPhysics::createCollection with PxCreateCollection. * Replaced RepXCollection with PxCollection, and unified corresponding interfaces. * Replaced PxCollection::serialize with PxSerialization::serializeCollectionToBinary. * Replaced PxCollection::deserialize with PxSerialization::createCollectionFromBinary. * Replaced PxSerializable::collectForExport(PxCollection& c) with PxSerializer::requires. The new method works in a non-recursive way. * Replaced PxDumpMetaData with PxSerialization::dumpMetaData. * Replaced PxCollectForExportSDK with PxCollectionExt::createCollection(PxPhysics& sdk). * Replaced PxCollectForExportScene with PxCollectionExt::createCollection(PxScene& scene). * Moved PxCooking::createBinaryConverter to PxSerialization * Changed PxShape release semantics for shapes. As a consequence deserialized shapes are never autmatically released, but need to be released by the application. Exception: PxPhysics::release. ### Cloth #### Added: * Improved GPU cloth performance significantly with new parallel solver. * Added tether constraints, which allow minimum amount of cloth stretching even for large gravity scales. See PxClothFabric. * Added support for dynamic addition and deletion of collision primitives. See PxCloth::addCollision* and PxCloth::removeCollision*. * Added triangle mesh collider support. See PxCloth::setCollisionTriangles. * Added support for self collision and inter-cloth collision. See PxCloth::setSelfCollision*() and PxScene::setClothInterCollision*(). * Added direct access to CUDA particle data for graphics interoperability, see PxCloth::lockParticleData() * Added PxRegisterCloth to reduce binary size by stripping unused code on platforms where static linking is used. * Added methods setWakeCounter/getWakeCounter() (see the corresponding API documentation for details). * It is illegal to call wakeUp/putToSleep/isSleeping() on a PxCloth that has not been added to a scene. #### Changed: * Cloth solver does not use fibers any more. See PxClothFabric for changes in fabric API. * Moved PxCooking.cookClothFabric() to extensions. See PxClothFabricCooker and PxClothFabricCreate. * PxClothMeshDesc has been moved to extensions and now supports both triangle and quad representations. See PxClothMeshDesc. * The scaling of damping and stiffness coefficients has been separated from the solver frequency and can now be set indepedently using PxCloth::setStiffnessFrequency(). * PxCloth::setInertiaScale() has been split into linear, angular, and centrifugal components. See PxCloth::set*IntertiaScale. * Drag coefficient has been split into linear and angular coefficient. See PxCloth::setLinearDragCoefficient and PxCloth::setAngularDragCoefficient. * Renamed PxCloth::lockClothReadData() to lockParticleData(). Added support for update operations on the returned particle arrays (as an alternative to setParticles()). * PxCloth::wakeUp() does not have a parameter anymore. Use setWakeCounter() instead to set a specific value. * PxCloth::getNbCollisionSpherePairs() has been renamed to PxCloth::getNbCollisionCapsules() #### Fixed: * Fixed a crash bug in the clothing collision code appearing on iOS. ### Rigid Bodies #### Added: * The contact distance parameter for a limit is automatically estimated if not supplied in the constructor for the limit structure. * The new callback PxConstraintConnector::onOriginShift() has been introduced. It gets called for all constraints of a scene, when its origin is shifted. * New helper function PxRigidBodyExt::computeVelocityDeltaFromImpulse has been added. * Shapes may be declared as shared on creation, and then attached to multiple actors, see the user manual for restrictions. * Since a shape is no longer necessarily associated with a unique actor, references to shapes in callbacks from the engine are accompanied by the a reference to the associated actor * Joints and contact modification now support tuning relative mass and inertia for the bodies on a per-contact basis. Inertia and mass can be tuned independently. #### Removed: * PxShape::overlap(), PxShape::sweep() and PxShape::raycast() have been removed. Equivalent functionality is provided in PxGeometryQuery. #### Changed: * It is illegal to call resetFiltering() on a PxShape or PxParticleBase if they have not been added to a scene. * It is illegal to call addForce/addTorque/clearForce/clearTorque() on a PxRigidBody that has not been added to a scene. * The sleep behavior of dynamic rigid bodies has changed significantly (for details on the current behavior see the API documentation of isSleeping(), wakeUp(), putToSleep(), setKinematicTarget(), PxRigidBodyFlag::eKINEMATIC, ...). Among the changes are: * The methods setWakeCounter/getWakeCounter() have been added for PxRigidDynamic and PxArticulation objects (see the corresponding API documentation for details). * The wakeUp() method of PxRigidDynamic and PxArticulation has lost the wake counter parameter. Use setWakeCounter() instead to set a specific value. * It is illegal to call wakeUp/putToSleep/isSleeping() on a PxRigidDynamic or PxArticulation that has not been added to a scene. * Putting a dynamic rigid actor to sleep will clear any pending force updates. * Switching a dynamic actor to kinematic will put the actor to sleep immediately. * Switching a kinematic actor back to dynamic will not affect the sleep state (previously the actor was woken up). * Calling wakeUp/putToSleep() on a kinematically controlled dynamic actor is not valid any longer. The sleep state of a kinematic actor is solely defined based on whether a target pose has been set (see API documentation of isSleeping() for details). * A call to PxRigidBody::setCMassLocalPose() does not wake up the actor anymore. Note: this also affects related methods in PhysXExtensions like PxRigidBodyExt::updateMassAndInertia() etc. * If a non-zero velocity or force is set through PxRigidBody::setLinearVelocity(), ::setAngularVelocity(), ::addForce() or ::addTorque(), the actor will get woken up automatically even if the autowake parameter is false. * PxRigidBody::clearForce() and ::clearTorque() do not have the autowake parameter, to optionally wake the actor up, anymore. These methods will not change the sleep state any longer. Call ::wakeUp() subsequently to get the old default behavior. * Adding or removing a PxConstraint/PxJoint to/from the scene does not wake the connected actors up automatically anymore. * It is now possible to avoid automatic wake up of previously touching objects on scene removal. See the additional parameter wakeOnLostTouch in PxScene::removeActor(), ::removeArticulation(), ::removeAggregte(), PxRigidActor::detachShape(). * PxJointLimit and PxJointLimitPair are now PxJointLinearLimit, PxJointLinearLimitPair, PxJointAngularLimitPair, depending on whether the limit is linear or angular. * Joints now solve for the entire position error rather than a ratio of 0.7 of it. The flag PxConstraintFlag::eDEPRECATED_32_COMPATIBILITY can be used to restore this behavior * PxConstraintFlag::Type has been renamed to PxConstraintFlag::Enum * * The spring constant parameter in joints and articulations that was previously 'spring' is now 'stiffness'. * The tangential spring constant parameter in articulations that was previously 'tangentialSpring' is now 'tangentialStiffness'. * Constraints do not respect PxDominanceGroup settings. Use PxJoint::setInvMassScale and setInvInertiaScale * Shapes are reference counted. PxShape::release() now decrements the reference count on a shape, and its use is deprecated for detaching a shape from its actor - use detachShape() instead. * Shape creation methods do not take a local transform parameter anymore. Instead PxShapeFlags can be specified. Triangle meshes, height fields and plane geometry shapes cannot be combined with non-kinematic PxRigidDynmic actors if PxShapeFlag::eSIMULATION_SHAPE is specified. Corresponding calls to PxRigidActor::createShape() or PxRigidActor::attachShape() are not supported. * PxShape::getActor() now returns a pointer, which is NULL if the shape is shareable. * PxShape::getWorldBounds() has been replaced with PxShapeExt::getWorldBounds(). * PxContactPoint has been renamed PxFeatureContact. * The internal format for contact storage has been modified; applications directly accessing the internal contact representation rather than PxContactPair::extractContacts should be modified accordingly. * Friction mode flags eENABLE_ONE_DIRECTIONAL_FRICTION and eENABLE_TWO_DIRECTIONAL_FRICTION have been replaced by PxFrictionType::Enum PxSceneDesc::frictionType. * PxSceneDesc::contactCorrelationDistance has been deprecated. * PxSceneDesc::contactCorrelationDistance no longer has an influence on how many friction anchors are created in a single frame, only on when they are removed in later frames. This may cause a very minor change in friction behavior. #### Fixed: * Rigid bodies now properly accumulate the forces/torques that are applied with addForce/addTorque while scene insertion is still pending. This affects bodies added to the scene while the scene is simulating and then given forces/torques with addForce/addTorque while the scene is simulating. These accumulated forces and torques are applied during the next simulate() call. Prior to this fix the forces/torques that accumulated while scene insertion was pending were lost and never applied. * Its now possible to serialize collections with jointed actors without including the corresponding joints in the collection. The deserialized actors will not be jointed anymore. * Joint drive force limits are actual force limits rather than impulse limits. Set the flag PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES to false to support legacy behavior * Angular drive constraints for revolute joints were wrongly computed, resulting in a negative angular velocity when a positive drive target was set. * Scene addActors will now correctly remove all actors that were passed to add, if some insert failed. * Contact modification now enforces max impulse field correctly. Previously, it only enforced it if max impulse was set to 0. * Contact modification now supports target velocity in all directions. Previously, it only enforced the target velocity components that were perpendicular to the contact normal. * Jittering of small spheres & capsules on very large triangles has been fixed. * Setting sleep threshold to 0 now guarantees that bodies won't fall asleep even if their kinetic energy reaches exactly 0. #### Deprecated: * PxShape::release() now decrements the reference count on a shape, and its use is deprecated for detaching a shape from its actor - use detachShape() instead. * PxJoint::getType() is deprecated - use getConcreteType() instead. * PxConstraintFlag::eREPORTING is deprecated - constraints always generate force reports * PxConstraintDominance is deprecated - use PxDominanceGroupPair instead. ### Scene queries #### Added: * PxVolumeCache, a volumetric cache for local collision geometry. * Parameter inflation was added to some PxGeometryQuery functions. * Flag eMESH_BOTH_SIDES can be now used to control triangle mesh culling for raycasts and sweeps. * Added PxBatchQueryMemory as a part of PxBatchQueryDesc, to allow memory buffers to be set before execution. * PxBatchQueryDesc() constructor now requires 3 parameters at initialization - see migration guide for more details. * PxBatchQuery::raycast, sweep, overlap calls will now issue a warning and discard the query when over maximum allowed queries. * There is a new flag to allow manually updating the scene query representation, see: PxSceneFlags::eENABLE_MANUAL_SQ_UPDATE and PxScene::flushQueryChanges(). * Added PxScene::forceDynamicTreeRebuild() function to immediately rebuild the scene query structures. * Added bool PxSweepHit::hadInitialOverlap() returning true if a sweep hit occurred early due to initial overlap at distance=0. #### Removed: * PxBatchQuery::linearCompoundGeometrySweepSingle and PxBatchQuery::linearCompoundGeometrySweepMultiple functions are no longer supported. * Globals PxPS3ConfigParam::eSPU_OVERLAP, eSPU_RAYCAST, eSPU_SWEEP that were previous set via setSceneParamInt call are replaced with PxBatchQueryDesc::runOnSpu. See migration guide for more details. #### Changed: * Scene Query raycastAny/Single/Multiple APIs were merged into a single raycast() call (same for overlaps and sweeps). Please refer to user and migration guides for details. * Scene Query raycast() API now uses a PxRaycastBuffer or a PxRaycastCallback parameter for reporting hits. Blocking hits are now reported separately from toching and PxRaycastCallback class supports reporting an unbounded number of results (same for overlaps and sweeps). * A const templated PxRaycastBufferN<int> object was added to allow convenient creation of fixed size scene query touch buffers. Same for overlaps and sweeps. * Support for compound sweeps was moved out from core SDK to extensions. * Support for compound sweeps was moved from PxScene to extensions (see PxRigidBodyExt::linearSweepSingle, PxRigidBodyExt::linearSweepMultiple). * PxQueryFilterCallback::preFilter now passes an actor pointer as well as a shape pointer. * PxSceneQueryFlag::eINITIAL_OVERLAP and PxSceneQueryFlag::eINITIAL_OVERLAP_KEEP have been replaced with PxHitFlag::eINITIAL_OVERLAP_DISABLE and PxLocationHit::hadInitialOverlap(). Note that checking for initial overlap is now the defaut for sweeps. * Sweeps in 3.3 execute using a new faster code path, in some cases with reduced precision. If you encounter precision issues not previously experienced in earlier versions of PhysX, use ePRECISE_SWEEP flag to enable the backwards compatible more accurate sweep code. * The default behavior for overlap queries with query filters returning eBLOCK has changed to only return one of eBLOCK hits. Please refer to the migration guide for details. #### Fixed: * Scene Query performance was significantly improved in a variety of scenarios. * Fixed a bug in capsule/mesh overlap code that occasionally caused unreported and misreported faces. * Fixed a crash in raycastMultiple when a convex was hit by the ray and eMESH_MULTIPLE flag was specified as a query flag. * Fixed a rare crash in heightfield raycast code. * Internal limit of 65536 results has been removed. * Accuracy in sphere/capsule-vs-triangle overlap and sweep tests has been improved. ### Cooking #### Added: * Added support for convex hull creation with limited output vertices count. * Added support for convex hull creation directly from polygons rather than triangles. * Added support function computeHullPolygons in cooking, that creates hull polygons from given vertices and triangles. The resulting polygons can be used to create the convex hull directly. #### Changed: * Changed convex hull volume integrals. * PxCookingParams constructor requires now PxTolerancesScale as an additional parameter. This enables us to perform further checks on the triangles during cooking. A warning will be emitted to the error stream if too huge triangles were found. This will ensure better simulation stability. #### Fixed: * Optimized heightfield load code for no-endian conversion case. ### Triangle meshes #### Added: * Added PxTriangleMeshFlag::eHAS_ADJACENCY_INFO flag for adjacency information checks. #### Removed: * Removed has16BitTriangleIndices(), replaced by triangleMesh->getTriangleMeshFlags() & PxTriangleMeshFlag::eHAS_16BIT_TRIANGLE_INDICES. ### Particles #### Added: * Direct read access to CUDA particle data has been added for graphics interoperability, see PxParticleBase::lockParticleReadData(PxDataAccessFlags flags) and PxParticleFluid::lockParticleFluidReadData(PxDataAccessFlags flags) * Added PxRegisterParticles to reduce binary size by stipping unused code on platforms where static linking is used. * Added setExplicitCudaFlushCountHint to allow early flushing of the cuda push buffer. * Added caching of triangle meshes. setTriangleMeshCacheSizeHint is supported on Kepler and above GPUs. #### Fixed: * Creating and immediately setting the position of particles failed and possibly crashed with GPU acceleration enabled. This would only happen after one or more simulation updates. * Creating many spread out particles might have crashed the GPU pipeline. ### Broad Phase #### Added: * The SDK now supports multiple broad-phase algorithms (SAP & MBP). See Release Highlights, PxBroadPhaseType and PxBroadPhaseDesc. * PxVisualizationParameter::eMBP_REGIONS has been added to visualize MBP regions #### Fixed: * The sap broadphase now gracefully handles PxShape instances whose axis-aligned bounding boxes have min/max limits with value +/- PX_MAX_F32 or QNAN or INF. Such bounds values can occur if a PxShape is given a global transform that is either illegal or close to the upper limit of the floating point range. Prior to this release, the sap broadphase could crash when the axis-aligned bounds of shapes had values that weren't within the floating point range. This has now been fixed. The overlap pairs reported by the broadphase for bounds with such values is undefined. ### Vehicles #### Added: * Vehicles now support serialization. A PxSerializationRegistry instance may be passed into PxInitVehicleSdk and PxCloseVehicleSdk in order to enable support. * Vehicle telemetry graphs can now be queried per channel for the most recent value with the function PxVehicleGraph::getLatestValue. * New vehicle PxVehicleDriveNW type has been introduced. This class makes use of a new differential type PxVehicleDifferentialNW, which allows specified wheels to be equally coupled to the differential, and allows all for some or all of the N wheels to be driven. * Support for camber angles has been added to the PxVehicleSuspensionData class. * Moment of inertia parameter has been added to the PxVehicleEngineData class. Prior to this a value of 1.0 was assumed internally. A default value of 1.0 has been used in the constructor for backwards compatability. * Vehicle manual contains new section describing the conversion of default vehicle parameter values from SI units to any system of units with particular reference to the use of centimetres instead of metres . * The SI units of each parameter in PxVehicleComponents.h has been documented. * Vehicle manual contains updated troubleshooting section. * The requirements for disabled wheels (PxVehicleWheelsSimData::disableWheel) have been documented to make it clear that disabled wheels must be no longer associated with a PxShape, must have zero rotation speed, and must be decoupled from the differential. This is also now discussed in the guide. * Wheel raycasts documentation has been improved to clarify the start and end points of each raycast. * Suspension line raycasts do not need to be performed for each vehicle prior to update with PxVehicleUpdates. This feature is implemented with a boolean array passed as an extra function argument to PxVehicleSuspensionRaycasts. This feature is useful for vehicles that require only low level of detail. * The clutch model now supports two accuracy modes (PxVehicleClutchAccuracyMode::eESTIMATE and PxVehicleClutchAccuracyMode::eBEST_POSSIBLE). If the estimate mode is chosen the computational cost and accuracy of the clutch can be tuned with PxVehicleClutchData::mEstimateIterations. * PxVehicleSuspensionData now has a function setMassAndPreserveNaturalFrequency. This modifies the mass and stiffness of the spring in a way that preserves the spring natural frequency. * A new helper function PxVehicleCopyDynamicsData has been added that allows dynamics data such as engine rotation speed, wheel rotation speed, gear etc to be copied from one vehicle to another of the same type. This is particularly useful if a vehicle has a number of different versions where each represents a different level of detail. * A new function PxVehicleWheelsSimData::copy has been added to allow per wheel dynamics data to be copied from one vehicle to another. * The vehicle manual contains a new section "Level of Detail" describing the available options for vehicles that require only a low level of detail. * PxVehicleTireLoadFilterData now requires that mMinNormalisedLoad is greater than or equal to zero. * PxVehicleTireLoadFilterData now has a new member variable mMinFilteredNormalisedLoad. This value describes the filtered normalised load that occurs when the normalised is less than or equal to mMinNormalisedLoad. * PxVehicleWheelsSimData now has a new function setMinLongSlipDenominator. This can be used to tune stability issues that can arise when the vehicle slows down in the absence of brake and drive torques. * A new section "PxVehicleAutoBoxData" has been added to the vehicle tuning guide to describe operation of the automatic gearbox. * A new section "The Vehicle Under-steers Then Over-steers" has been added to the vehicle troubleshooting guide to describe steps to avoid twitchy handling on bumpy surfaces. A new section "The Vehicle Never Goes Beyond First Gear" has been added to the vehicle troubleshooting guide to describe a common scenario that occurs when the automatic gearbox is given a latency time that is shorter than the time taken to complete a gear change. * A new section "The Vehicle Slows Down Unnaturally" has been added to the vehicle troubleshooting guide to describe the steps that can be taken to help the vehicle slow down more smoothly. * A number of vehicle snippets have been added. #### Changed: * Minor api change for consistency: PxVehicleDrive4WWheelOrder has been introduced to replace the enum beginning with PxVehicleDrive4W::eFRONT_LEFT_WHEEL. * Minor api change for consistency: PxVehicleDrive4WControl has been introduced to replace the enum beginning with PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL. * Minor api change for consistency: PxVehicleDriveTankWheelOrder has been introduced to replace the enum beginning with PxVehicleDriveTankWheelOrder::eFRONT_LEFT. * Minor api change for consistency: PxVehicleDriveTankControl has been introduced to replace the enum beginning with PxVehicleDriveTank::eANALOG_INPUT_ACCEL. * Minor api change for consistency: PxVehicleDriveTankControlModel has been introduced to replace the enum beginning with PxVehicleDriveTank::eDRIVE_MODEL_STANDARD. * Minor api change for consistency: PxVehicleTypes has been introduced to replace the enum beginning with eVEHICLE_TYPE_DRIVE4W. * Minor api change for consistency: PxVehicleWheelGraphChannel has been introduced to replace the enum beginning with PxVehicleGraph::eCHANNEL_JOUNCE. * Minor api change for consistency: PxVehicleDriveGraphChannel has been introduced to replace the enum beginning with PxVehicleGraph::eCHANNEL_ENGINE_REVS. * Minor api change for consistency: PxVehicleGraphType has been introduced to replace the enum beginning with PxVehicleGraph::eGRAPH_TYPE_WHEEL. * PxVehicleUpdates now checks in checked and debug config that the wheel positioning of the driven wheels in a PxVehicleDrive4W obey the wheel ordering specified in PxVehicleDrive4WWheelOrder. Vehicles that are back-to-front or right-to-left are also allowed. A warning is issued if the check fails. * PxVehicleUpdates now checks in checked and debug config that the odd wheels of a PxVehicleDriveTank are either all to the left or all to the right of their even-wheeled complement, as specified in PxVehicleDriveTankWheelOrder. A warning is issued if the check fails. * To improve api consistency the arguments of the function PxVehicleDriveDynData::setAnalogInput(const PxReal analogVal, const PxU32 type) have been swapped so that it is now of the form PxVehicleDriveDynData::setAnalogInput(const PxU32 type, const PxReal analogVal). * Non-persistent wheel dynamics data (slip, friction, suspension force, hit data etc) has been moved out of the PxVehicleWheelsDynData class and is now recorded in a PxWheelQueryResult buffer that is passed as a function argument to the PxVehicleUpdates function. * PxVehicleWheels::isInAir() has been replaced with PxVehicleIsInAir(const PxVehicleWheelQueryResult& vehWheelQueryResults) to reflect the change to non-persistent data storage. * The origin of vehicles can now be shifted to stay in sync when the origin of the underlying PxScene is shifted. See PxVehicleShiftOrigin() for details. * PxVehicleWheels::setWheelShapeMapping and PxVehicleWheels::getWheelShapeMapping have been moved to PxVehicleWheelsSimData::setWheelShapeMapping and PxVehicleWheelsSimData::getWheelShapeMapping * PxVehicleWheels::setSceneQueryFilterData and PxVehicleWheels::getSceneQueryFilterData have been moved to PxVehicleWheelsSimData::setSceneQueryFilterData and PxVehicleWheelsSimData::getSceneQueryFilterData * PxVehicle4WEnable3WTadpoleMode and PxVehicle4WEnable3WDeltaMode now take an extra function argument: a non-const reference to a PxVehicleWheelsDynData. * The section "SI Units" in the vehicle guide has been updated to include the new functon PxVehicleWheelsSimData::setMinLongSlipDenominator. * PxVehicleTireData::mCamberStiffness has been replaced with PxVehicleTireData::mCamberStiffnessPerUnitGravity. PxVehicleTireData::mCamberStiffnessPerUnitGravity should be set so that it is equivalent to the old value of PxVehicleTireData::mCamberStiffness divided by the magnitude of gravitational acceleration. * PxVehicleComputeTireForceDefault has been removed from the public vehicle api. Custom tire shaders that call PxVehicleComputeTireForceDefault are best implemented by taking a copy of PxVehicleComputeTireForceDefault and calling the copy instead. #### Fixed: * Sticky tire friction is now activated in the tire's lateral direction at the tire force application point when the velocity at the base of the tire has low longitudinal and low lateral components. Longitudinal sticky tire friction is unaffected and is still activated when the vehicle has low forward speed. This fixes a minor bug where vehicles positioned on a slope perpendicular to the slope's downwards direction can slowly drift down the slope. * Bugs in the suspension force and tire load computation have been fixed that affected handling when the car was upside down. * The tire load passed to the tire force computation is now clamped so that it never falls below zero. * A bug in the tank damping forces has now been fixed. Tanks now slow down more aggressively from engine and wheel damping forces. # v3.2.4 April 2013 ## What's New In NVIDIA PhysX 3.2.4 #### General * <i>Note: PS3 platform specific changes can be found in the PS3 readme file.</i> * Fixed a bug which caused actors to return wrong world bounds if the bounds minimum was above 10000 on any axis. * Reporting allocation names can now be enabled or disabled (see PxFoundation::setReportAllocationNames). When enabled, some platforms allocate memory through 'malloc'. * eEXCEPTION_ON_STARTUP is removed from PxErrorCode and it is no longer needed. * Added boilerplate.txt to the Tools folder. SpuShaderDump.exe and clang.exe require it. * PxWindowsDelayLoadHook.h has been moved from Include/foundation/windows to Include/common/windows. * PxScene::saveToDesc now reports the bounceThresholdVelocity value. * Fixed a bug in PxDefaultSimulationFilterShader: the value of the second filter constant in the collision filtering equation was ignored and instead the value of the first filter constant was used. * Fixed a crash bug in PCM collision. #### Rigid Bodies * Forces applied to bodies (with PxRigidBody::addForce) that go to sleep in the subsequent update now have their applied forces cleared when the body is set to sleep to avoid them being applied in a later update when the body is once more awake. This bug broke the rule that forces applied with PxRigidBody::addForce do not persist beyond the next scene update. * Jittering of small spheres & capsules on very large triangles has been fixed. #### Cooking * PxCookingParams constructor is now marked as deprecated. PxToleranceScale is needed for PxCookingParams in order to perform additional triangle check during cooking. This triangle check will trigger warning if too huge triangles are used. This check will ensure better simulation stability. #### Scene Queries * Added PxScene::forceDynamicTreeRebuild() function to immediately rebuild the scene query structures. * Accuracy in sphere/capsule-vs-triangle overlap and sweep tests has been improved. #### Broad Phase * Fixed assert in debug mode that wrongly asserted when an overlap pair was removed with perfect equality between the min of one bound and the max of the other along at least one axis. #### Character controller * PxControllerFilterCallback has been added, to make CCT-vs-CCT filtering more flexible. * Fixed a bug where PxControllerBehaviorCallback was not called when a PxUserControllerHitReport was not defined. * PxObstacle notifications has been added to handle touched obstacles. * Touched PxObstacle has been replaced by touched ObstacleHandle. * PxObstacleContext::getObstacleByHandle has been added. * Touched actors scene is checked before ride on shape, to ensure valid touched shape. * Touched shape scene query flag is checked before ride on shape, to ensure valid touched shape. * Touched shape user CCT filtering is triggered before ride on shape, to ensure valid touched shape. * Box & capsule controllers' resize function now properly take the up direction into account #### Vehicles * Documented potential problem with PxVehicleWheelsDynData::getTireDrivableSurfaceType() and PxVehicleWheelsDynData::getTireDrivableSurfaceShape() whereby the pointer returned may reference a PxShape or PxMaterial that has been released in-between storing the pointer in PxVehicleUpdates and any subsequent query. * PxVehicleWheelsSimData::disableWheel has been documented in more detail. PxVehicleWheelsSimData::enableWheel has been added. * Fixed a bug where the denominator of the longitudinal slip calculation didn't take into account the value of PxTolerancesScale::length. This will only have an impact if PxTolerancesScale::length != 1.0f. * Fixed a bug where the engine torque would be incorrectly applied if PxTolerancesScale::length != 1.0f. This will only have an impact if PxTolerancesScale::length != 1.0f. #### Particles * Creating and immediately setting the position of particles failed and possibly crashed with GPU acceleration enabled. This would only happen after one or more simulation updates. ## Supported Platforms Unchanged from from 3.2.3 except: #### Development * Upgraded to Xcode 4.6 ## Known Issues And Limitations Unchanged from from 3.2.3. # v3.2.3 November 2012 ## What's New In NVIDIA PhysX 3.2.3 #### General * <i>Note: PS3 platform specific changes can be found in the PS3 readme file.</i> * Quaternions passed through the API are now considered valid if their magnitude is between 0.99 and 1.01. * Fixed crash when running out of memory on creation of a triangle mesh. * For applications using floating point exceptions, the SDK will now mask or avoid exceptions arising from invalid floating point operations (inexact and underflow exceptions may still be generated). * Fixed a bug with recursive use of the PxScene read/write lock. * Fixed a shutdown bug with very short lived threads on Linux platforms. * PhysX version number in error messages now printed in hex for easier reading. * Fixed memory barrier and prefetch implementation for all posix based platforms (android, ios, osx, linux). #### Broad Phase * Fixed a broad phase crash bug that occurred when deleting shapes with bounds very far from the origin. #### Collision Detection * Documentation of limits of PxShape counts has been added for affected platforms. * Made kinematics interact better with CCD. * Adding support for disabled contact response in CCD by respecting the dominance setting. In this case, CCD will emit events but will not alter the motion of the bodies. * Fixed potential crash in eENABLE_PCM codepath. #### Rigid Bodies * Fixed bug in force based contact reports. An assert could occur when PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS was set and PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND was not set. * Twist Limit range is documented for revolute and D6 joints, and validated. * Reduced the number of SDK allocations when using CCD. #### Scene Queries * Raycasts against heighfields now return correct actual mesh index, which can be used for getTriangle(). * Fixed bug that caused scene queries to miss hits for static rigid bodies that got moved around (after having been added to the scene). * Fixed rebuilding the dynamic structure properly when used for static rigid bodies. * Fixed a rare crash in heightfield raycast code. #### Character controller * A new runtime tessellation feature has been added, that can help reducing FPU accuracy issues in the sweep tests. #### Convex hulls * Zero-sized convex hull data double delete detection fix. #### Vehicles * Vehicles with rigid body actors that are asleep and also have no acceleration or steer inputs are treated as though they are asleep too; that is, they are bypassed completely in the PxVehicleUpdates function. Vehicles with sleeping rigid body actors but with non-zero acceleration or steer inputs are processed as normal in PxVehicleUpdates and will automatically have their rigid body actor woken up. * New function PxVehicleSetUpdateMode to allow PxVehicleUpdates to select between applying accelerations to vehicle rigid bodies or immediate updating of their velocity. #### Particles * Fixed a non-deterministic crash appearing with rigid bodies using CCD and gpu particles in the same scene. #### Physx Visual Debugger * Material release events are now correctly sent to PVD. #### RepX * Add more RepX class information in PhysXAPI document. ## Supported Platforms #### Runtime * Apple iOS * Apple Mac OS X * Google Android (version 2.2 or later for SDK, 2.3 or later required for samples) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver ver 295.73 or later is required for GPU acceleration) * Microsoft Windows RT (formerly known as Windows on ARM) (SDK only, no samples yet) * Microsoft XBox 360 * Sony Playstation 3 #### Development * Microsoft Windows XP or later * Microsoft Visual Studio 2008, 2010 * Xcode 4.5 ## Known Issues And Limitations Unchanged from from 3.2.2. # v3.2.2 October 2012 ## What's New In NVIDIA PhysX 3.2.2 #### General * <i>Note: PS3 platform specific changes can be found in the PS3 readme file.</i> * Added Microsoft Windows RT (formerly known as Windows on ARM) support. * Suspended Sony Playstation Vita support. * PxScene now exposes methods to make multithreaded sharing of scenes easier, see PxSceneFlags::eREQUIRE_RW_LOCK for details. * Enabled Win64 DEBUG build to use SIMD enabled code path. * Fixed bug in quaternion to axis/angle routine which failed on negative w values. * Fixed crash when using ConvX on a PxCollection with external references. * Fixed a spurious overlapping read/write error report when using simulation call backs in checked builds. * The bounce threshold velocity can be set at run-time with PxScene::setBounceThresholdVelocity. Likewise, it can be queried with PxScene::getBounceThresholdVelocity * Fixed return value of Ps::atomicExchange for POSIX based platforms: Linux, Android, IOS and OSX * PxGeometryQuery::computePenetration() has been added, to compute the Minimum Translational Distance between geometry objects. #### Broad Phase * Fixed a broad phase crash bug. #### Collision Detection * Collision detection now more robust when confronted with ill-conditioned scenarios. * Fixed crash when SDK is unable to create more contact pairs. Now a warning is emitted and the contacts are ignored. #### Rigid Bodies * Improved the numerical stability of articulations. * The target pose of a kinematically controlled dynamic actor can now get extracted through PxRigidDynamic::getKinematicTarget(). * The new flag PxRigidDynamicFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES makes scene queries use the target pose of a kinematically controlled dynamic actor instead of the actual pose. * Fixed PxConstraintFlag::eVISUALIZATION having no effect. * Fixed bug that caused sleep/wake-up notification events to get lost. * Fixed a bug where sleeping objects were not waking up properly. * Fixed potential assert when switching a rigid body between kinematic and dynamic with contact reports enabled. * Fixed a bug where CCD didn't consider the scaling transform for triangle meshes. * Fixed a potential crash bug when PxConstraintFlag::ePROJECTION gets raised after a joint (that connects to other projecting joints) has been created. * Fixed a bug that resulted in joint breakage being reported every frame for any broken joint * Added PxArticulationDriveCache for applying an impulse to an entire articulation * fixed various crash bugs when sleeping articulations were removed from the scene and re-added * #### GPU Physics * Fixed a possible out of bounds array access in GPU particle collision code. * Updated the GPU PhysX Visual Indicator to allow APEX to hook into it. * Fixed sample particles crash when there is a cuda kernel error. * Upgraded GPU tech to CUDA 4.2. #### Scene Queries * PxSceneQueryHit::faceIndex is now filled in for sweeps against convex meshes. * Added support for sphere and capsule shaped heightfield overlap queries. * Added an inflation parameter to all sweep queries in PxGeometryQuery, PxBatchQuery, and PxScene. This can be used to maintain a minimum distance between objects when moving them using sweeps. * Made sure that raycast multiple will include the closest triangle in the results even if the output cannot hold all the triangles that are hit. * Fixed swept sphere against capsule not properly testing for initial overlap. * Fixed the normal vector returned from sweeps being sometimes negated. * Fixed a scenario where raycasting could miss an actor after the user has moved it using setGlobalPose(). * Fixed swept convex against plane sometimes reporting false hits * Fixed swept/overlap/raycast with convexes that don't have identity scale rotation. * Fixed a culling bug for box-triangle mesh sweep. #### Convex hulls * Convex hull is rejected if it has less than 4 polygons. * Additional convex hull check has been added to detect open volumes. #### Triangle meshes * Added triangle mesh flags for 16bit indices and adjacency information. * Fixed adjacency information order for getTriangle with triangle meshes to respect the vertex order. #### HeightFields * Fixed bug where capsules would bounce as they roll across heightfield edges. * Fixed bug where spheres would bounce as they roll across heightfield vertices. * Added adjacency information for getTriangle with height fields. #### Particles * Fixed triangle mesh shapes with ePARTICLE_DRAIN colliding with particles. * Fixed crash with GPU particles when a lot of grid cells get occupied and vacated within one time step. #### Character Controller * The PxControllerBehaviorFlag::eCCT_USER_DEFINED_RIDE flag has been added. * Fixed character controller not walking up steps properly if they are not exactly 90 degrees vertical. * Fixed a bug where the character controller was not able to move up slopes when using a small step offset setting. * Fixed a bug where the character controller could rise off the ground when blocked by a step. * Fixed a bug where the character controller could rise off the ground when hitting another character controller. * Fixed a bug where releasing a shape of a touching actor and then releasing the character controller would crash. Releasing shapes of actors in touch may still lead to crashes in other situations. PxController::invalidateCache() can be used to work around these situations. #### CCD * Fixed culling bug in CCD sweeps with meshes with transforms that caused contacts to be missed #### Vehicles * The vehicle sdk used to make the assumption that wheels 0 and 1 (the front wheels) of a PxVehicleDrive4W responded positively to the input steering wheel angle, while wheels 2 and 3 (the rear wheels) responded in the opposite direction to that of the input steering wheel angle. A consequence of this assumed behaviour was the restriction that PxVehicleWheelData::mMaxSteer was limited to positive values. This restriction has now been relaxed with the caveat that PxVehicleWheelData::mMaxSteer must be in range (-Pi/2, Pi/2). It is now possible to turn each wheel positively or negatively relative to the input steering wheel angle by choosing positive or negative values for PxVehicleWheelData::mMaxSteer. Ackermann steer correction might result in the front and rear wheels competing against each other if the rear and front all steer in the same direction relative to the input steering wheel angle. If this is the case it will be necessary to set the Ackermann accuracy to zero. * It is now possible to set the engine rotation speed (PxVehicleDriveDynData::setEngineRotationSpeed), the rotation speed of each wheel (PxVehicleWheelsDynData::setWheelRotationSpeed) and the rotation angle of each wheel (PxVehicleWheelsDynData::setWheelRotationAngle). The default values for each of these properties remains zero. * Wheel contact reporting has been improved with the addition of a number of query functions to the PxVehicleWheelsDynData class. These are getTireDrivableSurfaceContactPoint, getTireDrivableSurfaceContactNormal, getTireLongitudinalDir, getTireLateralDir, getSuspensionForce, getTireDrivableSurfaceShape. * It is now possible to store a userData pointer per wheel. This allows, for example, each wheel to be associated with a game object. The relevant functions are PxVehicleWheelsDynData::setUserData and PxVehicleWheelsDynData::getUserData. * The default behavior of PxVehicleWheels::setWheelShapeMapping has changed. Previously, default values were automatically assigned to each wheel at construction so that the ith wheel was mapped to the ith body shape. This, however, made the assumption that there was a wheel shape for each wheel, which is not always true. As a consequence, the default value is now -1, meaning any mapping between body shape and wheel has to be explictily made by calling setWheelShapeMapping. * It is now possible to query the mapping between wheel and body shape with PxVehicleWheels::getWheelShapeMapping. * It is now possible to query the tire shader data that has been applied to each wheel with PxVehicleWheelsDynData::getTireForceShaderData. * The helper function PxVehicleComputeSprungMasses has been added to aid the setup of the suspension sprung masses from the rigid body centre of mass and wheel center coordinates. * The scene query filter data applied to the suspension raycasts was previously taken from the filter data of the associated body shape. This makes the assumption of a body shape per wheel, which is not always true. As a consequence, the filter data must be explictly set per wheel by calling PxVehicleWheels::setSceneQueryFilterData. The filter data can be queried with PxVehicleWheels::getSceneQueryFilterData. * Sub-stepping of the vehicle update can now be applied per vehicle with PxVehicleWheelsSimData::setSubStepCount. * PxVehicleDrivableSurfaceToTireFrictionPairs has been modified so that the dictionary of material pointers can be updated without the necessity of further allocation. The create function has been replaced with separate allocate and setup functions. * A new vehicle type PxVehicleNoDrive has been added to provide a close approximation to backwards compatibility with the api of the 2.8.x NxWheelShape. #### Visual Remote Debugger * Added PVD compatible profile zones for batched queries. * Added the ability to capture and inspect scene queries in PVD. * SDK will now flush the pvd connection stream immediately after cloth or cloth fabric is created or released. * Fixed the PVD support for articulations. * Fixed PVD rendering wrong constraint limits. #### Documentation * Wrong statement in PxRigidStatic::release() has been corrected. Static rigid bodies do wake up touching dynamic rigid bodies on release. * Wrong statement in PxShape::setFlag() has been corrected. It is a valid operation to clear all flags. * Retroactively added more detail about changes to 3.2.1 release notes below. ## Supported Platforms #### Runtime * Apple iOS * Apple Mac OS X * Google Android (version 2.2 or later for SDK, 2.3 or later required for samples) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver ver 295.73 or later is required for GPU acceleration) * Microsoft Windows RT (formerly known as Windows on ARM) (SDK only, no samples yet) * Microsoft XBox 360 * Sony Playstation 3 #### Development * Microsoft Windows XP or later * Microsoft Visual Studio 2008, 2010 * Xcode 4.2 ## Known Issues And Limitations #### General * Memory leaks might get reported when using the debug versions of malloc and free together with the debug version of PhysX on Microsoft Windows platforms with Visual Studio 2010. This is caused by a bug in the Visual Studio 2010 runtime libraries. If such a leak appears immediately after releasing PhysX and all its components, please contact us for information about workarounds. * Use of articulations may require an increase of 64K in the stack size for threads making API calls and engine worker threads Please also see the previous lists from 3.2.1 and earlier. # v3.2.1 June 2012 ## What's New In NVIDIA PhysX 3.2.1 #### General * <i>Note: PS3 platform specific changes can be found in the PS3 readme file.</i> * Added GRB hooks for APEX 1.2.1. * Some incorrect usages of __restrict have been fixed. * A crash when the user's code had FPU exceptions enabled has been fixed. * A rare crash on Win64 has been fixed. * Removed no longer needed RapidXML library from distribution. * Binary serialization can now save the names of actors and shapes. * Removed a RepXUtility.h reinterpret_cast compile warning that happened on some platforms. * Fixed a spurious overlapping read/write error report when using simulation call backs in checked builds. * Fixed a bug in PxBinaryConverter when processing PxConvexMesh and PxMaterial assets. * Fixed bug in implementations of array accessors (PxPhysics::getScenes(), GuMeshFactory::getTriangleMeshes(), GuMeshFactory::getConvexMeshes(), GuMeshFactory::getHeightFields(), PxAggregate::getActors(), PxScene::getAggregates(), PxScene::getArticulations(), PxScene::getConstraints() ) when startIndex > bufferSize. * Reduced the number of libraries provided for game consoles. The following core libraries are included in the PhysX3 library and are not available separately anymore: LowLevel, LowLevelCloth, PhysX3Common, PhysXProfileSDK, PhysXVisualDebuggerSDK, PvdRuntime, PxTask, SceneQuery, SimulationController. #### Documentation * Clarified documentation regarding use of eSEND_SLEEP_NOTIFIES flag. * Clarified documentation regarding using different CRT libraries. * Removed some confusing statements about meta data from the documentation. * Updated PsPool, PsSort so they can use the user allocator. #### Mesh Cooking * A warning message about negative volumes in the convex mesh cooker could cause a crash. * Fixed failure to create valid convex hull in cooking when using PxConvexFlag::eINFLATE_CONVEX. * The convex mesh cooking has been made more robust and properly outputs some error messages that were previously missing. * Fixed crash bug in x64 version of ClothEdgeQuadifier. * Adjacency information option for TriangleMeshes. This is controlled using the PxCookingParams::buildTriangleAdjacencies flag, and returned if available by PxMeshQuery::getTriangle(). #### Broad Phase * The sdk gracefully handles the case of more than 65536 broadphase pairs and reports a warning that some contacts will be dropped in the event that this limit is exceeded. This affects all platforms except win32/win64/linux/linux64, which support a maximum number of 4294967296 pairs. #### Collision Detection * Fixed a memory corruption bug in heightfield code. * Fixed a bug in sphere vs mesh contact generation that could result in bad normals. * Added a flag to enable or disable contact caching, to permit users to make a performance vs memory tradeoff. * Fixed a crash bug in ContactReport cleanup code. #### Rigid Bodies * The simultaneous raising of both the PxShapeFlag::eSIMULATION_SHAPE and PxShapeFlag::eTRIGGER_SHAPE flags is now explicitly forbidden by the sdk. If any of the two is raised then any attempt to raise the other is rejected by the sdk and an error is passed to the error stream. #### Articulations * The API stubbed in 3.2.0 for applying an impulse to an entire articulation is now implemented. #### GPU Physics * Much more specific error messages for CUDA compute capability related failures. * Added SM35 support for GK110 GPUs. * The CUDA contexts provided by the gpu dispatcher can now be shared across scenes. * Fixed a possible out of bounds array access in GPU particle collision code. #### Scene Queries * Resolved poor GJK sweep convergence. * Batched queries accept sphere geometry for sweeps. * Optimized performance of raycasts. * An internal limit of 65536 objects in the scene-query subsytem has been lifted. * Fixed a bug where raycasts that sliced through two adjoining heightfields did not return correct results. * Fixed a crash bug in PxFindOverlapTriangleMeshUtil when doing a sphere overlap query against a heightfield. #### Cloth * PxCloth::setMotionConstraints() now works with NULL parameter. #### Character Controller * PhysX CCT code no longer sets PxShape::userData. * Intersection of pairs of CCTs now uses the supplied filter data and the supplied callback prefilter. The callback postfilter is not yet hooked up. * A bug has been fixed whereby the filterData was ignored in one of the scene queries initiated by the PhysX CCT code. * Introduced a more automatic mechanism for invelidating the character controller's scene cache. As part of this, PxController::reportSceneChanged() was replaced with PxController::invalidateCache(). * Added helper functions PxController::get/setFootPosition() to let user specify the bottom point of the character controller, rather than the center. * A new helper function, PxController::resize(), has been added to facilitate character controller resizing. * PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT is not the default behavior anymore. * The slope limit is only observed when walking on static convex meshes, static triangle meshes, static boxes and static heightfields. The slope limit is not observed when walking on dynamic or kinematic rigid bodies or static capsules or static spheres. This partially fixes a bug where the slope limit was inadvertently considered for shapes attached to dynamic rigid bodies and inadvertently ignored for boxes attached to static shapes. #### Vehicles * The vehicle sdk now reports an error to the error stream and exits from PxVehicleUpates if PxInitVehicleSdk has not been called in advance. This avoids a divide-by-zero error that can arise if the vehicle sdk has not been initialised correctly. #### Visual Debugger * Releasing of cloth fabrics is reported to the VRD. * Ext::Joint::setActors() call now reported to PVD. * Fixed crash bug when removing an aggregate containing a PxArticulation, while PVD is running. ## Supported Platforms Unchanged from from 3.2. ## Known Issues And Limitations Unchanged from from 3.2. # v3.2 December 2011 ## What's New In NVIDIA PhysX 3.2 #### General * Three new sample applications: SampleCharacterCloth (character with cloth cape and cloth flags), SampleBridges (character controller walking on dynamic bridges and moving platforms), SampleCustomGravity (character controller with arbitrary up vector). * On Windows, the PxFoundation instance is now a process wide singleton and part of the new PhysX3Common.dll library * PxCreatePhysics() does not create a PxFoundation instance any longer. The PxFoundation instance has to be created in advance through PxCreateFoundation(). * Calls to PxCreatePhysics() are not valid anymore if a PxPhysics instance already exists. * If profiling information should be sent to the PhysX Visual Debugger, a PxProfileZoneManager instance has to be provided when creating the PxPhysics instance. * The version number constant PX_PUBLIC_FOUNDATION_VERSION has been replaced with PX_PHYSICS_VERSION. Both PxFoundation and PxPhysics use the same version number now. * The API now distinguishes between input and output stream types. * Added mechanism to reduce code size by not linking optional components. See PxCreateBasePhysics() and the PxRegister*() functions. * Added getConcreteTypeName() to API classes to provide run time type information. * Added PxScene::getTimestamp() to retrieve the simulation counter. * PxGetFoundation has been moved to PxGetFoundation.h * Changed the functions PxPhysics::releaseUserReferences(), releaseCollection(), addCollection() and releaseCollected() to now take a reference rather than a pointer. * The signature of PxCreatePhysics has changed: The Foundation SDK instance must be passed in explicitly. One can also hook profiling information by passing a PxProfileZoneManager. * Platform conversion for serialized data has been moved from the ConvX command line tool to the PxBinaryConverter interface in the cooking library * contact data block allocation now provides statistics on usage and max usage * On all platforms except PS3, contact data blocks can be progressively allocated * PxExtensionVisualDebugger has been renamed to PxVisualDebuggerExt, PxExtensionsConnectionType renamed to PxVisualDebuggerConnectionFlag * Default implementations of memory and file streams added in PxDefaultStreams.h * Renamed PxPhysics::getMetaData() to ::PxGetSDKMetaData(). * Scene::simulate() now takes a memory block which is used for allocation of temporary data during simulation * On Windows, CudaContextManagerDesc support appGUID now. It only works on release build. If your application employs PhysX modules that use CUDA you need to use a GUID so that patches for new architectures can be released for your game.You can obtain a GUID for your application from Nvidia. #### Rigid Bodies * Introduced a new contact generation mode, see eENABLE_PCM. Note that this is an experimental feature that still shows simulation artifacts in some scenarios. * Introduced two new friction simulation modes, see eENABLE_ONE_DIRECTIONAL_FRICTION and eENABLE_TWO_DIRECTIONAL_FRICTION. * Introduced a new scene query flag PxSceneQueryFlag::eINITIAL_OVERLAP_KEEP to control how initial overhaps are treated in scene queries. * Per-triangle materials have been implemented. * Changes to material properties are automatically reflected in contact resolution. * New helper methods to compute mass properties for a dynamic rigid body taking per shape density/mass values into account (see documentation on PxRigidBodyExt for details). * A new set of methods for overlap, sweep and raycast tests based on PxGeometry objects has been introduced. See documentation on PxMeshQuery and PxGeometryQuery for details). * The contact report API has changed (for details see the documentation on PxSimulationEventCallback::onContact()). Among the changes are: * Reports only get sent for shape pairs which request them. Previously, reports were sent for an actor pair even if the requested shape pair event was not triggered (for example because other shapes of the same actors started colliding etc.) * The following PxPairFlags have been removed eNOTIFY_CONTACT_FORCES, eNOTIFY_CONTACT_FORCE_PER_POINT, eNOTIFY_CONTACT_FEATURE_INDICES_PER_POINT. Forces and feature indices are now always provided if applicable. * It is much easier now to skip shape pairs or contact point information when traversing the contact report data. * The memory footprint of contact reports has been reduced. * The members featureIndex0/1 of PxContactPoint have been renamed to internalFaceIndex0/1 for consistency. * For trigger reports, the eNOTIFY_TOUCH_PERSISTS event has been deprecated and will be removed in the next release. For performance and flexibility reasons it is recommended to use eNOTIFY_TOUCH_FOUND and eNOTIFY_TOUCH_LOST only and manage the persistent state separately. * Added PxConstraintVisualizer interface and code to visualize joint frames and limits. * Improved PxBatchQuery API. * PxPhysics::getProfileZoneManager() now returns a pointer rather than a reference. * PxRigidDynamic::moveKinematic() has been renamed to setKinematicTarget() to underline its precise semantics. * Added new function PxShape::getGeometry and class PxGeometryHolder to improve Geometry APIs. * PxCreatePlane now takes a PxPlane equation as a parameter. Note that the interpretation of the distance value is negated relative to 3.1 * Added new actor creation helpers PxCloneStatic, PxCloneDynamic, PxScaleActor. * Added new functions PxTransformFromSegment, PxTransformFromPlaneEquation to simplify creation of planes and capsules. * added PxJoint::getConstraint() to access the underlying constraint object, from which the constraint force can be read * Some methods of PxAggregate have been renamed for consistency or replaced for extended functionality. * getMaxSize() is now called getMaxNbActors(). * getCurrentSize() is now called getNbActors(). * getActor() has been replaced by getActors() which copies the actor pointers to a user buffer. * Added support for kinematic triangle meshes, planes and heighfields. #### Scene queries * Dynamic AABBTree has been set as the default dynamic pruning structure. #### Particles * Removed descriptors from particle API: The properties maxParticles and PxParticleBaseFlag::ePER_PARTICLE_REST_OFFSET need to be specified when calling PxPhysics::createParticleSystem() and createParticleFluid(). All other properties can be adjusted after creation through set methods. #### Cloth * Added convex collision shapes, see PxCloth::addCollisionConvex() * Added friction support, see PxCloth::setFrictionCoefficient() * Added angle based bending constraints, see PxClothPhaseSolverConfig::SolverType::eBENDING * Added separation constraints, a spherical volume that particles should stay outside of, see PxCloth::setSeparationConstraints() * Added drag, see PxCloth::setDragCoefficient() * Added inertia scaling, controls how much movement due to PxCloth::setTargetPose() will affect the cloth * Added support for setting particle previous positions, see PxCloth::setParticles() * Added controls for scaling particle mass during collision, this can help reduce edge stretching around joints on characters, see PxCloth::setCollisionMassScale() * Particle data is now copied asynchronously from the GPU after simulate (rather than on demand) * Improved fabric layout, you can now share fabric data across multiple phases to reduce memory usage, see PxClothFabric * Fixed bug in collision when capsules are tapered at a slope > 1 #### Vehicles * Added PxVehicleDriveTank, a vehicle class that enables tank behaviors. * Support for vehicles with more than 4 wheels, see PxVehicleDrive4W, PxVehicleDriveTank. * Significant refactor of vehicle api to allow further types of vehicle to be added. * Americal English spelling used in vehicle api. * PxVehicle4W replaced with PxVehicleDrive4W, PxVehicle4WSimulationData replaced with PxVehicleDriveSimData4W. * Removal of scene query helper functions and structs: PxVehicle4WSceneQueryData, PxVehicle4WSetUpSceneQuery, PxWheelRaycastPreFilter, PxSetupDrivableShapeQueryFilterData, PxSetupNonDrivableShapeQueryFilterData, PxSetupVehicleShapeQueryFilterData. See SampleVehicle_SceneQuery.h for their implementation in SampleVehicle. * PxVehicle4WSimpleSetup and PxCreateVehicle4WSimulationData have been removed and replaced with default values in vehicle components, see PxVehicleComponents.h. * PxVehicle4WTelemetryData has been replaced with PxVehicleTelemetryData, a class that supports vehicles with any number of wheels, see PxVehicleTelemetryData * PxVehicleDrivableSurfaceType no longer stored in PxMaterial::userData. A hash table of PxMaterial pointers is instead used to associate each PxMaterial with a PxVehicleDrivableSurfaceType, see PxVehicleDrivableSurfaceToTireFrictionPairs. * PxVehicleTyreData::mLongitudinalStiffness has been replaced with PxVehicleTireData::mLongitudinalStiffnessPerUnitGravity, see PxVehicleTireData. * Tire forces now computed from a shader to allow user-specified tire force functions, see PxVehicleTireForceCalculator. * Added helper functions to quickly configure 3-wheeled cars, see PxVehicle4WEnable3WTadpoleMode, PxVehicle4WEnable3WDeltaMode. #### Serialization * Changed the functions PxPhysics::releaseUserReferences(), releaseCollection(), addCollection() and releaseCollected() to now take a reference rather than a pointer. * Platform conversion for serialized data has been moved from the ConvX command line tool to the PxBinaryConverter interface in the cooking library. * Changed some functions in RepXUtility.h and RepX.h to take a reference rather than a pointer. #### What we removed: * Deformables have been removed. Use the optimized solution for clothing simulation instead (see documentation on PxCloth for details). * PxSweepCache was replaced with PxVolumeCache. * PVD is no longer enabled in the release build. * Removed anisotropic friction. * Removed the CCD mode eSWEPT_CONTACT_PAIRS. * PxActorDesc has been removed. * The ConvX tool has been removed. * Removed empty default implementations of functions in PxSimulationEventCallback for consistency and because it can create bugs in user code if function prototypes change between releases. Users must now supply (eventually blank) implementations for all functions. * Octree and quadtree pruning structures have been removed. #### Fixed Bugs * PxScene::getActors() might not work properly when the startIndex parameter is used. * Improved the doc-comment of PxConvexMesh::getMassInformation(). * RepX instantiation can lose all internal references when addOriginalIdsToObjectMap is false. * PxSetGroup crashed when used on a compound. * PhysXCommon.dll can be delay loaded. * ContactReportStream can now handle huge report numbers and size (resize-able flag) can be set in PxSceneDesc.h. * Fixed assert in sweep tests. * Concurrent read/write operations during a PxScene::fetchResults() call were not detected properly and no warning message got sent in checked builds. Forbidden write operations during callbacks triggered by PxScene::fetchResults() (contact/trigger reports etc.) were not covered either. * Fixed crash bug that occurred during collision detection when more than 16K of contact data was generated. Contacts that generate more than 16K of contact data are now fully supported. * Fixed crash bug when PhysX Visual Debugger is connected and an object gets modified and then released while the simulation is running. ## Supported Platforms #### Runtime * Apple iOS * Apple Mac OS X * Google Android (version 2.2 or later for SDK, 2.3 or later required for samples) * Linux (tested on Ubuntu) * Microsoft Windows XP or later (NVIDIA Driver ver 295.73 or later is required for GPU acceleration) * Microsoft XBox 360 * Sony Playstation 3 * Sony Playstation Vita #### Development * Microsoft Windows XP or later * Microsoft Visual Studio 2008, 2010 * Xcode 4.2 ## Known Issues And Limitations #### Binary Serialization * Meta data generation for PxParticleFluid and PxParticleSystem serializables currently fails. * For collections that contain jointed rigid bodies all corresponding joints need to be added as well, otherwise deserialization will fail. #### Rigid Body Simulation * Capsules and spheres can struggle to come to rest on even perfectly flat surfaces. To ensure these objects come to rest, it is necessary to increase angular damping on rigid bodies made of these shapes. In addition, flagging the capsule/sphere's material with physx::PxMaterialFlag::eDISABLE_STRONG_FRICTION can help bring these shapes to rest. #### Character Cloth Sample * An NVIDIA GPU with Compute Capability 2.0 or higher is required for GPU accelerated simulation in the SampleCharacterCloth sample, if no such device is present then simulation will be performed on the CPU. * Note that this is not a general SDK requirement, the clothing SDK supports cards with Compute Capability < 2.0 but with limitations on mesh size. #### Character Controller * Releasing shapes of actors that are in touch with a character controller may lead to crashes. Releasing whole actors doesn't lead to the same problems. PxController::invalidateCache() can be used to work around these issues. Please also see the previous lists from 3.1.1 and earlier. # v3.1.2 December 2011 ## What's New In NVIDIA PhysX 3.1.2 #### General * Fixed wrong write/read clash checks. * Removed some compiler warnings from public header files. * Fixed PxScene::getActors() returning wrong actors when a start index is specified. #### Rigid Bodies * Fixed broken joint projection in connection with kinematics. * Fixed inaccurate normals returned from height field scene queries. * Fixed a crash when the geometry of a shape changes and then the actor gets removed from the scene while the simulation is running. * Fixed a crash when re-adding scene-query shape actors to scene. #### Particles * Fixed crash bug in particle simulation code on GPU. #### Cloth * Fixed a crash when GPU fabrics are shared between cloths. * Fixed a hang in cloth fiber cooker when handed non-manifold geometry. #### Samples * Fixed SampleVehicles doing an invalid write. * Fixed SampleVehicle jitter in profile build. ## Supported Platforms (available in separate packages) Unchanged from from 3.1.1. ## Known Issues And Limitations Unchanged from from 3.1. # v3.1.1 November 2011 ## What's New In NVIDIA PhysX 3.1.1 #### General * Ported samples to Linux. * Fixed crash bug in ConvX. * Fixed crash bug in the allocator code of PXC_NP_MEM_BLOCK_EXTENSIBLE. * Fixed crash bug when connected to PVD on various platforms. * Fixed bogus asserts due to overly strict validation of quaternions. * Fixed one frame lag in PVD scene statistics. * Fixed a number of OSX PVD sockets issues. * Fixed SampleSubmarine code that violated concurrent read/writes restriction. * Added warnings about read/write hazards to the checked build. * Fixed RepX not reading joint properties. * Fixed support for concurrent scene queries. * Fixed PhysX GPU Visual Indicator support. * Made it more clear in documentation that simulate(0) is not allowed. #### Rigid Bodies * eNOTIFY_TOUCH_LOST trigger events do now get reported if one of the objects in contact gets deleted (see documentation of PxTriggerPair for details). * Dynamic rigid bodies with trigger shapes only do not wake up other touching bodies anymore. * Added lost touch events for trigger reports when objects get deleted. * Fixed dynamic triggers waking up actors they are triggered by. * Removed an inapropriate assert from articulation code. * Fixed problem with the angular momentum conservation of articulations. * Fixed articulation sleep problems. * Fixed a linear velocity related bug in CCD. * Fixed crash bug CCD. * Optimized performance of joint information being sent to PVD. ## Supported Platforms (available in separate packages) #### Runtime * Microsoft Windows XP or later * Microsoft XBox 360 * Sony Playstation 3 * Android 2.2 or later for SDK, 2.3 or later required for samples * Linux (tested on Ubuntu) * Mac OS X #### Development * Microsoft Windows XP or later * Microsoft Visual Studio 2008, 2010 * Xcode 3 ## Known Issues And Limitations Unchanged from from 3.1. # v3.1 September 2011 ## What's New In NVIDIA PhysX 3.1 #### General * VC10 support has been introduced. * VC8 support has been discontinued. * Namespaces cleaned up. * Extensions, Character Controller and Vehicle source code made available in binary distribution. * Added x86,x64 suffix to PxTaskCUDA.dll * Removed boolean return value from PxScene::addActor(...), and similar API calls. * Added MacOS, Android and Linux to the list of supported platforms. See Supported Platforms below for details. * Upgraded GPU tech to CUDA 4. * Cleaned up a large number of warnings at C++ warning level 4, and set SDK to compile with warnings as errors. * Removed individual sample executables in favor of one Samples executable from PC and console builds. * Fixed alpha blending in samples. * Simplified some code in samples. * Improved ambient lighting in samples. * Made samples work with older graphics cards. * Improved and added more content the user's guide. * No longer passing NULL pointers to user allocator to deallocate. * Various improvements to Foundation and classes shared with APEX. #### Rigid Bodies * Rigid Body: High performance alternative convex narrow phase code available to source licensees. See PERSISTENT_CONTACT_MANIFOLD in the code. * Significant advancements in the continuous collision detection algorithm. * Optimizations and robustness improvements for articulations. * Added some helper code to the API. * Added sleep code for articulations. * Added support for vehicles with more than one chassis shape. * Solver iteration count for articulations. * Articulation limit padding configurable. * The reference count of meshes does now take the application's reference into acount as well and thus has increased by 1 (it used to count the number of objects referencing the mesh only). Note that a mesh does only get destroyed and removed from the list of meshes once the reference count reaches 0. * Fixed autowake parameter sometimes being ignored. * Constraint solver optimizations. * Improved behavior of character controller on steep slopes. * Binary serialization now saves names. * Removed some descriptors from API. * Removed the angular velocity term in the joint positional drive error formula. * Fixed bug in capsule sweep versus mesh. * Fixed a crash bug in the tire model. * Fixed crashing of single link articulations. * Fixed bug related to removing elements of an aggregate. * Fixed swapped wheel graphs in sample vehicle. * Fixed some slow moving bodies falling asleep in midair. * Fixed missing collisions after a call to resetFiltering. * Fixed broken autowake option in setAngularVelocity. * Fixed D6 joint linear limits being uninitialized. * A large number of misc. bug fixes and optimizations. * Improved documentation and error messages associated with running out of narrow phase buffer blocks. * Added articulation documentation. * Expanded manual sections on joints. * Improved reference doc for PxSceneQueryHitType. * Added reference doc for PxSerializable. #### Particles * Particle index allocation removed from SDK. Added index allocation pool to extensions. * Replaced GPU specific side band API PxPhysicsGpu and PxPhysics::getPhysicsGpu() with PxParticleGpu. * Memory optimizations on all platforms and options to reduce memory usage according to use case with new per particle system flags: * PxParticleBaseFlag::eCOLLISION_WITH_DYNAMIC_ACTORS * PxParticleBaseFlag::ePER_PARTICLE_COLLISION_CACHE_HINT * Fixed rare crash appearing with multi-threaded non-GPU particle systems and rigid bodies. * Fixed particles leaking through triangle mesh geometry on GPU. * Fixed fast particles tunneling through scene geometry in some cases. * Fixed erroneous collision of particles with teleporting rigid shapes (setGlobalPose). * Fixed particle sample behavior with some older GPU models. * Fixed a GPU particle crash bug. #### Cloth * A new solution for simulating cloth and clothing. #### Deformables * Deformables are deprecated and will be removed in the next release. There is a new optimized solution for clothing simulation (see documentation on PxCloth for details). ## Supported Platforms (available in separate packages) #### Runtime * Microsoft Windows XP or later * Microsoft XBox 360 * Sony Playstation 3 * Android 2.2 or later for SDK, 2.3 or later required for samples * Linux (SDK tested on Ubuntu, samples not yet ported) * Mac OS X #### Development * Microsoft Windows XP or later * Microsoft Visual Studio 2008, 2010 * Xcode 3 ## Known Issues And Limitations #### General * Under VC10, you may get warnings due to conflicting build configuration flags. Workaround: Clear the "Inherit from parent or project defaults" flag for all projects in Project->Properties->C/C++->Command Line. We plan to fix this for the 3.1 general availability release. #### Scene Query * Querying the scene (e.g. using raycastSingle()) from multiple threads simultaneously is not safe. #### Cloth * Even simple parameters of a PxCloth can not be set or accessed while the simulation is running. #### RepX * RepX fails to load elements of aggregate joint parameters (PxD6JointDrive etc.) Please also see the previous lists from 3.0. # v3.0 February 14<sup>th</sup>2011 ## What's New In NVIDIA PhysX 3.0 #### General This third major version of the SDK is a significant rewrite of the entire technology. We did away with a large amount of legacy clutter and replaced them with a wealth of new features and improvements. Because even the API changes are so significant, it is easier to see it as a whole new product rather than a long list of changes. #### What we removed: * The dedicated NVIDIA PhysX PPU hardware is not supported any more. * Scene compartments are not supported anymore. All created physical objects are now part of one and the same compartment. * Force fields are not part of the NVIDIA PhysX SDK anymore. * Splitting a simulation timestep into multiple substeps is not a functionality of the NVIDIA PhysX SDK any longer and has to be implemented above the SDK. #### Key new features: * Articulations: A way to create very stiff joint assemblies. * Serialization: Save objects in a binary format and load them back quickly! * Broad Phase Clustering: Put objects that belong together into a single broadphase volume. * Driverless Model: No need to worry about system software on PC anymore. * Dynamic Character Controller: A character controller that can robustly walk on dynamic objects. * Vehicle Library: A toolkit to make vehicles, including an all new tire model. * Non-Simulation Objects: A staging are outside of the simulation from where you can add things into the simulation at high speed. * Simulation Task Manager: Take control of the management of simulation tasks. * Stable Depenetration: Large penetrations can be gracefully recovered from. * Double Buffering: You can read from and write to the simulated objects while the simulation is running on another thread. * Mesh Scaling: Create different nonuniformly scaled instances of your meshes and convexes without duplicating the memory. * Distance Based Collision Detection: Have the simulation create contacts before objects touch, and do away with unsightly overlaps. * Fast Continuous Collision Detection: Have small and high speed objects collide correctly without sacrificing performance. * Significantly increased performance and memory footprint, especially on consoles. * Unified solver for deformables and rigid bodies for great interaction. * Triangle collision detection with deformables. * Support for our new Physics Visual Debugger, including integrated profiling. #### Math classes * Matrix based transforms have been replaced by quaternions. * All angles are now expressed in radians. IN PARTICULAR the PxQuat constructor from axis and angle as well as the getAngleAxis and fromAngleAxis methods now use radians rather than degrees. #### Rigid Bodies * Capsules are now defined to extend along the x rather than the y axis. * Triangle meshes do not support heightfield functionality anymore. Use the dedicated PxHeightField class instead. * Dynamic triangle mesh actors are not supported any longer. However, you can decompose your mesh into convex parts and create a dynamic actor consisting of these convex parts. * The deprecated heightfield property NxHeightFieldDesc::verticalExtent is not supported any longer. Please use the PxHeightFieldDesc::thickness parameter instead. * NxSpringAndDamperEffector is not supported anymore. Use PxDistanceJoint instead. * Joints are now part of the PhysX extensions library (PhysXExtensions). * Wheel shapes have been replaced by the more flexible entity PxWheel. A default wheel implementation, encapsulating most of the old wheel functionality, can be found in the PhysX extensions library (see PxDefaultWheel). * The NxUtilLib library has been removed. Sweep/overlap/raycast tests and other helper methods can be found in the new GeomUtils library. * Materials can no longer be accessed through indices. Per triangle material meshes need a material table which can be specified per shape (see PxShape::setMaterials() for details). * The default material is not available anymore. #### Particle Systems, Particle Fluids * The NxFluid class has been replaced with two classes for separation of functionality and ease of use. * PxParticleSystem: Particles colliding against the scene. * PxParticleFluid: Particles simulating a fluid (sph). * Simplified parameterization for particle systems. * Using absolute distances instead of relative multipliers to rest spacing * Simplified sph parameters * Unified collision parameters with deformable and rigid body features * Creating and releasing particles is now fully controlled by the application. * Particle lifetime management isn't provided through the SDK anymore. * Emitters have been removed from the SDK. * Drain shapes don't cause particles to be deleted directly, but to be flagged instead. * Initial particle creation from the particle system descriptor isn't supported anymore. * Particle data buffer handling has been moved to the SDK. * Per particle collision rest offset. * GPU accelerated particle systems. * Application controllable mesh mirroring to device memory. * Runtime switching between software and GPU accelerated implementation. ## Supported Platforms (available in separate packages) #### Runtime * Microsoft Windows XP or and later * Microsoft XBox360 * Sony Playstation 3 #### Development * Microsoft Windows XP or and later * Microsoft Visual Studio 2008 ## Known Issues And Limitations #### Rigid Bodies * Adding or removing a PxAggregate object to the scene is not possible while the simulation is running. #### Particle Systems * Releasing the Physics SDK may result in a crash when using GPU accelerated particle systems. * This can be avoided by doing the following before releasing the Physics SDK: * Releasing the PxScene objects that contain the GPU accelerated particle systems. * Releasing application mirrored meshes by calling PxPhysicsGpu::releaseTriangleMeshMirror(...), PxPhysicsGpu::releaseHeightFieldMirror(...) or PxPhysicsGpu::releaseConvexMeshMirror(...).
NVIDIA-Omniverse/PhysX/physx/dependencies.xml
<project toolsVersion="6.4"> <dependency name="clangMetadata" tags="requiredForDistro requiredForMetaGen"> <package name="clang-physxmetadata" version="4.0.0.32489833_1"/> </dependency> <dependency name="vswhere"> <package name="VsWhere" version="2.7.3111.17308_1.0" platforms="vc15win64 vc16win64 vc17win64 linux-crosscompile linux-aarch64-crosscompile "/> </dependency> <dependency name="PhysXDevice"> <package name="PhysXDevice" version="18.12.7.6" platforms="vc15win64 vc16win64 vc17win64"/> </dependency> <dependency name="freeglut"> <package name="freeglut-windows" version="3.4_1.1" platforms="vc15win64 vc16win64 vc17win64"/> </dependency> <dependency name="PhysXGpu"> <package name="PhysXGpu" version="105.1-5.3.1.6193-f2687f97-windows-public" platforms="vc15win64 vc16win64 vc17win64"/> <package name="PhysXGpu" version="105.1-5.3.1.6193-f2687f97-linux-x86_64-public" platforms="linux"/> <package name="PhysXGpu" version="105.1-5.3.1.6193-f2687f97-linux-aarch64-public" platforms="linux-aarch64"/> </dependency> <dependency name="opengllinux" tags="requiredForDistro"> <package name="opengl-linux" version="2017.5.19.1" platforms="linux"/> </dependency> <dependency name="rapidjson"> <package name="rapidjson" version="1.1.0-67fac85-073453e1" /> </dependency> </project>
NVIDIA-Omniverse/PhysX/physx/generate_projects.sh
#!/bin/bash +x if [ -n "${BASH_SOURCE[0]}" ]; then SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}") else SCRIPT_DIR=$(dirname "$0") fi PACKMAN_CMD="$SCRIPT_DIR/buildtools/packman/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi source "$PACKMAN_CMD" init if [[ $# -eq 0 ]] ; then exec "$SCRIPT_DIR/buildtools/packman/python.sh" "$SCRIPT_DIR/buildtools/cmake_generate_projects.py" exit 1 fi echo Running packman in preparation for cmake ... cutName=${1%%.*} export targetPlatform=$1 if [ "$1" = "$cutName" ] ; then source "$PACKMAN_CMD" pull "$SCRIPT_DIR/dependencies.xml" --platform $1 exec "$SCRIPT_DIR/buildtools/packman/python.sh" "$SCRIPT_DIR/buildtools/cmake_generate_projects.py" "$targetPlatform" else source "$PACKMAN_CMD" pull "$SCRIPT_DIR/dependencies.xml" --platform $cutName exec "$SCRIPT_DIR/buildtools/packman/python.sh" "$SCRIPT_DIR/buildtools/cmake_generate_projects.py" "$targetPlatform" fi status=$? if [ "$status" -ne "0" ]; then echo "Error $status" exit 1 fi
NVIDIA-Omniverse/PhysX/physx/README.md
# NVIDIA PhysX SDK 5 Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NVIDIA CORPORATION nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## Introduction Welcome to the NVIDIA PhysX SDK source code repository. The NVIDIA PhysX SDK is a scalable multi-platform physics solution. PhysX is integrated into [NVIDIA Omniverse](https://developer.nvidia.com/omniverse). See also [PhysX SDK on developer.nvidia.com](https://developer.nvidia.com/physx-sdk). Please see [Release Notes](./CHANGELOG.md) for updates pertaining to the latest version. ## CPU Source and GPU Binaries The source made available in this repository is restricted to CPU code. GPU acceleration is made available through precompiled binaries. ## User Guide and API Documentation The user guide and API documentation are available on [GitHub Pages](https://nvidia-omniverse.github.io/PhysX/physx/index.html). Please create an [Issue](https://github.com/NVIDIA-Omniverse/PhysX/issues/) if you find a documentation issue. ## Quick Start Instructions Platform specific environment and build information can be found in [documentation/platformreadme](./documentation/platformreadme). To begin, clone this repository onto your local drive. Then change directory to physx/, run ./generate_projects.[bat|sh] and follow on-screen prompts. This will let you select a platform specific solution to build. You can then build from the generated solution/make file in the platform- and configuration-specific folders in the ``compiler`` folder. ## Acknowledgements This depot references packages of third party open source software copyright their respective owners. For copyright details, please refer to the license files included in the packages. | Software | Copyright Holder | Package | |---------------------------|-------------------------------------------------------------------------------------|----------------------------------| | CMake | Kitware, Inc. and Contributors | cmake | | LLVM | University of Illinois at Urbana-Champaign | clang-physxmetadata | | Visual Studio Locator | Microsoft Corporation | VsWhere | | Freeglut | Pawel W. Olszta | freeglut-windows<br>opengl-linux | | Mesa 3-D graphics library | Brian Paul | opengl-linux | | RapidJSON | THL A29 Limited, a Tencent company, and Milo Yip<br>Alexander Chemeris (msinttypes) | rapidjson | | OpenGL Ext Wrangler Lib | Nigel Stewart, Milan Ikits, Marcelo E. Magallon, Lev Povalahev | [SDK_ROOT]/snippets/graphics |
NVIDIA-Omniverse/PhysX/physx/generate_projects.bat
:: Reset errorlevel status so we are not inheriting this state from the calling process: @call :CLEAN_EXIT @echo off call "%~dp0\buildtools\packman\packman" init set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%" IF %1.==. GOTO ADDITIONAL_PARAMS_MISSING :: Run packman to ensure dependencies are present and run cmake generation script afterwards echo Running packman in preparation for cmake ... set str1=%1 if not x%str1:.user=%==x%str1% ( call "%~dp0buildtools\packman\packman.cmd" pull "%~dp0dependencies.xml" --platform %str1:.user=% ) else ( call "%~dp0buildtools\packman\packman.cmd" pull "%~dp0dependencies.xml" --platform %1 ) for /f "usebackq tokens=*" %%i in (`"%PM_vswhere_PATH%\VsWhere.exe -version [15.0,16.0) -latest -property installationPath"`) do ( set Install2017Dir=%%i set VS150PATH="%%i" ) for /f "usebackq tokens=*" %%i in (`"%PM_vswhere_PATH%\VsWhere.exe -version [16.0,17.0) -latest -property installationPath"`) do ( set Install2019Dir=%%i set VS160PATH="%%i" ) for /f "usebackq tokens=*" %%i in (`"%PM_vswhere_PATH%\VsWhere.exe -version [17.0,18.0) -latest -property installationPath"`) do ( set Install2022Dir=%%i set VS170PATH="%%i" ) if exist "%Install2017Dir%\VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt" ( pushd "%Install2017Dir%\VC\Auxiliary\Build\" set /p Version=<Microsoft.VCToolsVersion.default.txt for /f "delims=" %%x in (Microsoft.VCToolsVersion.default.txt) do ( if not %%x=="" ( rem Example hardcodes x64 as the host and target architecture, but you could parse it from arguments set VS150CLPATH="%Install2017Dir%\VC\Tools\MSVC\%%x\bin\HostX64\x64\cl.exe" ) ) popd ) if exist "%Install2019Dir%\VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt" ( pushd "%Install2019Dir%\VC\Auxiliary\Build\" set /p Version=<Microsoft.VCToolsVersion.default.txt for /f "delims=" %%x in (Microsoft.VCToolsVersion.default.txt) do ( if not %%x=="" ( rem Example hardcodes x64 as the host and target architecture, but you could parse it from arguments set VS160CLPATH="%Install2019Dir%\VC\Tools\MSVC\%%x\bin\HostX64\x64\cl.exe" ) ) popd ) if exist "%Install2022Dir%\VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt" ( pushd "%Install2022Dir%\VC\Auxiliary\Build\" set /p Version=<Microsoft.VCToolsVersion.default.txt for /f "delims=" %%x in (Microsoft.VCToolsVersion.default.txt) do ( if not %%x=="" ( rem Example hardcodes x64 as the host and target architecture, but you could parse it from arguments set VS170CLPATH="%Install2022Dir%\VC\Tools\MSVC\%%x\bin\HostX64\x64\cl.exe" ) ) popd ) :ADDITIONAL_PARAMS_MISSING call "%~dp0buildtools\packman\python" "%~dp0buildtools\cmake_generate_projects.py" %1 if %ERRORLEVEL% neq 0 ( set /p DUMMY=Hit ENTER to continue... exit /b %errorlevel% ) else ( goto CLEAN_EXIT ) :CLEAN_EXIT @exit /b 0
NVIDIA-Omniverse/PhysX/physx/documentation/platformreadme/windows/README_WINDOWS.md
# NVIDIA PhysX SDK for Windows ## Location of Binaries: * SDK DLLs/LIBs: bin/ * PhysX Device DLLs: bin/ ## Required packages to generate projects: * Windows OS + headers for at least Win7 (`_WIN32_WINNT = 0x0601`) * CMake, minimum version 3.21 * Python, minimum version 3.5 ## PhysX GPU Acceleration: * Requires CUDA 11.8 compatible display driver. The corresponding driver version can be found [here](https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#cuda-major-component-versions__table-cuda-toolkit-driver-versions). ## Generating solutions for Visual Studio: * Solutions are generated through a script in the physx root directory: generate_projects.bat * The generate_projects.bat script expects a preset name as a parameter; if a parameter is not provided, it lists the available presets. * The generated solutions are in the folder compiler/"preset name". ## Notes: * The PhysXDevice/64.dll must be redistributed with GPU-enabled applications, and must live in the same directory as PhysXGpu.dll. * The nvcuda.dll and PhysXUpdateLoader/64.dll are loaded and checked for the NVIDIA Corporation digital signature. The signature is expected on all NVIDIA Corporation provided dlls. The application will exit if the signature check failed.
NVIDIA-Omniverse/PhysX/physx/documentation/platformreadme/linux/README_LINUX.md
# NVIDIA PhysX SDK for Linux ## Location of Binaries: * SDK libraries: bin/linux.clang ## Required packages to generate projects: * CMake, minimum version 3.14 * Python, minimum version 3.5 * curl Compilers: * For linux x86-64 builds we support Ubuntu LTS releases with their respective default compiler versions: * Ubuntu 20.04 LTS with gcc 9 or clang 10 * Ubuntu 22.04 LTS with gcc 11 or clang 14 * For linux aarch64 builds we support gcc version 9 ## Generating Makefiles: * Makefiles are generated through a script in the physx root directory: generate_projects.sh * The script generate_projects.sh expects a preset name as a parameter, if a parameter is not provided it does list the available presets and you can select one. * Generated solutions are placed in the folders compiler/linux-debug, compiler/linux-checked, compiler/linux-profile, compiler/linux-release. ## Building SDK: * Makefiles are in compiler/linux-debug etc * Clean solution: make clean * Build solution: make * Install solution: make install Note: Compile errors on unsupported compilers or platforms are frequently caused by additional warnings that are treated as errors by default. While we cannot offer support in this case we recommend removing all occurences of the `-Werror` flag in the file `physx/source/compiler/cmake/linux/CMakeLists.txt`. ## PhysX GPU Acceleration: * Running GPU-accelerated simulations requires a CUDA 11.8 compatible display driver. The corresponding driver version can be found [here](https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#cuda-major-component-versions__table-cuda-toolkit-driver-versions). * Note that CUDA is not required for building PhysX, it is only a runtime requirement for GPU-accelerated scenes. ## Required Packages for Building and Running PhysX Snippets: * freeglut3 * libglu1 * libxdamage-dev * libxmu6 ## How to select the PhysX GPU Device: * Set the environment variable PHYSX_GPU_DEVICE to the device ordinal on which GPU PhysX should run. Default is 0. * Example: export PHYSX_GPU_DEVICE="1"
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/helper.sh
## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions ## are met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## * Neither the name of NVIDIA CORPORATION nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY ## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY ## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #!/bin/bash set -e python generateMetaData.py $GEN_META_DATA_PARAMETER status=$? if [ "$status" -ne "0" ]; then echo "Error $status" exit 1 fi
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/PxBoilerPlate.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/generateMetaData.py
## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions ## are met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## * Neither the name of NVIDIA CORPORATION nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY ## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY ## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. import argparse import os import stat import sys import re import platform import shutil from lib import utils from lib import compare # test mode: create copy of reference files # update mode: try to open file in p4 if necessary def setup_targetdir(metaDataDir, isTestMode): if isTestMode: targetDir = metaDataDir + "_test" if os.path.isdir(targetDir): print("deleting", targetDir) shutil.rmtree(targetDir) def ignore_non_autogen(dir, files): return [f for f in files if not (os.path.isdir(os.path.join(dir, f)) or re.search(r"AutoGenerated", f))] shutil.copytree(metaDataDir, targetDir, ignore=ignore_non_autogen) #set write to new files: for root, dirs, files in os.walk(targetDir): for file in files: os.chmod(os.path.join(root, file) , stat.S_IWRITE|stat.S_IREAD) else: targetDir = metaDataDir if not utils.check_files_writable(utils.list_autogen_files(targetDir)): utils.try_checkout_files(utils.list_autogen_files(targetDir)) if not utils.check_files_writable(utils.list_autogen_files(targetDir)): print("auto generated meta data files not writable:", targetDir) print("aborting") sys.exit(1) utils.clear_files(utils.list_autogen_files(targetDir)) return targetDir # test mode: run perl script to compare reference and generated files def test_targetdir(targetDir, metaDataDir, isTestMode): if isTestMode: print("compare generated meta data files with reference meta data files:") result = compare.compareMetaDataDirectories(targetDir, metaDataDir) if not result: print("failed!") sys.exit(1) else: print("passed.") def get_osx_platform_path(): cmd = "xcodebuild -showsdks" (stdout, stderr) = utils.run_cmd(cmd) if stderr != "": print(stderr) sys.exit(1) match = re.search(r"(-sdk macosx\d+.\d+)", stdout, flags=re.MULTILINE) if not match: print("coundn't parse output of:\n", cmd, "\naborting!") sys.exit(1) sdkparam = match.group(0) cmd = "xcodebuild -version " + sdkparam + " Path" (sdkPath, stderr) = utils.run_cmd(cmd) if stderr != "": print(stderr) sys.exit(1) print("using sdk path:", sdkPath.rstrip()) return sdkPath.rstrip() def includeString(path): return ' -I"' + path + '"' ########################################################################################################### # main ########################################################################################################### parser = argparse.ArgumentParser(description='Generates meta data source files.') parser.add_argument('-test', help='enables testing mode, internal only', action='store_true') args = parser.parse_args() scriptDir = os.path.dirname(os.path.realpath(__file__)) try: os.makedirs("temp") except: None # find SDK_ROOT and PX_SHARED sdkRoot = utils.find_root_path(scriptDir, "source") clangRoot = os.path.normpath(os.environ['PM_clangMetadata_PATH']) print("testmode:", args.test) print("root sdk:", sdkRoot) print("root clang:", clangRoot) boilerPlateFile = os.path.join(sdkRoot, os.path.normpath("tools/physxmetadatagenerator/PxBoilerPlate.h")) includes = '' includes += includeString(sdkRoot + '/include') includes += includeString(sdkRoot + '/tools/physxmetadatagenerator') print("platform:", platform.system()) commonFlags = '-DNDEBUG -DPX_GENERATE_META_DATA -DPX_ENABLE_FEATURES_UNDER_CONSTRUCTION=0 -x c++-header -w -Wno-c++11-narrowing -fms-extensions ' if platform.system() == "Windows": debugFile = open("temp/clangCommandLine_windows.txt", "a") # read INCLUDE variable, set by calling batch script sysIncludes = os.environ['INCLUDE'] sysIncludes = sysIncludes.rstrip(';') sysIncludeList = sysIncludes.split(';') sysIncludeFlags = ' -isystem"' + '" -isystem"'.join(sysIncludeList) + '"' # for some reason -cc1 needs to go first in commonFlags commonFlags = '-cc1 ' + commonFlags platformFlags = '-DPX_VC=14 -D_WIN32 -std=c++14' + sysIncludeFlags clangExe = os.path.join(clangRoot, os.path.normpath('win32/bin/clang.exe')) elif platform.system() == "Linux": debugFile = open("temp/clangCommandLine_linux.txt", "a") platformFlags = '-std=c++0x' clangExe = os.path.join(clangRoot, os.path.normpath('linux32/bin/clang')) elif platform.system() == "Darwin": debugFile = open("temp/clangCommandLine_osx.txt", "a") platformFlags = '-std=c++0x -isysroot' + get_osx_platform_path() clangExe = os.path.join(clangRoot, os.path.normpath('osx/bin/clang')) else: print("unsupported platform, aborting!") sys.exit(1) commonFlags += ' -boilerplate-file ' + boilerPlateFile #some checks if not os.path.isfile(clangExe): print("didn't find,", clangExe, ", aborting!") sys.exit(1) clangExe = '"' + clangExe + '"' # required for execution of clang.exe os.environ["PWD"] = os.path.join(sdkRoot, os.path.normpath("tools/physxmetadatagenerator")) ############################### # PxPhysicsWithExtensions # ############################### print("PxPhysicsWithExtensions:") srcPath = "PxPhysicsWithExtensionsAPI.h" metaDataDir = os.path.join(sdkRoot, os.path.normpath("source/physxmetadata")) targetDir = setup_targetdir(metaDataDir, args.test) cmd = " ".join(["", clangExe, commonFlags, "", platformFlags, includes, srcPath, "-o", '"'+targetDir+'"']) print(cmd, file=debugFile) (stdout, stderr) = utils.run_cmd(cmd) if (stderr != "" or stdout != ""): print(stderr, "\n", stdout) print("wrote meta data files in", targetDir) test_targetdir(targetDir, metaDataDir, args.test) ############################### # PxVehicleExtension # ############################### print("PxVehicleExtension:") srcPath = "PxVehicleExtensionAPI.h" metaDataDir = os.path.join(sdkRoot, os.path.normpath("source/physxvehicle/src/physxmetadata")) includes += includeString(sdkRoot + '/include/vehicle') #TODO, get rid of source include includes += includeString(sdkRoot + '/source/physxvehicle/src') targetDir = setup_targetdir(metaDataDir, args.test) cmd = " ".join(["", clangExe, commonFlags, "", platformFlags, includes, srcPath, "-o", '"'+targetDir+'"']) print(cmd, file=debugFile) (stdout, stderr) = utils.run_cmd(cmd) if (stderr != "" or stdout != ""): print(stderr, "\n", stdout) print("wrote meta data files in", targetDir) test_targetdir(targetDir, metaDataDir, args.test)
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/PxExtensionsCommon.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_EXTENSIONS_COMMON_H #define PX_EXTENSIONS_COMMON_H #include <stdint.h> #include "foundation/PxSimpleTypes.h" #include "PxPhysXConfig.h" //Property overrides will output this exact property name instead of the general //property name that would be used. The properties need to have no template arguments //and exactly the same initialization as the classes they are overriding. struct PropertyOverride { const char* TypeName; const char* PropName; const char* OverridePropName; PropertyOverride( const char* tn, const char* pn, const char* opn ) : TypeName( tn ) , PropName( pn ) , OverridePropName( opn ) { } }; //The meta data generator ignores properties that are marked as disabled. Note that in the declaration //for properties that are defined via getter and setter methods, the 'get' and 'set' prefix can be dropped. //For protected fields the "m" prefix can be dropped, however for public fields the whole field qualifier is expected. struct DisabledPropertyEntry { const char* mTypeName; const char* mPropertyName; DisabledPropertyEntry( const char* inTypeName, const char* inValueName ) : mTypeName( inTypeName ) , mPropertyName( inValueName ) { } }; struct CustomProperty { const char* mPropertyType; const char* mTypeName; const char* mValueStructDefinition; const char* mValueStructInit; CustomProperty( const char* inTypeName, const char* inName, const char* inPropertyType, const char* valueStructDefinition, const char* valueStructInit ) : mPropertyType( inPropertyType ) , mTypeName( inTypeName ) , mValueStructDefinition( valueStructDefinition ) , mValueStructInit( valueStructInit ) { } }; #endif // PX_EXTENSIONS_COMMON_H
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/PxPhysicsWithExtensionsAPI.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_NXPHYSICSWITHEXTENSIONS_API #define PX_PHYSICS_NXPHYSICSWITHEXTENSIONS_API #include "PxExtensionsCommon.h" //Property overrides will output this exact property name instead of the general //property name that would be used. The properties need to have no template arguments //and exactly the same initialization as the classes they are overriding. static PropertyOverride gPropertyOverrides[] = { PropertyOverride( "PxShape", "Materials", "PxShapeMaterialsProperty" ), PropertyOverride( "PxRigidActor", "Shapes", "PxRigidActorShapeCollection" ), PropertyOverride( "PxArticulationReducedCoordinate", "Links", "PxArticulationLinkCollectionProp" ), }; //The meta data generator ignores properties that are marked as disabled. Note that in the declaration //for properties that are defined via getter and setter methods, the 'get' and 'set' prefix can be dropped. //For protected fields the "m" prefix can be dropped, however for public fields the whole field qualifier is expected. static DisabledPropertyEntry gDisabledProperties[] = { DisabledPropertyEntry( "PxSceneLimits", "IsValid" ), DisabledPropertyEntry( "PxSceneDesc", "TolerancesScale" ), DisabledPropertyEntry( "PxSceneDesc", "IsValid" ), DisabledPropertyEntry( "PxSceneDesc", "SceneQuerySystem" ), DisabledPropertyEntry( "PxShape", "Actor" ), DisabledPropertyEntry( "PxShape", "Geometry" ), DisabledPropertyEntry( "PxArticulationLink", "Articulation" ), DisabledPropertyEntry("PxArticulationJointReducedCoordinate", "ParentArticulationLink"), DisabledPropertyEntry("PxArticulationJointReducedCoordinate", "ChildArticulationLink"), DisabledPropertyEntry("PxArticulationJointReducedCoordinate", "Limit"), DisabledPropertyEntry( "PxArticulationReducedCoordinate", "LoopJoints"), DisabledPropertyEntry("PxArticulationReducedCoordinate", "Dofs"), DisabledPropertyEntry("PxArticulationReducedCoordinate", "CacheDataSize"), DisabledPropertyEntry("PxArticulationReducedCoordinate", "CoefficientMatrixSize"), DisabledPropertyEntry( "PxRigidActor", "IsRigidActor" ), DisabledPropertyEntry( "PxRigidActor", "ClassName" ), DisabledPropertyEntry( "PxRigidActor", "InternalActorIndex" ), DisabledPropertyEntry( "PxRigidStatic", "ClassName" ), DisabledPropertyEntry( "PxRigidDynamic", "ClassName" ), DisabledPropertyEntry( "PxRigidBody", "IsRigidBody" ), DisabledPropertyEntry( "PxRigidBody", "InternalIslandNodeIndex"), DisabledPropertyEntry( "PxRigidBody", "LinearVelocity"), DisabledPropertyEntry("PxRigidBody", "AngularVelocity"), DisabledPropertyEntry( "PxActor", "IsRigidStatic" ), DisabledPropertyEntry( "PxActor", "Type" ), DisabledPropertyEntry( "PxActor", "ClassName" ), DisabledPropertyEntry( "PxActor", "IsRigidDynamic" ), DisabledPropertyEntry( "PxActor", "IsArticulationLink" ), DisabledPropertyEntry( "PxActor", "IsRigidActor" ), DisabledPropertyEntry( "PxActor", "IsRigidBody" ), DisabledPropertyEntry( "PxMeshScale", "Inverse" ), DisabledPropertyEntry( "PxMeshScale", "IsIdentity" ), DisabledPropertyEntry( "PxMeshScale", "IsValidForTriangleMesh" ), DisabledPropertyEntry( "PxMeshScale", "IsValidForConvexMesh" ), DisabledPropertyEntry( "PxGeometry", "Type" ), DisabledPropertyEntry( "PxGeometry", "MTypePadding" ), DisabledPropertyEntry( "PxBoxGeometry", "IsValid" ), DisabledPropertyEntry( "PxSphereGeometry", "IsValid" ), DisabledPropertyEntry( "PxPlaneGeometry", "IsValid" ), DisabledPropertyEntry( "PxCapsuleGeometry", "IsValid" ), DisabledPropertyEntry( "PxConvexMeshGeometry", "IsValid" ), DisabledPropertyEntry( "PxTetrahedronMeshGeometry", "IsValid"), DisabledPropertyEntry( "PxTriangleMeshGeometry", "IsValid" ), DisabledPropertyEntry( "PxHeightFieldGeometry", "IsValid" ), DisabledPropertyEntry( "PxCustomGeometry", "IsValid" ), DisabledPropertyEntry( "PxCustomGeometry", "Callbacks" ), DisabledPropertyEntry( "PxJoint", "ClassName" ), DisabledPropertyEntry( "PxDistanceJoint", "ClassName" ), DisabledPropertyEntry( "PxContactJoint", "ClassName"), DisabledPropertyEntry( "PxGearJoint", "ClassName"), DisabledPropertyEntry( "PxRackAndPinionJoint", "ClassName"), DisabledPropertyEntry( "PxFixedJoint", "ClassName" ), DisabledPropertyEntry( "PxRevoluteJoint", "ClassName" ), DisabledPropertyEntry( "PxPrismaticJoint", "ClassName" ), DisabledPropertyEntry( "PxSphericalJoint", "ClassName" ), DisabledPropertyEntry( "PxD6Joint", "ClassName" ), DisabledPropertyEntry( "PxJointLimitParameters", "IsValid" ), DisabledPropertyEntry( "PxJointLimitParameters", "IsSoft" ), DisabledPropertyEntry( "PxJointLinearLimit", "IsValid" ), DisabledPropertyEntry( "PxJointLinearLimitPair", "IsValid" ), DisabledPropertyEntry( "PxJointAngularLimitPair", "IsValid" ), DisabledPropertyEntry( "PxJointLimitCone", "IsValid" ), DisabledPropertyEntry( "PxJointLimitPyramid", "IsValid" ), DisabledPropertyEntry( "PxD6JointDrive", "IsValid" ), DisabledPropertyEntry( "PxPhysics", "FLIPMaterials" ), DisabledPropertyEntry( "PxPhysics", "MPMMaterials" ), DisabledPropertyEntry( "PxScene", "ParticleSystems"), DisabledPropertyEntry( "PxScene", "FEMCloths"), DisabledPropertyEntry( "PxScene", "HairSystems"), // PT: added this for PVD-315. It's a mystery to me why we don't need to do that here for PxConvexMeshDesc. Maybe because the convex desc is in the cooking lib. DisabledPropertyEntry( "PxHeightFieldDesc", "IsValid" ), // DisabledPropertyEntry( "PxConstraint", "IsValid" ), // DisabledPropertyEntry( "PxTolerancesScale", "IsValid" ), }; //Append these properties to this type. static CustomProperty gCustomProperties[] = { #define DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( propName, propType, fieldName ) CustomProperty("PxSimulationStatistics", #propName, #propType, "PxU32 " #propName "[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];", "PxMemCopy( "#propName ", inSource->"#fieldName", sizeof( "#propName" ) );" ) DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( NbDiscreteContactPairs, NbDiscreteContactPairsProperty, nbDiscreteContactPairs ), DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( NbModifiedContactPairs, NbModifiedContactPairsProperty, nbModifiedContactPairs), DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( NbCCDPairs, NbCCDPairsProperty, nbCCDPairs), DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY( NbTriggerPairs, NbTriggerPairsProperty, nbTriggerPairs), #undef DEFINE_SIM_STATS_DUAL_INDEXED_PROPERTY CustomProperty( "PxSimulationStatistics", "NbShapes", "NbShapesProperty", "PxU32 NbShapes[PxGeometryType::eGEOMETRY_COUNT];", "PxMemCopy( NbShapes, inSource->nbShapes, sizeof( NbShapes ) );" ), CustomProperty( "PxScene", "SimulationStatistics", "SimulationStatisticsProperty", "PxSimulationStatistics SimulationStatistics;", "inSource->getSimulationStatistics(SimulationStatistics);" ), CustomProperty( "PxShape", "Geom", "PxShapeGeomProperty", "PxGeometryHolder Geom;", "Geom = PxGeometryHolder(inSource->getGeometry());" ), CustomProperty( "PxCustomGeometry", "CustomType", "PxCustomGeometryCustomTypeProperty", "PxU32 CustomType;", "PxCustomGeometry::Type t = inSource->callbacks->getCustomType(); CustomType = *reinterpret_cast<const PxU32*>(&t);" ), }; static const char* gImportantPhysXTypes[] = { "PxRigidStatic", "PxRigidDynamic", "PxShape", "PxArticulationReducedCoordinate", "PxArticulationLink", "PxMaterial", "PxFEMSoftBodyMaterial", "PxPBDMaterial", "PxFLIPMaterial", "PxMPMMaterial", "PxArticulationJointReducedCoordinate", "PxArticulationLimit", "PxArticulationDrive", "PxScene", "PxPhysics", "PxHeightFieldDesc", "PxMeshScale", "PxConstraint", "PxTolerancesScale", "PxSimulationStatistics", "PxSceneDesc", "PxSceneLimits", "PxgDynamicsMemoryConfig", "PxBroadPhaseDesc", "PxGeometry", "PxBoxGeometry", "PxCapsuleGeometry", "PxConvexMeshGeometry", "PxSphereGeometry", "PxPlaneGeometry", "PxTetrahedronMeshGeometry", "PxTriangleMeshGeometry", "PxHeightFieldGeometry", "PxCustomGeometry", "PxAggregate", "PxPruningStructure", //The mesh and heightfield buffers will need to be //handled by hand; they are very unorthodox compared //to the rest of the objects. #if PX_SUPPORT_GPU_PHYSX "PxgDynamicsMemoryConfig", #endif }; static const char* gExtensionPhysXTypes[] = { "PxD6JointDrive", "PxJointLinearLimit", "PxJointLinearLimitPair", "PxJointAngularLimitPair", "PxJointLimitCone", "PxJointLimitPyramid", "PxD6Joint", "PxDistanceJoint", "PxGearJoint", "PxRackAndPinionJoint", "PxContactJoint", "PxFixedJoint", "PxPrismaticJoint", "PxRevoluteJoint", "PxSphericalJoint", }; //We absolutely never generate information about these types, even if types //we do care about are derived from these types. static const char* gAvoidedPhysXTypes[] = { "PxSerializable", "PxObservable", "PxBase", "PxBaseFlag::Enum", "PxFLIPMaterial", "PxMPMMaterial", }; #include "PxPhysicsAPI.h" #include "extensions/PxExtensionsAPI.h" #endif
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/generateMetaData.bat
:: Redistribution and use in source and binary forms, with or without :: modification, are permitted provided that the following conditions :: are met: :: * Redistributions of source code must retain the above copyright :: notice, this list of conditions and the following disclaimer. :: * Redistributions in binary form must reproduce the above copyright :: notice, this list of conditions and the following disclaimer in the :: documentation and/or other materials provided with the distribution. :: * Neither the name of NVIDIA CORPORATION nor the names of its :: contributors may be used to endorse or promote products derived :: from this software without specific prior written permission. :: :: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY :: EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE :: IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR :: PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR :: CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, :: EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, :: PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR :: PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY :: OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT :: (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE :: OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. :: :: Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. @call :CLEAN_EXIT @echo off setlocal EnableDelayedExpansion :: batch script that runs generateMetaData.py :: see readme.txt pushd %~dp0 set PHYSX_ROOT_DIR=%CD%\..\..\ popd SET PHYSX_ROOT_DIR=%PHYSX_ROOT_DIR:\=/% echo "PhysX root: %PHYSX_ROOT_DIR%" set PACKMAN_CMD="%PHYSX_ROOT_DIR%buildtools\packman\packman" call "%PHYSX_ROOT_DIR%\buildtools\packman\packman" init if errorlevel 1 @exit /b %errorlevel% call %PACKMAN_CMD% pull "%PHYSX_ROOT_DIR%dependencies.xml" --platform vc15win64 --include-tag=requiredForDistro if errorlevel 1 exit /b %ERRORLEVEL% :: visual studio 2015 is required for the meta data generation :: run vcvarsall.bat to get visual studio developer console environment variables if not defined VS140COMNTOOLS ( goto no_vs140 ) echo calling: %VS140COMNTOOLS%..\..\VC\vcvarsall.bat call "%VS140COMNTOOLS%..\..\VC\vcvarsall.bat" %PM_PYTHON% %~dp0generateMetaData.py %1 if %ERRORLEVEL% neq 0 ( exit /b %errorlevel% ) else ( goto CLEAN_EXIT ) :no_vs140 echo echo make sure vs 2015 is installed. endlocal exit /b 1 :: ************************************************************************** :: functions :: ************************************************************************** :: find a root directory containing a known directory (as a hint) :find_root_path setlocal set START_DIR=%~1 set CONTAINED_DIR=%~2 :: search directory tree set TMP_DIR=!START_DIR! set OUT_DIR=0 :find_root_path_loop if exist !TMP_DIR!\!CONTAINED_DIR! goto :find_root_path_loop_end set TMP_DIR=!TMP_DIR!..\ :: normalize path pushd !TMP_DIR! set OUT_DIR=!CD! popd :: break if we reach the root, by checking the last two charactors if "!OUT_DIR:~-2!"==":\" ( set OUT_DIR=0 goto :find_root_path_loop_end ) goto :find_root_path_loop :find_root_path_loop_end ::echo no idea why we need to use % here endlocal & set _RESULT=%OUT_DIR% exit /b 0 :CLEAN_EXIT exit /b 0
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/generateMetaData.sh
## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions ## are met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## * Neither the name of NVIDIA CORPORATION nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY ## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY ## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #!/bin/bash +x SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" PHYSX_ROOT_DIR=$SCRIPT_DIR/../.. export GEN_META_DATA_PARAMETER=$1 PACKMAN_CMD="$PHYSX_ROOT_DIR/buildtools/packman/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}" if [ -f "$PACKMAN_CMD" ] ; then source "$PACKMAN_CMD" init source "$PACKMAN_CMD" pull "$PHYSX_ROOT_DIR/dependencies.xml" --platform linux --include-tag=requiredForMetaGen "${PM_PYTHON}" $SCRIPT_DIR/generateMetaData.py $GEN_META_DATA_PARAMETER fi status=$? if [ "$status" -ne "0" ]; then echo "Error $status" exit 1 fi
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/readme.txt
## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions ## are met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## * Neither the name of NVIDIA CORPORATION nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY ## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY ## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. If the Physx API is changed, the API level serialization meta data files need to be updated. This can be done by running: Windows: generateMetaData.bat Linux/MacOS: generateMetaData.sh Linux and osx distributions mostly come with Python pre-installed. On windows please download and install the latest python version from here: https://www.python.org/downloads and make sure to add python to your windows PATH (option in python installer) The generateMetaData.py tests for meta data files being writable. If not, p4 commands are used to open the files for edit before the update. If p4 is not available (or not configured for cmd line usage, see https://www.perforce.com/perforce/r15.1/manuals/p4guide/chapter.configuration.html: "Using config files"), the files need to be made writable manually. Requirements: Windows: Visual Studio 2015 Testing: generateMetaData.py -test runs the meta data generation in test mode. This mode checks that the current set of meta data files is still in sync with the PhysX API (i.e. already generated meta data files).
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/PxVehicleExtensionAPI.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_NXPHYSICSWITHVEHICLEEXTENSIONS_API #define PX_PHYSICS_NXPHYSICSWITHVEHICLEEXTENSIONS_API #include "PxExtensionsCommon.h" //The meta data generator ignores properties that are marked as disabled. Note that in the declaration //for properties that are defined via getter and setter methods, the 'get' and 'set' prefix can be dropped. //For protected fields the "m" prefix can be dropped, however for public fields the whole field qualifier is expected. static DisabledPropertyEntry gDisabledProperties[] = { DisabledPropertyEntry( "PxVehicleWheelsDynData", "MTireForceCalculators" ), DisabledPropertyEntry( "PxVehicleWheelsDynData", "TireForceShaderData" ), DisabledPropertyEntry( "PxVehicleWheelsDynData", "UserData" ), DisabledPropertyEntry( "PxVehicleWheels", "MActor" ), }; //Append these properties to this type. static CustomProperty gCustomProperties[] = { #define DEFINE_VEHICLETIREDATA_INDEXED_PROPERTY( propName, propType, fieldName ) CustomProperty("PxVehicleTireData", #propName, #propType, "PxReal " #propName "[3][2];", "PxMemCopy( "#propName ", inSource->"#fieldName", sizeof( "#propName" ) );" ) DEFINE_VEHICLETIREDATA_INDEXED_PROPERTY( MFrictionVsSlipGraph, MFrictionVsSlipGraphProperty, mFrictionVsSlipGraph), #undef DEFINE_VEHICLETIREDATA_INDEXED_PROPERTY CustomProperty( "PxVehicleEngineData", "MTorqueCurve", "MTorqueCurveProperty", "", "" ), }; static const char* gUserPhysXTypes[] = { "PxVehicleWheels", "PxVehicleWheelsSimData", "PxVehicleWheelsDynData", "PxVehicleDrive4W", "PxVehicleWheels4SimData", "PxVehicleDriveSimData4W", "PxVehicleWheelData", "PxVehicleSuspensionData", "PxVehicleDriveDynData", "PxVehicleDifferential4WData", "PxVehicleDifferentialNWData", "PxVehicleAckermannGeometryData", "PxVehicleTireLoadFilterData", "PxVehicleEngineData", "PxVehicleGearsData", "PxVehicleClutchData", "PxVehicleAutoBoxData", "PxVehicleTireData", "PxVehicleChassisData", "PxTorqueCurvePair", "PxVehicleDriveTank", "PxVehicleNoDrive", "PxVehicleDriveSimDataNW", "PxVehicleDriveNW", "PxVehicleAntiRollBarData", }; //We absolutely never generate information about these types, even if types //we do care about are derived from these types. static const char* gAvoidedPhysXTypes[] = { "PxSerializable", "PxObservable", "PxBase", "PxBaseFlag::Enum", }; #include "PxPhysicsAPI.h" #include "PxVehicleSuspWheelTire4.h" #endif
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/lib/__init__.py
## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions ## are met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## * Neither the name of NVIDIA CORPORATION nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY ## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY ## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/lib/utils.py
## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions ## are met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## * Neither the name of NVIDIA CORPORATION nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY ## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY ## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. # general utility module import os import sys import re import subprocess def list_autogen_files(dirPath): autogenFiles = [] for (root, subdirs, files) in os.walk(dirPath): files = [f for f in files if re.search(r"AutoGenerated", f)] autogenFiles.extend([os.path.join(root, f) for f in files]) return autogenFiles #checkout files with p4 if available def try_checkout_files(files): print("checking p4 connection parameter...") # checking p4 cmd = "p4" (stdout, stderr) = run_cmd(cmd) if stderr == "": print("p4 available.") else: print("p4 unavailable.") return cmd = "p4 edit " + " " + " ".join(files) (stdout, stderr) = run_cmd(cmd) print(stderr) print(stdout) # check files writability def check_files_writable(files): for file in files: if not os.access(file, os.W_OK): return False return True # find a root directory containing a known directory (as a hint) def find_root_path(startDir, containedDir): currentDir = startDir # search directory tree mergedDir = os.path.join(currentDir, containedDir) while not os.path.isdir(mergedDir): (currentDir, dir) = os.path.split(currentDir) if not dir: return None mergedDir = os.path.join(currentDir, containedDir) return currentDir def run_cmd(cmd, stdin = ""): process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdoutRaw, stderrRaw) = process.communicate(stdin.encode('utf-8')) stdout = stdoutRaw.decode(encoding='utf-8') stderr = stderrRaw.decode(encoding='utf-8') return (stdout, stderr) # clears content of files def clear_files(files): for file in files: open(file, 'w').close() ############################################################################## # internal functions ##############################################################################
NVIDIA-Omniverse/PhysX/physx/tools/physxmetadatagenerator/lib/compare.py
## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions ## are met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## * Neither the name of NVIDIA CORPORATION nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY ## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY ## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. # general utility module import os import sys import re from . import utils def compareMetaDataDirectories(candidateDir, referenceDir): print("reference dir:", referenceDir) print("candidate dir:", candidateDir) if not _checkFileExistence(candidateDir, referenceDir): return False referenceFiles = utils.list_autogen_files(referenceDir) #get corresponding candidate files without relying on os.walk order def mapRefToCand(refFile): return os.path.join(candidateDir, os.path.relpath(refFile, referenceDir)) candidateFiles = [mapRefToCand(f) for f in referenceFiles] for (fileCand, fileRef) in zip(candidateFiles, referenceFiles): timeCand = os.path.getmtime(fileCand) timeRef = os.path.getmtime(fileRef) if timeCand <= timeRef: print("last modified time of candidate is not later than last modified time of reference:") print("candidate:", fileCand, "\n", "reference:", fileRef) print("ref:", timeRef) print("cand:", timeCand) return False #_read_file_content will remove line endings(windows/unix), but not ignore empty lines candLines = _read_file_content(fileCand) refLines = _read_file_content(fileRef) if not (candLines and refLines): return False if len(candLines) != len(refLines): print("files got different number of lines:") print("candidate:", fileCand, "\n", "reference:", fileRef) print("ref:", len(refLines)) print("cand:", len(candLines)) return False for (i, (lineCand, lineRef)) in enumerate(zip(candLines, refLines)): if (lineCand != lineRef): print("candidate line is not equal to refence line:") print("candidate:", fileCand, "\n", "reference:", fileRef) print("@line number:", i) print("ref:", lineRef) print("cand:", lineCand) return False return True ############################################################################## # internal functions ############################################################################## #will remove line endings(windows/unix), but not ignore empty lines def _read_file_content(filePath): lines = [] try: with open(filePath, "r") as file: for line in file: lines.append(line.rstrip()) except: print("issue with reading file:", filePath) return lines def _checkFileExistence(candidateDir, referenceDir): candidateSet = set([os.path.relpath(f, candidateDir) for f in utils.list_autogen_files(candidateDir)]) referenceSet = set([os.path.relpath(f, referenceDir) for f in utils.list_autogen_files(referenceDir)]) missingSet = referenceSet - candidateSet if missingSet: print("the following files are missing from the candidates:\n", "\n".join(missingSet)) return False excessSet = candidateSet - referenceSet if excessSet: print("too many candidate files:\n", "\n".join(excessSet)) return False return True
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometry/SnippetCustomGeometryRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void debugRender(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if (nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } debugRender(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f, -0.2f, -0.7f)); Snippets::setupDefault("PhysX Snippet CustomGeometry", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometry/VoxelMap.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef VOXEL_MAP_H #define VOXEL_MAP_H #include "PxPhysicsAPI.h" /* VoxelMap inherits physx::PxCustomGeometry::Callbacks interface and provides implementations for 5 callback functions: - getLocalBounds - generateContacts - raycast - overlap - sweep It should be passed to PxCustomGeometry constructor. */ struct VoxelMap : physx::PxCustomGeometry::Callbacks, physx::PxUserAllocated { void setDimensions(int x, int y, int z); int dimX() const; int dimY() const; int dimZ() const; void setVoxelSize(float x, float y, float z); const physx::PxVec3& voxelSize() const; float voxelSizeX() const; float voxelSizeY() const; float voxelSizeZ() const; physx::PxVec3 extents() const; void setVoxel(int x, int y, int z, bool yes = true); bool voxel(int x, int y, int z) const; void clearVoxels(); void setFloorVoxels(int layers); void setWaveVoxels(); void voxelize(const physx::PxGeometry& geom, const physx::PxTransform& pose, bool add = true); physx::PxVec3 voxelPos(int x, int y, int z) const; void pointCoords(const physx::PxVec3& p, int& x, int& y, int& z) const; void getVoxelRegion(const physx::PxBounds3& b, int& sx, int& sy, int& sz, int& ex, int& ey, int& ez) const; // physx::PxCustomGeometry::Callbacks overrides DECLARE_CUSTOM_GEOMETRY_TYPE virtual physx::PxBounds3 getLocalBounds(const physx::PxGeometry&) const; virtual bool generateContacts(const physx::PxGeometry& geom0, const physx::PxGeometry& geom1, const physx::PxTransform& pose0, const physx::PxTransform& pose1, const physx::PxReal contactDistance, const physx::PxReal meshContactMargin, const physx::PxReal toleranceLength, physx::PxContactBuffer& contactBuffer) const; virtual physx::PxU32 raycast(const physx::PxVec3& origin, const physx::PxVec3& unitDir, const physx::PxGeometry& geom, const physx::PxTransform& pose, physx::PxReal maxDist, physx::PxHitFlags hitFlags, physx::PxU32 maxHits, physx::PxGeomRaycastHit* rayHits, physx::PxU32 stride, physx::PxRaycastThreadContext*) const; virtual bool overlap(const physx::PxGeometry& geom0, const physx::PxTransform& pose0, const physx::PxGeometry& geom1, const physx::PxTransform& pose1, physx::PxOverlapThreadContext*) const; virtual bool sweep(const physx::PxVec3& unitDir, const physx::PxReal maxDist, const physx::PxGeometry& geom0, const physx::PxTransform& pose0, const physx::PxGeometry& geom1, const physx::PxTransform& pose1, physx::PxGeomSweepHit& sweepHit, physx::PxHitFlags hitFlags, const physx::PxReal inflation, physx::PxSweepThreadContext*) const; virtual void visualize(const physx::PxGeometry&, physx::PxRenderOutput&, const physx::PxTransform&, const physx::PxBounds3&) const; virtual void computeMassProperties(const physx::PxGeometry&, physx::PxMassProperties&) const {} virtual bool usePersistentContactManifold(const physx::PxGeometry&, physx::PxReal&) const { return true; } private: int pacsX() const; int pacsY() const; int pacsZ() const; int m_dimensions[3]; physx::PxVec3 m_voxelSize; physx::PxArray<physx::PxU64> m_packs; }; #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometry/VoxelMap.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "collision/PxCollisionDefs.h" #include "PxImmediateMode.h" #include "VoxelMap.h" #include "common/PxRenderOutput.h" #include "geomutils/PxContactBuffer.h" using namespace physx; void VoxelMap::setDimensions(int x, int y, int z) { m_dimensions[0] = x; m_dimensions[1] = y; m_dimensions[2] = z; m_packs.resize(size_t(pacsX()) * size_t(pacsY()) * size_t(pacsZ()), 0U); } int VoxelMap::dimX() const { return m_dimensions[0]; } int VoxelMap::dimY() const { return m_dimensions[1]; } int VoxelMap::dimZ() const { return m_dimensions[2]; } int VoxelMap::pacsX() const { return (dimX() + 3) / 4; } int VoxelMap::pacsY() const { return (dimY() + 3) / 4; } int VoxelMap::pacsZ() const { return (dimZ() + 3) / 4; } PxVec3 VoxelMap::extents() const { return PxVec3(dimX() * voxelSizeX(), dimY() * voxelSizeY(), dimZ() * voxelSizeZ()); } void VoxelMap::setVoxelSize(float x, float y, float z) { m_voxelSize = PxVec3(x, y, z); } const PxVec3& VoxelMap::voxelSize() const { return m_voxelSize; } float VoxelMap::voxelSizeX() const { return m_voxelSize.x; } float VoxelMap::voxelSizeY() const { return m_voxelSize.y; } float VoxelMap::voxelSizeZ() const { return m_voxelSize.z; } void VoxelMap::setVoxel(int x, int y, int z, bool yes) { if (x < 0 || x >= int(dimX()) || y < 0 || y >= int(dimY()) || z < 0 || z >= int(dimZ())) return; int px = x / 4, py = y / 4, pz = z / 4; int bx = x & 3, by = y & 3, bz = z & 3; PxU64& p = m_packs[px + py * size_t(pacsX()) + pz * size_t(pacsX()) * size_t(pacsY())]; if (yes) p |= (PxU64(1) << (bx + by * 4 + bz * 16)); else p &= ~(PxU64(1) << (bx + by * 4 + bz * 16)); } bool VoxelMap::voxel(int x, int y, int z) const { if (x < 0 || x >= int(dimX()) || y < 0 || y >= int(dimY()) || z < 0 || z >= int(dimZ())) return false; int px = x / 4, py = y / 4, pz = z / 4; int bx = x & 3, by = y & 3, bz = z & 3; PxU64 p = m_packs[px + py * size_t(pacsX()) + pz * size_t(pacsX()) * size_t(pacsY())]; return (p & (PxU64(1) << (bx + by * 4 + bz * 16))) != 0; } void VoxelMap::clearVoxels() { memset(&m_packs[0], 0, m_packs.size() * sizeof(PxU64)); } void VoxelMap::setFloorVoxels(int layers) { for (int x = 0; x < dimX(); ++x) for (int y = 0; y < layers; ++y) for (int z = 0; z < dimZ(); ++z) setVoxel(x, y, z); } void VoxelMap::setWaveVoxels() { PxVec3 ext = extents(); for (int x = 0; x < dimX(); ++x) for (int y = 0; y < dimY(); ++y) for (int z = 0; z < dimZ(); ++z) { PxVec3 pos = voxelPos(x, y, z); float a = sqrtf((pos.x / ext.x) * (pos.x / ext.x) + (pos.z / ext.z) * (pos.z / ext.z)); if (a * 0.5f > pos.y / ext.y + 0.4f) setVoxel(x, y, z); } } void VoxelMap::voxelize(const PxGeometry& geom, const PxTransform& pose, bool add) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, geom, pose); int sx, sy, sz, ex, ey, ez; getVoxelRegion(bounds, sx, sy, sz, ex, ey, ez); for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (voxel(x, y, z)) { if (!add && PxGeometryQuery::pointDistance(voxelPos(x, y, z), geom, pose) == 0) setVoxel(x, y, z, false); } else { if (add && PxGeometryQuery::pointDistance(voxelPos(x, y, z), geom, pose) == 0) setVoxel(x, y, z); } } PxVec3 VoxelMap::voxelPos(int x, int y, int z) const { return PxVec3((x + 0.5f) * voxelSizeX(), (y + 0.5f) * voxelSizeY(), (z + 0.5f) * voxelSizeZ()) - extents() * 0.5f; } void VoxelMap::pointCoords(const PxVec3& p, int& x, int& y, int& z) const { PxVec3 l = p + extents() * 0.5f, s = voxelSize(); x = int(PxFloor(l.x / s.x)); y = int(PxFloor(l.y / s.y)); z = int(PxFloor(l.z / s.z)); } void VoxelMap::getVoxelRegion(const PxBounds3& b, int& sx, int& sy, int& sz, int& ex, int& ey, int& ez) const { pointCoords(b.minimum, sx, sy, sz); pointCoords(b.maximum, ex, ey, ez); } // physx::PxCustomGeometry::Callbacks overrides IMPLEMENT_CUSTOM_GEOMETRY_TYPE(VoxelMap) PxBounds3 VoxelMap::getLocalBounds(const PxGeometry&) const { return PxBounds3::centerExtents(PxVec3(0), extents()); } bool VoxelMap::generateContacts(const PxGeometry& /*geom0*/, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1, const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength, PxContactBuffer& contactBuffer) const { PxBoxGeometry voxelGeom(voxelSize() * 0.5f); PxGeometry* pGeom0 = &voxelGeom; const PxGeometry* pGeom1 = &geom1; PxTransform pose1in0 = pose0.transformInv(pose1); PxBounds3 bounds1; PxGeometryQuery::computeGeomBounds(bounds1, geom1, pose1in0, contactDistance); struct ContactRecorder : immediate::PxContactRecorder { PxContactBuffer* contactBuffer; ContactRecorder(PxContactBuffer& _contactBuffer) : contactBuffer(&_contactBuffer) {} virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/) { for (PxU32 i = 0; i < nbContacts; ++i) contactBuffer->contact(contactPoints[i]); return true; } } contactRecorder(contactBuffer); PxCache contactCache; struct ContactCacheAllocator : PxCacheAllocator { PxU8 buffer[1024]; ContactCacheAllocator() { memset(buffer, 0, sizeof(buffer)); } virtual PxU8* allocateCacheData(const PxU32 /*byteSize*/) { return reinterpret_cast<PxU8*>(size_t(buffer + 0xf) & ~0xf); } } contactCacheAllocator; int sx, sy, sz, ex, ey, ez; getVoxelRegion(bounds1, sx, sy, sz, ex, ey, ez); for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (voxel(x, y, z)) { PxTransform p0 = pose0.transform(PxTransform(voxelPos(x, y, z))); immediate::PxGenerateContacts(&pGeom0, &pGeom1, &p0, &pose1, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); } return true; } PxU32 VoxelMap::raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& /*geom*/, const PxTransform& pose, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* rayHits, PxU32 stride, PxRaycastThreadContext*) const { PxVec3 p = pose.transformInv(origin); PxVec3 n = pose.rotateInv(unitDir); PxVec3 s = voxelSize() * 0.5f; int x, y, z; pointCoords(p, x, y, z); int hitCount = 0; PxU8* hitBuffer = reinterpret_cast<PxU8*>(rayHits); float currDist = 0; PxVec3 hitN(0); while (currDist < maxDist) { PxVec3 v = voxelPos(x, y, z); if (voxel(x, y, z)) { PxGeomRaycastHit& h = *reinterpret_cast<PxGeomRaycastHit*>(hitBuffer + hitCount * stride); h.distance = currDist; if (hitFlags.isSet(PxHitFlag::ePOSITION)) h.position = origin + unitDir * currDist; if (hitFlags.isSet(PxHitFlag::eNORMAL)) h.normal = hitN; if (hitFlags.isSet(PxHitFlag::eFACE_INDEX)) h.faceIndex = (x) | (y << 10) | (z << 20); hitCount += 1; } if (hitCount == int(maxHits)) break; float step = FLT_MAX; int dx = 0, dy = 0, dz = 0; if (n.x > FLT_EPSILON) { float d = (v.x + s.x - p.x) / n.x; if (d < step) { step = d; dx = 1; dy = 0; dz = 0; } } if (n.x < -FLT_EPSILON) { float d = (v.x - s.x - p.x) / n.x; if (d < step) { step = d; dx = -1; dy = 0; dz = 0; } } if (n.y > FLT_EPSILON) { float d = (v.y + s.y - p.y) / n.y; if (d < step) { step = d; dx = 0; dy = 1; dz = 0; } } if (n.y < -FLT_EPSILON) { float d = (v.y - s.y - p.y) / n.y; if (d < step) { step = d; dx = 0; dy = -1; dz = 0; } } if (n.z > FLT_EPSILON) { float d = (v.z + s.z - p.z) / n.z; if (d < step) { step = d; dx = 0; dy = 0; dz = 1; } } if (n.z < -FLT_EPSILON) { float d = (v.z - s.z - p.z) / n.z; if (d < step) { step = d; dx = 0; dy = 0; dz = -1; } } x += dx; y += dy; z += dz; hitN = PxVec3(float(-dx), float(-dy), float(-dz)); currDist = step; } return hitCount; } bool VoxelMap::overlap(const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext*) const { PxBoxGeometry voxelGeom(voxelSize() * 0.5f); PxTransform pose1in0 = pose0.transformInv(pose1); PxBounds3 bounds1; PxGeometryQuery::computeGeomBounds(bounds1, geom1, pose1in0); int sx, sy, sz, ex, ey, ez; getVoxelRegion(bounds1, sx, sy, sz, ex, ey, ez); for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (voxel(x, y, z)) { PxTransform p0 = pose0.transform(PxTransform(voxelPos(x, y, z))); if (PxGeometryQuery::overlap(voxelGeom, p0, geom1, pose1, PxGeometryQueryFlags(0))) return true; } return false; } bool VoxelMap::sweep(const PxVec3& unitDir, const PxReal maxDist, const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxReal inflation, PxSweepThreadContext*) const { PxBoxGeometry voxelGeom(voxelSize() * 0.5f); PxTransform pose1in0 = pose0.transformInv(pose1); PxBounds3 b; PxGeometryQuery::computeGeomBounds(b, geom1, pose1in0, 0, 1.0f, PxGeometryQueryFlags(0)); PxVec3 n = pose0.rotateInv(unitDir); PxVec3 s = voxelSize(); int sx, sy, sz, ex, ey, ez; getVoxelRegion(b, sx, sy, sz, ex, ey, ez); int sx1, sy1, sz1, ex1, ey1, ez1; sx1 = sy1 = sz1 = -1; ex1 = ey1 = ez1 = 0; float currDist = 0; sweepHit.distance = FLT_MAX; while (currDist < maxDist && currDist < sweepHit.distance) { for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (voxel(x, y, z)) { if (x >= sx1 && x <= ex1 && y >= sy1 && y <= ey1 && z >= sz1 && z <= ez1) continue; PxGeomSweepHit hit; PxTransform p0 = pose0.transform(PxTransform(voxelPos(x, y, z))); if (PxGeometryQuery::sweep(unitDir, maxDist, geom1, pose1, voxelGeom, p0, hit, hitFlags, inflation, PxGeometryQueryFlags(0))) if (hit.distance < sweepHit.distance) sweepHit = hit; } PxVec3 mi = b.minimum, ma = b.maximum; PxVec3 bs = voxelPos(sx, sy, sz) - s, be = voxelPos(ex, ey, ez) + s; float dist = FLT_MAX; if (n.x > FLT_EPSILON) { float d = (be.x - ma.x) / n.x; if (d < dist) dist = d; } if (n.x < -FLT_EPSILON) { float d = (bs.x - mi.x) / n.x; if (d < dist) dist = d; } if (n.y > FLT_EPSILON) { float d = (be.y - ma.y) / n.y; if (d < dist) dist = d; } if (n.y < -FLT_EPSILON) { float d = (bs.y - mi.y) / n.y; if (d < dist) dist = d; } if (n.z > FLT_EPSILON) { float d = (be.z - ma.z) / n.z; if (d < dist) dist = d; } if (n.z < -FLT_EPSILON) { float d = (bs.z - mi.z) / n.z; if (d < dist) dist = d; } sx1 = sx; sy1 = sy; sz1 = sz; ex1 = ex; ey1 = ey; ez1 = ez; PxBounds3 b1 = b; b1.minimum += n * dist; b1.maximum += n * dist; getVoxelRegion(b1, sx, sy, sz, ex, ey, ez); currDist = dist; } return sweepHit.distance < FLT_MAX; } void VoxelMap::visualize(const physx::PxGeometry& /*geom*/, physx::PxRenderOutput& render, const physx::PxTransform& transform, const physx::PxBounds3& /*bound*/) const { PxVec3 extents = voxelSize() * 0.5f; render << transform; for (int x = 0; x < dimX(); ++x) for (int y = 0; y < dimY(); ++y) for (int z = 0; z < dimZ(); ++z) if (voxel(x, y, z)) { if (voxel(x + 1, y, z) && voxel(x - 1, y, z) && voxel(x, y + 1, z) && voxel(x, y - 1, z) && voxel(x, y, z + 1) && voxel(x, y, z - 1)) continue; PxVec3 pos = voxelPos(x, y, z); PxBounds3 bounds(pos - extents, pos + extents); physx::PxDebugBox box(bounds, true); render << box; } }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometry/SnippetCustomGeometry.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet shows how to use custom geometries in PhysX. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" #include "VoxelMap.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidStatic* gActor = NULL; static const int gVoxelMapDim = 20; static const float gVoxelMapSize = 80.0f; static VoxelMap* gVoxelMap; static PxArray<PxVec3> gVertices; static PxArray<PxU32> gIndices; static PxU32 gVertexCount; static PxU32 gIndexCount; static PxGeometryHolder gVoxelGeometryHolder; static const PxU32 gVertexOrder[12] = { 0, 2, 1, 2, 3, 1, 0, 1, 2, 2, 1, 3 }; PX_INLINE void cookVoxelFace(bool reverseWinding) { for (int i = 0; i < 6; ++i) { gIndices[gIndexCount + i] = gVertexCount + gVertexOrder[i + (reverseWinding ? 6 : 0)]; } gVertexCount += 4; gIndexCount += 6; } void cookVoxelMesh() { int faceCount = 0; gVertexCount = 0; gIndexCount = 0; float vx[2] = {gVoxelMap->voxelSize().x * -0.5f, gVoxelMap->voxelSize().x * 0.5f}; float vy[2] = {gVoxelMap->voxelSize().y * -0.5f, gVoxelMap->voxelSize().y * 0.5f}; float vz[2] = {gVoxelMap->voxelSize().z * -0.5f, gVoxelMap->voxelSize().z * 0.5f}; for (int x = 0; x < gVoxelMap->dimX(); ++x) for (int y = 0; y < gVoxelMap->dimY(); ++y) for (int z = 0; z < gVoxelMap->dimZ(); ++z) if (gVoxelMap->voxel(x, y, z)) { if (!gVoxelMap->voxel(x+1, y, z)) {faceCount++;} if (!gVoxelMap->voxel(x-1, y, z)) {faceCount++;} if (!gVoxelMap->voxel(x, y+1, z)) {faceCount++;} if (!gVoxelMap->voxel(x, y-1, z)) {faceCount++;} if (!gVoxelMap->voxel(x, y, z+1)) {faceCount++;} if (!gVoxelMap->voxel(x, y, z-1)) {faceCount++;} } gVertices.resize(faceCount*4); gIndices.resize(faceCount*6); for (int x = 0; x < gVoxelMap->dimX(); ++x) { for (int y = 0; y < gVoxelMap->dimY(); ++y) { for (int z = 0; z < gVoxelMap->dimZ(); ++z) { PxVec3 voxelPos = gVoxelMap->voxelPos(x, y, z); if (gVoxelMap->voxel(x, y, z)) { if (!gVoxelMap->voxel(x+1, y, z)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[1], vy[0], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[1], vy[0], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[1], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[1], vz[1]); cookVoxelFace(false); } if (!gVoxelMap->voxel(x-1, y, z)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[0], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[0], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[0], vy[1], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[0], vy[1], vz[1]); cookVoxelFace(true); } if (!gVoxelMap->voxel(x, y+1, z)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[1], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[1], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[1], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[1], vz[1]); cookVoxelFace(true); } if (!gVoxelMap->voxel(x, y-1, z)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[0], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[0], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[0], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[0], vz[1]); cookVoxelFace(false); } if (!gVoxelMap->voxel(x, y, z+1)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[0], vz[1]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[1], vz[1]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[0], vz[1]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[1], vz[1]); cookVoxelFace(false); } if (!gVoxelMap->voxel(x, y, z-1)) { gVertices[gVertexCount + 0] = voxelPos + PxVec3(vx[0], vy[0], vz[0]); gVertices[gVertexCount + 1] = voxelPos + PxVec3(vx[0], vy[1], vz[0]); gVertices[gVertexCount + 2] = voxelPos + PxVec3(vx[1], vy[0], vz[0]); gVertices[gVertexCount + 3] = voxelPos + PxVec3(vx[1], vy[1], vz[0]); cookVoxelFace(true); } } } } } const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; PxTriangleMeshDesc triangleMeshDesc; triangleMeshDesc.points.count = gVertexCount; triangleMeshDesc.points.data = gVertices.begin(); triangleMeshDesc.points.stride = sizeof(PxVec3); triangleMeshDesc.triangles.count = gIndexCount / 3; triangleMeshDesc.triangles.data = gIndices.begin(); triangleMeshDesc.triangles.stride = 3 * sizeof(PxU32); PxTriangleMesh* gTriangleMesh = PxCreateTriangleMesh(params, triangleMeshDesc); gVoxelGeometryHolder.storeAny( PxTriangleMeshGeometry(gTriangleMesh) ); } static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0), PxReal density = 1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i < size; i++) { for (PxU32 j = 0; j < size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void initVoxelMap() { gVoxelMap = PX_NEW(VoxelMap); gVoxelMap->setDimensions(gVoxelMapDim, gVoxelMapDim, gVoxelMapDim); gVoxelMap->setVoxelSize(gVoxelMapSize / gVoxelMapDim, gVoxelMapSize / gVoxelMapDim, gVoxelMapSize / gVoxelMapDim); gVoxelMap->setWaveVoxels(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gScene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 1.0f); gScene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.0f); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Create voxel map actor initVoxelMap(); PxRigidStatic* voxelMapActor = gPhysics->createRigidStatic(PxTransform(PxVec3(0, gVoxelMapSize * 0.5f, 0))); PxShape* shape = PxRigidActorExt::createExclusiveShape(*voxelMapActor, PxCustomGeometry(*gVoxelMap), *gMaterial); shape->setFlag(PxShapeFlag::eVISUALIZATION, true); gScene->addActor(*voxelMapActor); gActor = voxelMapActor; gActor->setActorFlag(PxActorFlag::eVISUALIZATION, true); // Ground plane PxRigidStatic* planeActor = gPhysics->createRigidStatic(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 0, 1)))); PxRigidActorExt::createExclusiveShape(*planeActor, PxPlaneGeometry(), *gMaterial); gScene->addActor(*planeActor); gScene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.f); gScene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 1.0f); createStack(PxTransform(PxVec3(0, 22, 0)), 10, 2.0f); cookVoxelMesh(); } void debugRender() { PxTransform pose = gActor->getGlobalPose(); Snippets::renderGeoms(1, &gVoxelGeometryHolder, &pose, false, PxVec3(0.5f)); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_DELETE(gVoxelMap); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); gVertices.reset(); gIndices.reset(); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetCustomGeometry done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch (toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0, 0, -1)) * 200, 3.0f); break; } } int snippetMain(int, const char* const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for (PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char* const*) { return 0; } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetCamera.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_SNIPPET_CAMERA_H #define PHYSX_SNIPPET_CAMERA_H #include "foundation/PxTransform.h" namespace Snippets { class Camera { public: Camera(const physx::PxVec3& eye, const physx::PxVec3& dir); void handleMouse(int button, int state, int x, int y); bool handleKey(unsigned char key, int x, int y, float speed = 0.5f); void handleMotion(int x, int y); void handleAnalogMove(float x, float y); physx::PxVec3 getEye() const; physx::PxVec3 getDir() const; physx::PxTransform getTransform() const; void setPose(const physx::PxVec3& eye, const physx::PxVec3& dir); void setSpeed(float speed); private: physx::PxVec3 mEye; physx::PxVec3 mDir; int mMouseX; int mMouseY; float mSpeed; }; } #endif //PHYSX_SNIPPET_CAMERA_H
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetCamera.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "SnippetCamera.h" #include <ctype.h> #include "foundation/PxMat33.h" using namespace physx; namespace Snippets { Camera::Camera(const PxVec3& eye, const PxVec3& dir) : mMouseX(0), mMouseY(0), mSpeed(2.0f) { mEye = eye; mDir = dir.getNormalized(); } void Camera::handleMouse(int button, int state, int x, int y) { PX_UNUSED(state); PX_UNUSED(button); mMouseX = x; mMouseY = y; } bool Camera::handleKey(unsigned char key, int x, int y, float speed) { PX_UNUSED(x); PX_UNUSED(y); const PxVec3 viewY = mDir.cross(PxVec3(0,1,0)).getNormalized(); switch(toupper(key)) { case 'W': mEye += mDir*mSpeed*speed; break; case 'S': mEye -= mDir*mSpeed*speed; break; case 'A': mEye -= viewY*mSpeed*speed; break; case 'D': mEye += viewY*mSpeed*speed; break; default: return false; } return true; } void Camera::handleAnalogMove(float x, float y) { PxVec3 viewY = mDir.cross(PxVec3(0,1,0)).getNormalized(); mEye += mDir*y; mEye += viewY*x; } void Camera::handleMotion(int x, int y) { const int dx = mMouseX - x; const int dy = mMouseY - y; const PxVec3 viewY = mDir.cross(PxVec3(0,1,0)).getNormalized(); const float Sensitivity = PxPi * 0.5f / 180.0f; const PxQuat qx(Sensitivity * dx, PxVec3(0,1,0)); mDir = qx.rotate(mDir); const PxQuat qy(Sensitivity * dy, viewY); mDir = qy.rotate(mDir); mDir.normalize(); mMouseX = x; mMouseY = y; } PxTransform Camera::getTransform() const { PxVec3 viewY = mDir.cross(PxVec3(0,1,0)); if(viewY.normalize()<1e-6f) return PxTransform(mEye); const PxMat33 m(mDir.cross(viewY), viewY, -mDir); return PxTransform(mEye, PxQuat(m)); } PxVec3 Camera::getEye() const { return mEye; } PxVec3 Camera::getDir() const { return mDir; } void Camera::setPose(const PxVec3& eye, const PxVec3& dir) { mEye = eye; mDir = dir; } void Camera::setSpeed(float speed) { mSpeed = speed; } }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetRender.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_SNIPPET_RENDER_H #define PHYSX_SNIPPET_RENDER_H #include "PxPhysicsAPI.h" #include "foundation/PxPreprocessor.h" #if PX_WINDOWS #include <windows.h> #pragma warning(disable: 4505) #include <GL/glew.h> #include <GL/freeglut.h> #elif PX_LINUX_FAMILY #if PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-identifier" #endif #include <GL/glew.h> #include <GL/freeglut.h> #if PX_CLANG #pragma clang diagnostic pop #endif #elif PX_OSX #include <GL/glew.h> #include <GLUT/glut.h> #else #error platform not supported. #endif typedef void (*KeyboardCallback) (unsigned char key, const physx::PxTransform& camera); typedef void (*RenderCallback) (); typedef void (*ExitCallback) (); namespace Snippets { class Camera; void setupDefault(const char* name, Camera* camera, KeyboardCallback kbcb, RenderCallback rdcb, ExitCallback excb); Camera* getCamera(); physx::PxVec3 computeWorldRayF(float xs, float ys, const physx::PxVec3& camDir); PX_FORCE_INLINE physx::PxVec3 computeWorldRay(int xs, int ys, const physx::PxVec3& camDir) { return computeWorldRayF(float(xs), float(ys), camDir); } physx::PxU32 getScreenWidth(); physx::PxU32 getScreenHeight(); void enableVSync(bool vsync); void startRender(const Camera* camera, float nearClip = 1.0f, float farClip = 10000.0f, float fov=60.0f, bool setupLighting=true); void finishRender(); void print(const char* text); class TriggerRender { public: virtual bool isTrigger(physx::PxShape*) const = 0; }; #if PX_SUPPORT_GPU_PHYSX class SharedGLBuffer { public: SharedGLBuffer(); ~SharedGLBuffer(); void initialize(physx::PxCudaContextManager* contextManager); void allocate(physx::PxU32 sizeInBytes); void release(); void* map(); void unmap(); private: physx::PxCudaContextManager* cudaContextManager; void* vbo_res; void* devicePointer; public: GLuint vbo; //Opengl vertex buffer object physx::PxU32 size; }; #endif void initFPS(); void showFPS(int updateIntervalMS = 30, const char* info = NULL); void renderSoftBody(physx::PxSoftBody* softBody, const physx::PxVec4* deformedPositionsInvMass, bool shadows, const physx::PxVec3& color = physx::PxVec3(0.0f, 0.75f, 0.0f)); void renderActors(physx::PxRigidActor** actors, const physx::PxU32 numActors, bool shadows = false, const physx::PxVec3& color = physx::PxVec3(0.0f, 0.75f, 0.0f), TriggerRender* cb = NULL, bool changeColorForSleepingActors = true, bool wireframePass=true); // void renderGeoms(const physx::PxU32 nbGeoms, const physx::PxGeometry* geoms, const physx::PxTransform* poses, bool shadows, const physx::PxVec3& color); void renderGeoms(const physx::PxU32 nbGeoms, const physx::PxGeometryHolder* geoms, const physx::PxTransform* poses, bool shadows, const physx::PxVec3& color); void renderMesh(physx::PxU32 nbVerts, const physx::PxVec3* verts, physx::PxU32 nbTris, const physx::PxU32* indices, const physx::PxVec3& color, const physx::PxVec3* normals = NULL, bool flipFaceOrientation = false); void renderMesh(physx::PxU32 nbVerts, const physx::PxVec4* verts, physx::PxU32 nbTris, const physx::PxU32* indices, const physx::PxVec3& color, const physx::PxVec4* normals = NULL, bool flipFaceOrientation = false); void renderMesh(physx::PxU32 nbVerts, const physx::PxVec4* verts, physx::PxU32 nbTris, const void* indices, bool hasSixteenBitIndices, const physx::PxVec3& color, const physx::PxVec4* normals = NULL, bool flipFaceOrientation = false, bool enableBackFaceCulling = true); void renderHairSystem(physx::PxHairSystem* hairSystem, const physx::PxVec4* vertexPositionInvMass, physx::PxU32 numVertices); void DrawLine(const physx::PxVec3& p0, const physx::PxVec3& p1, const physx::PxVec3& color); void DrawPoints(const physx::PxArray<physx::PxVec3>& pts, const physx::PxVec3& color, float scale); void DrawPoints(const physx::PxArray<physx::PxVec3>& pts, const physx::PxArray<physx::PxVec3>& colors, float scale); void DrawPoints(const physx::PxArray<physx::PxVec4>& pts, const physx::PxVec3& color, float scale); void DrawPoints(const physx::PxArray<physx::PxVec4>& pts, const physx::PxArray<physx::PxVec3>& colors, float scale); void DrawPoints(GLuint vbo, physx::PxU32 numPoints, const physx::PxVec3& color, float scale, physx::PxU32 coordinatesPerPoint = 3, physx::PxU32 stride = 4 * sizeof(float), size_t offset = 0); void DrawLines(GLuint vbo, physx::PxU32 numPoints, const physx::PxVec3& color, float scale, physx::PxU32 coordinatesPerPoint = 3, physx::PxU32 stride = 4 * sizeof(float), size_t offset = 0); void DrawIcosahedraPoints(const physx::PxArray<physx::PxVec3>& pts, const physx::PxVec3& color, float radius); void DrawFrame(const physx::PxVec3& pt, float scale=1.0f); void DrawBounds(const physx::PxBounds3& box); void DrawBounds(const physx::PxBounds3& box, const physx::PxVec3& color); void DrawMeshIndexedNoNormals(GLuint vbo, GLuint elementbuffer, GLuint numTriangles, const physx::PxVec3& color, physx::PxU32 stride = 4 * sizeof(float)); void DrawMeshIndexed(GLuint vbo, GLuint elementbuffer, GLuint numTriangles, const physx::PxVec3& color, physx::PxU32 stride = 6 * sizeof(float)); GLuint CreateTexture(physx::PxU32 width, physx::PxU32 height, const GLubyte* buffer, bool createMipmaps); void UpdateTexture(GLuint texId, physx::PxU32 width, physx::PxU32 height, const GLubyte* buffer, bool createMipmaps); void ReleaseTexture(GLuint texId); void DrawRectangle(float x_start, float x_end, float y_start, float y_end, const physx::PxVec3& color_top, const physx::PxVec3& color_bottom, float alpha, physx::PxU32 screen_width, physx::PxU32 screen_height, bool draw_outline, bool texturing); void DisplayTexture(GLuint texId, physx::PxU32 size, physx::PxU32 margin); } #endif //PHYSX_SNIPPET_RENDER_H
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #define USE_CUDA_INTEROP (!PX_PUBLIC_RELEASE) #if (PX_SUPPORT_GPU_PHYSX && USE_CUDA_INTEROP) #if PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include "cuda.h" #include "SnippetRender.h" #include "cudaGL.h" #if PX_LINUX && PX_CLANG #pragma clang diagnostic pop #endif #else #include "SnippetRender.h" #endif #include "SnippetFontRenderer.h" #include "SnippetCamera.h" #include "foundation/PxArray.h" #include "foundation/PxMathUtils.h" #include <vector> #define MAX_NUM_ACTOR_SHAPES 128 #define INITIAL_SCREEN_WIDTH 768 #define INITIAL_SCREEN_HEIGHT 768 using namespace physx; static GLFontRenderer gTexter; static float gCylinderData[]={ 1.0f,0.0f,1.0f,1.0f,0.0f,1.0f,1.0f,0.0f,0.0f,1.0f,0.0f,0.0f, 0.866025f,0.500000f,1.0f,0.866025f,0.500000f,1.0f,0.866025f,0.500000f,0.0f,0.866025f,0.500000f,0.0f, 0.500000f,0.866025f,1.0f,0.500000f,0.866025f,1.0f,0.500000f,0.866025f,0.0f,0.500000f,0.866025f,0.0f, -0.0f,1.0f,1.0f,-0.0f,1.0f,1.0f,-0.0f,1.0f,0.0f,-0.0f,1.0f,0.0f, -0.500000f,0.866025f,1.0f,-0.500000f,0.866025f,1.0f,-0.500000f,0.866025f,0.0f,-0.500000f,0.866025f,0.0f, -0.866025f,0.500000f,1.0f,-0.866025f,0.500000f,1.0f,-0.866025f,0.500000f,0.0f,-0.866025f,0.500000f,0.0f, -1.0f,-0.0f,1.0f,-1.0f,-0.0f,1.0f,-1.0f,-0.0f,0.0f,-1.0f,-0.0f,0.0f, -0.866025f,-0.500000f,1.0f,-0.866025f,-0.500000f,1.0f,-0.866025f,-0.500000f,0.0f,-0.866025f,-0.500000f,0.0f, -0.500000f,-0.866025f,1.0f,-0.500000f,-0.866025f,1.0f,-0.500000f,-0.866025f,0.0f,-0.500000f,-0.866025f,0.0f, 0.0f,-1.0f,1.0f,0.0f,-1.0f,1.0f,0.0f,-1.0f,0.0f,0.0f,-1.0f,0.0f, 0.500000f,-0.866025f,1.0f,0.500000f,-0.866025f,1.0f,0.500000f,-0.866025f,0.0f,0.500000f,-0.866025f,0.0f, 0.866026f,-0.500000f,1.0f,0.866026f,-0.500000f,1.0f,0.866026f,-0.500000f,0.0f,0.866026f,-0.500000f,0.0f, 1.0f,0.0f,1.0f,1.0f,0.0f,1.0f,1.0f,0.0f,0.0f,1.0f,0.0f,0.0f }; static std::vector<PxVec3>* gVertexBuffer = NULL; static int gLastTime = 0; static int gFrameCounter = 0; static char gTitle[256]; static bool gWireFrame = false; static PX_FORCE_INLINE void prepareVertexBuffer() { if(!gVertexBuffer) gVertexBuffer = new std::vector<PxVec3>; gVertexBuffer->clear(); } static PX_FORCE_INLINE void pushVertex(const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& n) { PX_ASSERT(gVertexBuffer); gVertexBuffer->push_back(n); gVertexBuffer->push_back(v0); gVertexBuffer->push_back(n); gVertexBuffer->push_back(v1); gVertexBuffer->push_back(n); gVertexBuffer->push_back(v2); } static PX_FORCE_INLINE void pushVertex(const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& n0, const PxVec3& n1, const PxVec3& n2, float normalSign = 1) { PX_ASSERT(gVertexBuffer); gVertexBuffer->push_back(normalSign * n0); gVertexBuffer->push_back(v0); gVertexBuffer->push_back(normalSign * n1); gVertexBuffer->push_back(v1); gVertexBuffer->push_back(normalSign * n2); gVertexBuffer->push_back(v2); } static PX_FORCE_INLINE const PxVec3* getVertexBuffer() { PX_ASSERT(gVertexBuffer); return &(*gVertexBuffer)[0]; } static void releaseVertexBuffer() { if(gVertexBuffer) { delete gVertexBuffer; gVertexBuffer = NULL; } } static void renderSoftBodyGeometry(const PxTetrahedronMesh& mesh, const PxVec4* deformedPositionsInvMass) { const int tetFaces[4][3] = { {0,2,1}, {0,1,3}, {0,3,2}, {1,2,3} }; //Get the deformed vertices //const PxVec3* vertices = mesh.getVertices(); const PxU32 tetCount = mesh.getNbTetrahedrons(); const PxU32 has16BitIndices = mesh.getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES; const void* indexBuffer = mesh.getTetrahedrons(); prepareVertexBuffer(); const PxU32* intIndices = reinterpret_cast<const PxU32*>(indexBuffer); const PxU16* shortIndices = reinterpret_cast<const PxU16*>(indexBuffer); PxU32 numTotalTriangles = 0; for (PxU32 i = 0; i < tetCount; ++i) { PxU32 vref[4]; if (has16BitIndices) { vref[0] = *shortIndices++; vref[1] = *shortIndices++; vref[2] = *shortIndices++; vref[3] = *shortIndices++; } else { vref[0] = *intIndices++; vref[1] = *intIndices++; vref[2] = *intIndices++; vref[3] = *intIndices++; } for (PxU32 j = 0; j < 4; ++j) { const PxVec4& v0 = deformedPositionsInvMass[vref[tetFaces[j][0]]]; const PxVec4& v1 = deformedPositionsInvMass[vref[tetFaces[j][1]]]; const PxVec4& v2 = deformedPositionsInvMass[vref[tetFaces[j][2]]]; PxVec3 fnormal = (v1.getXYZ() - v0.getXYZ()).cross(v2.getXYZ() - v0.getXYZ()); fnormal.normalize(); pushVertex(v0.getXYZ(), v1.getXYZ(), v2.getXYZ(), fnormal); numTotalTriangles++; } } glPushMatrix(); glScalef(1.0f, 1.0f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer + 1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); } static void renderGeometry(const PxGeometry& geom) { if (gWireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); switch(geom.getType()) { case PxGeometryType::eBOX: { const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom); glScalef(boxGeom.halfExtents.x, boxGeom.halfExtents.y, boxGeom.halfExtents.z); glutSolidCube(2); } break; case PxGeometryType::eSPHERE: { const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom); glutSolidSphere(GLdouble(sphereGeom.radius), 10, 10); } break; case PxGeometryType::eCAPSULE: { const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom); const PxF32 radius = capsuleGeom.radius; const PxF32 halfHeight = capsuleGeom.halfHeight; //Sphere glPushMatrix(); glTranslatef(halfHeight, 0.0f, 0.0f); glScalef(radius,radius,radius); glutSolidSphere(1, 10, 10); glPopMatrix(); //Sphere glPushMatrix(); glTranslatef(-halfHeight, 0.0f, 0.0f); glScalef(radius,radius,radius); glutSolidSphere(1, 10, 10); glPopMatrix(); //Cylinder glPushMatrix(); glTranslatef(-halfHeight, 0.0f, 0.0f); glScalef(2.0f*halfHeight, radius,radius); glRotatef(90.0f,0.0f,1.0f,0.0f); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), gCylinderData); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), gCylinderData+3); glDrawArrays(GL_TRIANGLE_STRIP, 0, 13*2); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); } break; case PxGeometryType::eCONVEXMESH: { const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom); //Compute triangles for each polygon. const PxVec3& scale = convexGeom.scale.scale; PxConvexMesh* mesh = convexGeom.convexMesh; const PxU32 nbPolys = mesh->getNbPolygons(); const PxU8* polygons = mesh->getIndexBuffer(); const PxVec3* verts = mesh->getVertices(); PxU32 nbVerts = mesh->getNbVertices(); PX_UNUSED(nbVerts); prepareVertexBuffer(); PxU32 numTotalTriangles = 0; for(PxU32 i = 0; i < nbPolys; i++) { PxHullPolygon data; mesh->getPolygonData(i, data); const PxU32 nbTris = PxU32(data.mNbVerts - 2); const PxU8 vref0 = polygons[data.mIndexBase + 0]; PX_ASSERT(vref0 < nbVerts); for(PxU32 j=0;j<nbTris;j++) { const PxU32 vref1 = polygons[data.mIndexBase + 0 + j + 1]; const PxU32 vref2 = polygons[data.mIndexBase + 0 + j + 2]; //generate face normal: PxVec3 e0 = verts[vref1] - verts[vref0]; PxVec3 e1 = verts[vref2] - verts[vref0]; PX_ASSERT(vref1 < nbVerts); PX_ASSERT(vref2 < nbVerts); PxVec3 fnormal = e0.cross(e1); fnormal.normalize(); pushVertex(verts[vref0], verts[vref1], verts[vref2], fnormal); numTotalTriangles++; } } glPushMatrix(); glScalef(scale.x, scale.y, scale.z); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), vertexBuffer+1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glPopMatrix(); } break; case PxGeometryType::eTRIANGLEMESH: { const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(geom); const PxTriangleMesh& mesh = *triGeom.triangleMesh; const PxVec3 scale = triGeom.scale.scale; const PxU32 triangleCount = mesh.getNbTriangles(); const PxU32 has16BitIndices = mesh.getTriangleMeshFlags() & PxTriangleMeshFlag::e16_BIT_INDICES; const void* indexBuffer = mesh.getTriangles(); const PxVec3* vertices = mesh.getVertices(); prepareVertexBuffer(); const PxU32* intIndices = reinterpret_cast<const PxU32*>(indexBuffer); const PxU16* shortIndices = reinterpret_cast<const PxU16*>(indexBuffer); PxU32 numTotalTriangles = 0; for(PxU32 i=0; i < triangleCount; ++i) { PxU32 vref0, vref1, vref2; if(has16BitIndices) { vref0 = *shortIndices++; vref1 = *shortIndices++; vref2 = *shortIndices++; } else { vref0 = *intIndices++; vref1 = *intIndices++; vref2 = *intIndices++; } const PxVec3& v0 = vertices[vref0]; const PxVec3& v1 = vertices[vref1]; const PxVec3& v2 = vertices[vref2]; PxVec3 fnormal = (v1 - v0).cross(v2 - v0); fnormal.normalize(); pushVertex(v0, v1, v2, fnormal); numTotalTriangles++; } glPushMatrix(); glScalef(scale.x, scale.y, scale.z); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), vertexBuffer+1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); } break; case PxGeometryType::eTETRAHEDRONMESH: { const int tetFaces[4][3] = { {0,2,1}, {0,1,3}, {0,3,2}, {1,2,3} }; const PxTetrahedronMeshGeometry& tetGeom = static_cast<const PxTetrahedronMeshGeometry&>(geom); const PxTetrahedronMesh& mesh = *tetGeom.tetrahedronMesh; //Get the deformed vertices const PxVec3* vertices = mesh.getVertices(); const PxU32 tetCount = mesh.getNbTetrahedrons(); const PxU32 has16BitIndices = mesh.getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES; const void* indexBuffer = mesh.getTetrahedrons(); prepareVertexBuffer(); const PxU32* intIndices = reinterpret_cast<const PxU32*>(indexBuffer); const PxU16* shortIndices = reinterpret_cast<const PxU16*>(indexBuffer); PxU32 numTotalTriangles = 0; for (PxU32 i = 0; i < tetCount; ++i) { PxU32 vref[4]; if (has16BitIndices) { vref[0] = *shortIndices++; vref[1] = *shortIndices++; vref[2] = *shortIndices++; vref[3] = *shortIndices++; } else { vref[0] = *intIndices++; vref[1] = *intIndices++; vref[2] = *intIndices++; vref[3] = *intIndices++; } for (PxU32 j = 0; j < 4; ++j) { const PxVec3& v0 = vertices[vref[tetFaces[j][0]]]; const PxVec3& v1 = vertices[vref[tetFaces[j][1]]]; const PxVec3& v2 = vertices[vref[tetFaces[j][2]]]; PxVec3 fnormal = (v1 - v0).cross(v2 - v0); fnormal.normalize(); pushVertex(v0, v1, v2, fnormal); numTotalTriangles++; } } glPushMatrix(); glScalef(1.0f, 1.0f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer + 1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); } break; default: break; } if (gWireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } static Snippets::Camera* gCamera = NULL; static KeyboardCallback gKbCb = NULL; static PxU32 gScreenWidth = 0; static PxU32 gScreenHeight = 0; static void defaultReshapeCallback(int width, int height) { glViewport(0, 0, width, height); gTexter.setScreenResolution(width, height); gScreenWidth = width; gScreenHeight = height; } static void defaultIdleCallback() { glutPostRedisplay(); } static bool gMoveCamera = false; static void defaultMotionCallback(int x, int y) { if(gCamera && gMoveCamera) gCamera->handleMotion(x, y); } static void defaultMouseCallback(int button, int state, int x, int y) { if(button==0) gMoveCamera = state==0; if(gCamera) gCamera->handleMouse(button, state, x, y); } static void defaultKeyboardCallback(unsigned char key, int x, int y) { if(key==27) glutLeaveMainLoop(); if (key == 110) //n gWireFrame = !gWireFrame; const bool status = gCamera ? gCamera->handleKey(key, x, y) : false; if(!status && gKbCb) gKbCb(key, gCamera ? gCamera->getTransform() : PxTransform(PxIdentity)); } static void defaultSpecialCallback(int key, int x, int y) { switch(key) { case GLUT_KEY_UP: key='W'; break; case GLUT_KEY_DOWN: key='S'; break; case GLUT_KEY_LEFT: key='A'; break; case GLUT_KEY_RIGHT: key='D'; break; } const bool status = gCamera ? gCamera->handleKey((unsigned char)key, x, y) : false; if(!status && gKbCb) gKbCb((unsigned char)key, gCamera ? gCamera->getTransform() : PxTransform(PxIdentity)); } static ExitCallback gUserExitCB = NULL; static void defaultExitCallback() { releaseVertexBuffer(); if(gUserExitCB) (gUserExitCB)(); } static void setupDefaultWindow(const char* name, RenderCallback rdcb) { char* namestr = new char[strlen(name)+1]; strcpy(namestr, name); int argc = 1; char* argv[1] = { namestr }; glutInit(&argc, argv); gScreenWidth = INITIAL_SCREEN_WIDTH; gScreenHeight = INITIAL_SCREEN_HEIGHT; gTexter.init(); gTexter.setScreenResolution(gScreenWidth, gScreenHeight); gTexter.setColor(1.0f, 1.0f, 1.0f, 1.0f); glutInitWindowSize(gScreenWidth, gScreenHeight); glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH); int mainHandle = glutCreateWindow(name); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } glutSetWindow(mainHandle); glutReshapeFunc(defaultReshapeCallback); glutIdleFunc(defaultIdleCallback); glutKeyboardFunc(defaultKeyboardCallback); glutSpecialFunc(defaultSpecialCallback); glutMouseFunc(defaultMouseCallback); glutMotionFunc(defaultMotionCallback); if(rdcb) glutDisplayFunc(rdcb); defaultMotionCallback(0,0); delete[] namestr; } static void setupDefaultRenderState() { // Setup default render states // glClearColor(0.3f, 0.4f, 0.5f, 1.0); glClearColor(0.2f, 0.2f, 0.2f, 1.0); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); // Setup lighting /* glEnable(GL_LIGHTING); PxReal ambientColor[] = { 0.0f, 0.1f, 0.2f, 0.0f }; PxReal diffuseColor[] = { 1.0f, 1.0f, 1.0f, 0.0f }; PxReal specularColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; PxReal position[] = { 100.0f, 100.0f, 400.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, ambientColor); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseColor); glLightfv(GL_LIGHT0, GL_SPECULAR, specularColor); glLightfv(GL_LIGHT0, GL_POSITION, position); glEnable(GL_LIGHT0);*/ } static void InitLighting() { glEnable(GL_COLOR_MATERIAL); glEnable(GL_NORMALIZE); const float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, zero); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, zero); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, zero); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, zero); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, zero); glEnable(GL_LIGHTING); PxVec3 Dir(-1.0f, 1.0f, 0.5f); // PxVec3 Dir(0.0f, 1.0f, 0.0f); Dir.normalize(); const float AmbientValue = 0.3f; const float ambientColor0[] = { AmbientValue, AmbientValue, AmbientValue, 0.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, ambientColor0); const float specularColor0[] = { 0.0f, 0.0f, 0.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_SPECULAR, specularColor0); const float diffuseColor0[] = { 1.0f, 1.0f, 1.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseColor0); const float position0[] = { Dir.x, Dir.y, Dir.z, 0.0f }; glLightfv(GL_LIGHT0, GL_POSITION, position0); glEnable(GL_LIGHT0); // glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // glColor4f(0.0f, 0.0f, 0.0f, 0.0f); /* glEnable(GL_LIGHTING); PxReal ambientColor[] = { 0.0f, 0.1f, 0.2f, 0.0f }; PxReal diffuseColor[] = { 1.0f, 1.0f, 1.0f, 0.0f }; PxReal specularColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; PxReal position[] = { 100.0f, 100.0f, 400.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, ambientColor); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseColor); glLightfv(GL_LIGHT0, GL_SPECULAR, specularColor); glLightfv(GL_LIGHT0, GL_POSITION, position); glEnable(GL_LIGHT0);*/ if(0) { glEnable(GL_FOG); glFogi(GL_FOG_MODE,GL_LINEAR); //glFogi(GL_FOG_MODE,GL_EXP); //glFogi(GL_FOG_MODE,GL_EXP2); glFogf(GL_FOG_START, 0.0f); glFogf(GL_FOG_END, 100.0f); glFogf(GL_FOG_DENSITY, 0.005f); // glClearColor(0.2f, 0.2f, 0.2f, 1.0); // const PxVec3 FogColor(0.2f, 0.2f, 0.2f); const PxVec3 FogColor(0.3f, 0.4f, 0.5f); // const PxVec3 FogColor(1.0f); glFogfv(GL_FOG_COLOR, &FogColor.x); } } namespace Snippets { void initFPS() { gLastTime = glutGet(GLUT_ELAPSED_TIME); } void showFPS(int updateIntervalMS, const char* info) { ++gFrameCounter; int currentTime = glutGet(GLUT_ELAPSED_TIME); if (currentTime - gLastTime > updateIntervalMS) { if (info) sprintf(gTitle, " FPS : %4.0f%s", gFrameCounter * 1000.0 / (currentTime - gLastTime), info); else sprintf(gTitle, " FPS : %4.0f", gFrameCounter * 1000.0 / (currentTime - gLastTime)); glutSetWindowTitle(gTitle); gLastTime = currentTime; gFrameCounter = 0; } } PxU32 getScreenWidth() { return gScreenWidth; } PxU32 getScreenHeight() { return gScreenHeight; } void enableVSync(bool vsync) { #if PX_WIN32 || PX_WIN64 typedef void (APIENTRY * PFNWGLSWAPINTERVALPROC) (GLenum interval); PFNWGLSWAPINTERVALPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALPROC)wglGetProcAddress("wglSwapIntervalEXT"); wglSwapIntervalEXT(vsync); #else PX_UNUSED(vsync); #endif } void setupDefault(const char* name, Camera* camera, KeyboardCallback kbcb, RenderCallback rdcb, ExitCallback excb) { gCamera = camera; gKbCb = kbcb; setupDefaultWindow(name, rdcb); setupDefaultRenderState(); enableVSync(true); glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); gUserExitCB = excb; atexit(defaultExitCallback); } Camera* getCamera() { return gCamera; } static float gNearClip = 0.0f; static float gFarClip = 0.0f; static float gFOV = 60.0f; static float gTextScale = 0.0f; static float gTextY = 0.0f; PxVec3 computeWorldRayF(float xs, float ys, const PxVec3& camDir) { const float Width = float(gScreenWidth); const float Height = float(gScreenHeight); // Recenter coordinates in camera space ([-1, 1]) const float u = ((xs - Width*0.5f)/Width)*2.0f; const float v = -((ys - Height*0.5f)/Height)*2.0f; // Adjust coordinates according to camera aspect ratio const float HTan = tanf(0.25f * fabsf(PxDegToRad(gFOV * 2.0f))); const float VTan = HTan*(Width/Height); // Ray in camera space const PxVec3 CamRay(VTan*u, HTan*v, 1.0f); // Compute ray in world space PxVec3 Right, Up; PxComputeBasisVectors(camDir, Right, Up); const PxMat33 invView(-Right, Up, camDir); return invView.transform(CamRay).getNormalized(); } void startRender(const Camera* camera, float clipNear, float clipFar, float fov, bool setupLighting) { const PxVec3 cameraEye = camera->getEye(); const PxVec3 cameraDir = camera->getDir(); gNearClip = clipNear; gFarClip = clipFar; gFOV = fov; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Setup camera glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(GLdouble(fov), GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)), GLdouble(clipNear), GLdouble(clipFar)); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(GLdouble(cameraEye.x), GLdouble(cameraEye.y), GLdouble(cameraEye.z), GLdouble(cameraEye.x + cameraDir.x), GLdouble(cameraEye.y + cameraDir.y), GLdouble(cameraEye.z + cameraDir.z), 0.0, 1.0, 0.0); glColor4f(0.4f, 0.4f, 0.4f, 1.0f); if(setupLighting) InitLighting(); gTextScale = 0.0175f * float(INITIAL_SCREEN_HEIGHT) / float(gScreenHeight); gTextY = 1.0f - gTextScale; gTexter.setColor(1.0f, 1.0f, 1.0f, 1.0f); } void finishRender() { glutSwapBuffers(); } void print(const char* text) { gTexter.print(0.0f, gTextY, gTextScale, text); gTextY -= gTextScale; } const PxVec3 shadowDir(0.0f, -0.7071067f, -0.7071067f); const PxReal shadowMat[] = { 1,0,0,0, -shadowDir.x / shadowDir.y,0,-shadowDir.z / shadowDir.y,0, 0,0,1,0, 0,0,0,1 }; void renderSoftBody(PxSoftBody* softBody, const PxVec4* deformedPositionsInvMass, bool shadows, const PxVec3& color) { PxShape* shape = softBody->getShape(); const PxMat44 shapePose(PxIdentity); // (PxShapeExt::getGlobalPose(*shapes[j], *actors[i])); const PxGeometry& geom = shape->getGeometry(); const PxTetrahedronMeshGeometry& tetGeom = static_cast<const PxTetrahedronMeshGeometry&>(geom); const PxTetrahedronMesh& mesh = *tetGeom.tetrahedronMesh; glPushMatrix(); glMultMatrixf(&shapePose.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); renderSoftBodyGeometry(mesh, deformedPositionsInvMass); glPopMatrix(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if (shadows) { glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); //glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glColor4f(0.1f, 0.1f, 0.1f, 1.0f); renderSoftBodyGeometry(mesh, deformedPositionsInvMass); glEnable(GL_LIGHTING); glPopMatrix(); } } void renderHairSystem(physx::PxHairSystem* /*hairSystem*/, const physx::PxVec4* vertexPositionInvMass, PxU32 numVertices) { const PxVec3 color{ 1.0f, 0.0f, 0.0f }; const PxSphereGeometry geom(0.05f); // draw the volume glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); for(PxU32 j=0;j<numVertices;j++) { const PxMat44 shapePose(PxTransform(reinterpret_cast<const PxVec3&>(vertexPositionInvMass[j]))); glPushMatrix(); glMultMatrixf(&shapePose.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); renderGeometry(geom); glPopMatrix(); } // draw the cage lines const GLdouble aspect = GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip * 1.005f), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0f, 0.0f, 0.0f, 1.0f); for (PxU32 j = 0; j < numVertices; j++) { const PxMat44 shapePose(PxTransform(reinterpret_cast<const PxVec3&>(vertexPositionInvMass[j]))); glPushMatrix(); glMultMatrixf(&shapePose.column0.x); renderGeometry(geom); glPopMatrix(); } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); } void renderActors(PxRigidActor** actors, const PxU32 numActors, bool shadows, const PxVec3& color, TriggerRender* cb, bool changeColorForSleepingActors, bool wireframePass) { PxShape* shapes[MAX_NUM_ACTOR_SHAPES]; for(PxU32 i=0;i<numActors;i++) { const PxU32 nbShapes = actors[i]->getNbShapes(); PX_ASSERT(nbShapes <= MAX_NUM_ACTOR_SHAPES); actors[i]->getShapes(shapes, nbShapes); bool sleeping; if (changeColorForSleepingActors) sleeping = actors[i]->is<PxRigidDynamic>() ? actors[i]->is<PxRigidDynamic>()->isSleeping() : false; else sleeping = false; for(PxU32 j=0;j<nbShapes;j++) { const PxMat44 shapePose(PxShapeExt::getGlobalPose(*shapes[j], *actors[i])); const PxGeometry& geom = shapes[j]->getGeometry(); const bool isTrigger = cb ? cb->isTrigger(shapes[j]) : shapes[j]->getFlags() & PxShapeFlag::eTRIGGER_SHAPE; if(isTrigger) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render object glPushMatrix(); glMultMatrixf(&shapePose.column0.x); if(sleeping) { const PxVec3 darkColor = color * 0.25f; glColor4f(darkColor.x, darkColor.y, darkColor.z, 1.0f); } else glColor4f(color.x, color.y, color.z, 1.0f); renderGeometry(geom); glPopMatrix(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(shadows) { glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); //glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glColor4f(0.1f, 0.1f, 0.1f, 1.0f); renderGeometry(geom); glEnable(GL_LIGHTING); glPopMatrix(); } } } if(wireframePass) { const GLdouble aspect = GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip*1.005f), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0f, 0.0f, 0.0f, 1.0f); for(PxU32 i=0;i<numActors;i++) { const PxU32 nbShapes = actors[i]->getNbShapes(); PX_ASSERT(nbShapes <= MAX_NUM_ACTOR_SHAPES); actors[i]->getShapes(shapes, nbShapes); for(PxU32 j=0;j<nbShapes;j++) { const PxMat44 shapePose(PxShapeExt::getGlobalPose(*shapes[j], *actors[i])); glPushMatrix(); glMultMatrixf(&shapePose.column0.x); renderGeometry(shapes[j]->getGeometry()); glPopMatrix(); } } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); } } /*static const PxU32 gGeomSizes[] = { sizeof(PxSphereGeometry), sizeof(PxPlaneGeometry), sizeof(PxCapsuleGeometry), sizeof(PxBoxGeometry), sizeof(PxConvexMeshGeometry), sizeof(PxTriangleMeshGeometry), sizeof(PxHeightFieldGeometry), }; void renderGeoms(const PxU32 nbGeoms, const PxGeometry* geoms, const PxTransform* poses, bool shadows, const PxVec3& color) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); const PxVec3 shadowDir(0.0f, -0.7071067f, -0.7071067f); const PxReal shadowMat[]={ 1,0,0,0, -shadowDir.x/shadowDir.y,0,-shadowDir.z/shadowDir.y,0, 0,0,1,0, 0,0,0,1 }; const PxU8* stream = reinterpret_cast<const PxU8*>(geoms); for(PxU32 j=0;j<nbGeoms;j++) { const PxMat44 shapePose(poses[j]); const PxGeometry& geom = *reinterpret_cast<const PxGeometry*>(stream); stream += gGeomSizes[geom.getType()]; // render object glPushMatrix(); glMultMatrixf(&shapePose.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); renderGeometry(geom); glPopMatrix(); if(shadows) { glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); glColor4f(0.1f, 0.2f, 0.3f, 1.0f); renderGeometry(geom); glEnable(GL_LIGHTING); glPopMatrix(); } } }*/ void renderGeoms(const PxU32 nbGeoms, const PxGeometryHolder* geoms, const PxTransform* poses, bool shadows, const PxVec3& color) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); //const PxVec3 shadowDir(0.0f, -0.7071067f, -0.7071067f); //const PxReal shadowMat[]={ 1,0,0,0, -shadowDir.x/shadowDir.y,0,-shadowDir.z/shadowDir.y,0, 0,0,1,0, 0,0,0,1 }; for(PxU32 j=0;j<nbGeoms;j++) { const PxMat44 shapePose(poses[j]); const PxGeometry& geom = geoms[j].any(); // render object glPushMatrix(); glMultMatrixf(&shapePose.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); renderGeometry(geom); glPopMatrix(); if(shadows) { glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); //glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glColor4f(0.1f, 0.1f, 0.1f, 1.0f); renderGeometry(geom); glEnable(GL_LIGHTING); glPopMatrix(); } } if(1) { const GLdouble aspect = GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip*1.005f), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0f, 0.0f, 0.0f, 1.0f); for(PxU32 j=0;j<nbGeoms;j++) { const PxMat44 shapePose(poses[j]); const PxGeometry& geom = geoms[j].any(); // render object glPushMatrix(); glMultMatrixf(&shapePose.column0.x); renderGeometry(geom); glPopMatrix(); } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); } } PX_FORCE_INLINE PxVec3 getVec3(const physx::PxU8* data, const PxU32 index, const PxU32 sStrideInBytes) { return *reinterpret_cast<const PxVec3*>(data + index * sStrideInBytes); } void renderMesh(physx::PxU32 /*nbVerts*/, const physx::PxU8* verts, const PxU32 vertsStrideInBytes, physx::PxU32 nbTris, const void* indices, bool has16bitIndices, const physx::PxVec3& color, const physx::PxU8* normals, const PxU32 normalsStrideInBytes, bool flipFaceOrientation, bool enableBackFaceCulling = true) { if (nbTris == 0) return; glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); const PxMat44 idt(PxIdentity); glPushMatrix(); glMultMatrixf(&idt.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); if (!enableBackFaceCulling) glDisable(GL_CULL_FACE); { prepareVertexBuffer(); PxU32 numTotalTriangles = 0; for(PxU32 i=0; i <nbTris; ++i) { PxU32 vref0, vref1, vref2; if (has16bitIndices) { vref0 = ((const PxU16*)indices)[i * 3 + 0]; vref1 = ((const PxU16*)indices)[i * 3 + 1]; vref2 = ((const PxU16*)indices)[i * 3 + 2]; } else { vref0 = ((const PxU32*)indices)[i * 3 + 0]; vref1 = ((const PxU32*)indices)[i * 3 + 1]; vref2 = ((const PxU32*)indices)[i * 3 + 2]; } const PxVec3& v0 = getVec3(verts, vref0, vertsStrideInBytes); const PxVec3& v1 = flipFaceOrientation ? getVec3(verts, vref2, vertsStrideInBytes) : getVec3(verts, vref1, vertsStrideInBytes); const PxVec3& v2 = flipFaceOrientation ? getVec3(verts, vref1, vertsStrideInBytes) : getVec3(verts, vref2, vertsStrideInBytes); if (normals) { const PxVec3& n0 = getVec3(normals, vref0, normalsStrideInBytes); const PxVec3& n1 = flipFaceOrientation ? getVec3(normals, vref2, normalsStrideInBytes) : getVec3(normals, vref1, normalsStrideInBytes); const PxVec3& n2 = flipFaceOrientation ? getVec3(normals, vref1, normalsStrideInBytes) : getVec3(normals, vref2, normalsStrideInBytes); pushVertex(v0, v1, v2, n0, n1, n2, flipFaceOrientation ? -1.0f : 1.0f); } else { PxVec3 fnormal = (v1 - v0).cross(v2 - v0); fnormal.normalize(); pushVertex(v0, v1, v2, fnormal); } numTotalTriangles++; } glScalef(1.0f, 1.0f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), vertexBuffer+1); glDrawArrays(GL_TRIANGLES, 0, int(nbTris * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); } glPopMatrix(); if (!enableBackFaceCulling) glEnable(GL_CULL_FACE); if(0) { const GLdouble aspect = GLdouble(glutGet(GLUT_WINDOW_WIDTH)) / GLdouble(glutGet(GLUT_WINDOW_HEIGHT)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip*1.005f), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0f, 0.0f, 0.0f, 1.0f); glPushMatrix(); glMultMatrixf(&idt.column0.x); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2*3*sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2*3*sizeof(float), vertexBuffer+1); glDrawArrays(GL_TRIANGLES, 0, int(nbTris * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, GLdouble(gNearClip), GLdouble(gFarClip)); glMatrixMode(GL_MODELVIEW); } } void renderMesh(physx::PxU32 nbVerts, const physx::PxVec3* verts, physx::PxU32 nbTris, const physx::PxU32* indices, const physx::PxVec3& color, const physx::PxVec3* normals, bool flipFaceOrientation) { renderMesh(nbVerts, reinterpret_cast<const PxU8*>(verts), sizeof(PxVec3), nbTris, indices, false, color, reinterpret_cast<const PxU8*>(normals), sizeof(PxVec3), flipFaceOrientation); } void renderMesh(physx::PxU32 nbVerts, const physx::PxVec4* verts, physx::PxU32 nbTris, const physx::PxU32* indices, const physx::PxVec3& color, const physx::PxVec4* normals, bool flipFaceOrientation) { renderMesh(nbVerts, reinterpret_cast<const PxU8*>(verts), sizeof(PxVec4), nbTris, indices, false, color, reinterpret_cast<const PxU8*>(normals), sizeof(PxVec4), flipFaceOrientation); } void renderMesh(physx::PxU32 nbVerts, const physx::PxVec4* verts, physx::PxU32 nbTris, const void* indices, bool hasSixteenBitIndices, const physx::PxVec3& color, const physx::PxVec4* normals, bool flipFaceOrientation, bool enableBackFaceCulling) { renderMesh(nbVerts, reinterpret_cast<const PxU8*>(verts), sizeof(PxVec4), nbTris, indices, hasSixteenBitIndices, color, reinterpret_cast<const PxU8*>(normals), sizeof(PxVec4), flipFaceOrientation, enableBackFaceCulling); } void DrawLine(const PxVec3& p0, const PxVec3& p1, const PxVec3& color) { glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); const PxVec3 Pts[] = { p0, p1 }; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec3), &Pts[0].x); glDrawArrays(GL_LINES, 0, 2); glDisableClientState(GL_VERTEX_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } const physx::PxVec3 icosahedronPoints[12] = { PxVec3(0, -0.525731, 0.850651), PxVec3(0.850651, 0, 0.525731), PxVec3(0.850651, 0, -0.525731), PxVec3(-0.850651, 0, -0.525731), PxVec3(-0.850651, 0, 0.525731), PxVec3(-0.525731, 0.850651, 0), PxVec3(0.525731, 0.850651, 0), PxVec3(0.525731, -0.850651, 0), PxVec3(-0.525731, -0.850651, 0), PxVec3(0, -0.525731, -0.850651), PxVec3(0, 0.525731, -0.850651), PxVec3(0, 0.525731, 0.850651) }; const PxU32 icosahedronIndices[3 * 20] = { 1 ,2 ,6 , 1 ,7 ,2 , 3 ,4 ,5 , 4 ,3 ,8 , 6 ,5 ,11 , 5 ,6 ,10 , 9 ,10 ,2 , 10 ,9 ,3 , 7 ,8 ,9 , 8 ,7 ,0 , 11 ,0 ,1 , 0 ,11 ,4 , 6 ,2 ,10 , 1 ,6 ,11 , 3 ,5 ,10 , 5 ,4 ,11 , 2 ,7 ,9 , 7 ,1 ,0 , 3 ,9 ,8 , 4 ,8 ,0 }; void DrawIcosahedraPoints(const PxArray<PxVec3>& pts, const PxVec3& color, float radius) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); const PxMat44 idt(PxIdentity); glPushMatrix(); glMultMatrixf(&idt.column0.x); glColor4f(color.x, color.y, color.z, 1.0f); PxU32 numTotalTriangles = 0; { prepareVertexBuffer(); for (PxU32 i = 0; i < pts.size(); ++i) { PxVec3 center = pts[i]; for (PxU32 j = 0; j < 20; ++j) { const PxVec3& v0 = icosahedronPoints[icosahedronIndices[3 * j + 0]] * radius + center; const PxVec3& v1 = icosahedronPoints[icosahedronIndices[3 * j + 1]] * radius + center; const PxVec3& v2 = icosahedronPoints[icosahedronIndices[3 * j + 2]] * radius + center; { PxVec3 fnormal = (v1 - v0).cross(v2 - v0); fnormal.normalize(); pushVertex(v0, v1, v2, fnormal); } numTotalTriangles++; } } glScalef(1.0f, 1.0f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); const PxVec3* vertexBuffer = getVertexBuffer(); glNormalPointer(GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer); glVertexPointer(3, GL_FLOAT, 2 * 3 * sizeof(float), vertexBuffer + 1); glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3)); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); } glPopMatrix(); } void DrawPoints(const PxArray<PxVec3>& pts, const PxVec3& color, float scale) { glPointSize(scale); glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec3), pts.begin()); glDrawArrays(GL_POINTS, 0, pts.size()); glDisableClientState(GL_VERTEX_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawPoints(const PxArray<PxVec4>& pts, const PxVec3& color, float scale) { glPointSize(scale); glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec4), pts.begin()); glDrawArrays(GL_POINTS, 0, pts.size()); glDisableClientState(GL_VERTEX_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawPoints(const physx::PxArray<physx::PxVec3>& pts, const physx::PxArray<physx::PxVec3>& colors, float scale) { glPointSize(scale); glDisable(GL_LIGHTING); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec3), pts.begin()); glColorPointer(3, GL_FLOAT, sizeof(PxVec3), colors.begin()); glDrawArrays(GL_POINTS, 0, pts.size()); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawPoints(const physx::PxArray<physx::PxVec4>& pts, const physx::PxArray<physx::PxVec3>& colors, float scale) { glPointSize(scale); glDisable(GL_LIGHTING); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(PxVec4), pts.begin()); glColorPointer(3, GL_FLOAT, sizeof(PxVec3), colors.begin()); glDrawArrays(GL_POINTS, 0, pts.size()); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } #if PX_SUPPORT_GPU_PHYSX namespace { void createVBO(GLuint* vbo, PxU32 size) { PX_ASSERT(vbo); // create buffer object glGenBuffers(1, vbo); glBindBuffer(GL_ARRAY_BUFFER, *vbo); // initialize buffer object glBufferData(GL_ARRAY_BUFFER, size, 0, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } void deleteVBO(GLuint* vbo) { glBindBuffer(1, *vbo); glDeleteBuffers(1, vbo); *vbo = 0; } #if USE_CUDA_INTEROP //Returns the pointer to the cuda buffer void* mapCudaGraphicsResource(CUgraphicsResource* vbo_resource, size_t& numBytes, CUstream stream = 0) { CUresult result0 = cuGraphicsMapResources(1, vbo_resource, stream); PX_UNUSED(result0); void* dptr; CUresult result1 = cuGraphicsResourceGetMappedPointer((CUdeviceptr*)&dptr, &numBytes, *vbo_resource); PX_UNUSED(result1); return dptr; } void unmapCudaGraphicsResource(CUgraphicsResource* vbo_resource, CUstream stream = 0) { CUresult result2 = cuGraphicsUnmapResources(1, vbo_resource, stream); PX_UNUSED(result2); } #endif } // namespace SharedGLBuffer::SharedGLBuffer() : vbo_res(NULL), devicePointer(NULL), vbo(0), size(0) { } void SharedGLBuffer::initialize(PxCudaContextManager* contextManager) { cudaContextManager = contextManager; } void SharedGLBuffer::allocate(PxU32 sizeInBytes) { release(); createVBO(&vbo, sizeInBytes); #if USE_CUDA_INTEROP physx::PxCudaInteropRegisterFlags flags = physx::PxCudaInteropRegisterFlags(); cudaContextManager->acquireContext(); CUresult result = cuGraphicsGLRegisterBuffer(reinterpret_cast<CUgraphicsResource*>(&vbo_res), vbo, flags); PX_UNUSED(result); cudaContextManager->releaseContext(); #endif size = sizeInBytes; } void SharedGLBuffer::release() { if (vbo) { deleteVBO(&vbo); vbo = 0; } #if USE_CUDA_INTEROP if (vbo_res) { cudaContextManager->acquireContext(); CUresult result = cuGraphicsUnregisterResource(reinterpret_cast<CUgraphicsResource>(vbo_res)); PX_UNUSED(result); cudaContextManager->releaseContext(); vbo_res = NULL; } #endif } SharedGLBuffer::~SharedGLBuffer() { //release(); } void* SharedGLBuffer::map() { if (devicePointer) return devicePointer; #if USE_CUDA_INTEROP size_t numBytes; cudaContextManager->acquireContext(); devicePointer = mapCudaGraphicsResource(reinterpret_cast<CUgraphicsResource*>(&vbo_res), numBytes, 0); cudaContextManager->releaseContext(); #else glBindBuffer(GL_ARRAY_BUFFER, vbo); devicePointer = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); glBindBuffer(GL_ARRAY_BUFFER, 0); #endif return devicePointer; } void SharedGLBuffer::unmap() { if (!devicePointer) return; #if USE_CUDA_INTEROP cudaContextManager->acquireContext(); unmapCudaGraphicsResource(reinterpret_cast<CUgraphicsResource*>(&vbo_res), 0); cudaContextManager->releaseContext(); #else glBindBuffer(GL_ARRAY_BUFFER, vbo); glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); #endif devicePointer = NULL; } #endif // PX_SUPPORT_GPU_PHYSX void DrawPoints(GLuint vbo, PxU32 numPoints, const PxVec3& color, float scale, PxU32 coordinatesPerPoint, PxU32 stride, size_t offset) { glPointSize(scale); glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(coordinatesPerPoint, GL_FLOAT, stride, (void*)offset /*offsetof(Vertex, pos)*/); glDrawArrays(GL_POINTS, 0, numPoints); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawLines(GLuint vbo, PxU32 numPoints, const PxVec3& color, float scale, PxU32 coordinatesPerPoint, PxU32 stride, size_t offset) { PX_ASSERT(numPoints % 2 == 0); glLineWidth(scale); glDisable(GL_LIGHTING); glColor4f(color.x, color.y, color.z, 1.0f); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(coordinatesPerPoint, GL_FLOAT, stride, (void*)offset /*offsetof(Vertex, pos)*/); glDrawArrays(GL_LINES, 0, numPoints); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); } void DrawMeshIndexed(GLuint vbo, GLuint elementbuffer, GLuint numTriangles, const physx::PxVec3& color, physx::PxU32 stride) { /*glPushMatrix(); glScalef(1.0f, 1.0f, 1.0f);*/ if(gWireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(color.x, color.y, color.z, 1.0f); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, stride, (void*)0); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, stride, (void*)(3 * sizeof(float))); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glDrawElements(GL_TRIANGLES, int(numTriangles * 3), GL_UNSIGNED_INT, (void*)0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); //glPopMatrix(); if (gWireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } void DrawMeshIndexedNoNormals(GLuint vbo, GLuint elementbuffer, GLuint numTriangles, const physx::PxVec3& color, physx::PxU32 stride) { /*glPushMatrix(); glScalef(1.0f, 1.0f, 1.0f);*/ glColor4f(color.x, color.y, color.z, 1.0f); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, stride, (void*)0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glDrawElements(GL_TRIANGLES, int(numTriangles * 3), GL_UNSIGNED_INT, (void*)0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); //glPopMatrix(); } void DrawFrame(const PxVec3& pt, float scale) { DrawLine(pt, pt + PxVec3(scale, 0.0f, 0.0f), PxVec3(1.0f, 0.0f, 0.0f)); DrawLine(pt, pt + PxVec3(0.0f, scale, 0.0f), PxVec3(0.0f, 1.0f, 0.0f)); DrawLine(pt, pt + PxVec3(0.0f, 0.0f, scale), PxVec3(0.0f, 0.0f, 1.0f)); } void DrawBounds(const physx::PxBounds3& box, const physx::PxVec3& color) { DrawLine(PxVec3(box.minimum.x, box.minimum.y, box.minimum.z), PxVec3(box.maximum.x, box.minimum.y, box.minimum.z), color); DrawLine(PxVec3(box.maximum.x, box.minimum.y, box.minimum.z), PxVec3(box.maximum.x, box.maximum.y, box.minimum.z), color); DrawLine(PxVec3(box.maximum.x, box.maximum.y, box.minimum.z), PxVec3(box.minimum.x, box.maximum.y, box.minimum.z), color); DrawLine(PxVec3(box.minimum.x, box.maximum.y, box.minimum.z), PxVec3(box.minimum.x, box.minimum.y, box.minimum.z), color); DrawLine(PxVec3(box.minimum.x, box.minimum.y, box.minimum.z), PxVec3(box.minimum.x, box.minimum.y, box.maximum.z), color); DrawLine(PxVec3(box.minimum.x, box.minimum.y, box.maximum.z), PxVec3(box.maximum.x, box.minimum.y, box.maximum.z), color); DrawLine(PxVec3(box.maximum.x, box.minimum.y, box.maximum.z), PxVec3(box.maximum.x, box.maximum.y, box.maximum.z), color); DrawLine(PxVec3(box.maximum.x, box.maximum.y, box.maximum.z), PxVec3(box.minimum.x, box.maximum.y, box.maximum.z), color); DrawLine(PxVec3(box.minimum.x, box.maximum.y, box.maximum.z), PxVec3(box.minimum.x, box.minimum.y, box.maximum.z), color); DrawLine(PxVec3(box.minimum.x, box.minimum.y, box.maximum.z), PxVec3(box.minimum.x, box.minimum.y, box.minimum.z), color); DrawLine(PxVec3(box.maximum.x, box.minimum.y, box.minimum.z), PxVec3(box.maximum.x, box.minimum.y, box.maximum.z), color); DrawLine(PxVec3(box.maximum.x, box.maximum.y, box.minimum.z), PxVec3(box.maximum.x, box.maximum.y, box.maximum.z), color); DrawLine(PxVec3(box.minimum.x, box.maximum.y, box.minimum.z), PxVec3(box.minimum.x, box.maximum.y, box.maximum.z), color); } void DrawBounds(const PxBounds3& box) { const PxVec3 color(1.0f, 1.0f, 0.0f); DrawBounds(box, color); } GLuint CreateTexture(PxU32 width, PxU32 height, const GLubyte* buffer, bool createMipmaps) { GLuint texId; glGenTextures(1, &texId); glBindTexture(GL_TEXTURE_2D, texId); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if(buffer) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); if(createMipmaps) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); } } glBindTexture(GL_TEXTURE_2D, 0); return texId; } void UpdateTexture(GLuint texId, physx::PxU32 width, physx::PxU32 height, const GLubyte* buffer, bool createMipmaps) { glBindTexture(GL_TEXTURE_2D, texId); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); if(createMipmaps) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); } glBindTexture( GL_TEXTURE_2D, 0); } void ReleaseTexture(GLuint texId) { glDeleteTextures(1, &texId); } void DrawRectangle(float x_start, float x_end, float y_start, float y_end, const PxVec3& color_top, const PxVec3& color_bottom, float alpha, PxU32 screen_width, PxU32 screen_height, bool draw_outline, bool texturing) { if(alpha!=1.0f) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); } else { glDisable(GL_BLEND); } glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); if(texturing) glEnable(GL_TEXTURE_2D); else glDisable(GL_TEXTURE_2D); { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, screen_width, 0, screen_height, -1, 1); } glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); const float x0 = x_start * float(screen_width); const float x1 = x_end * float(screen_width); const float y0 = y_start * float(screen_height); const float y1 = y_end * float(screen_height); const PxVec3 p0(x0, y0, 0.0f); const PxVec3 p1(x0, y1, 0.0f); const PxVec3 p2(x1, y1, 0.0f); const PxVec3 p3(x1, y0, 0.0f); // const float u = (texture_flags & SQT_FLIP_U) ? 1.0f : 0.0f; // const float v = (texture_flags & SQT_FLIP_V) ? 1.0f : 0.0f; const float u = 0.0f; const float v = 1.0f; const PxVec3 t0(u, v, 0.0f); const PxVec3 t1(u, 1.0f - v, 0.0f); const PxVec3 t2(1.0f - u, 1.0f - v, 0.0f); const PxVec3 t3(1.0f - u, v, 0.0f); glBegin(GL_TRIANGLES); glTexCoord2f(t0.x, t0.y); glColor4f(color_top.x, color_top.y, color_top.z, alpha); glVertex3f(p0.x, p0.y, p0.z); glTexCoord2f(t1.x, t1.y); glColor4f(color_bottom.x, color_bottom.y, color_bottom.z, alpha); glVertex3f(p1.x, p1.y, p1.z); glTexCoord2f(t2.x, t2.y); glColor4f(color_bottom.x, color_bottom.y, color_bottom.z, alpha); glVertex3f(p2.x, p2.y, p2.z); glTexCoord2f(t0.x, t0.y); glColor4f(color_top.x, color_top.y, color_top.z, alpha); glVertex3f(p0.x, p0.y, p0.z); glTexCoord2f(t2.x, t2.y); glColor4f(color_bottom.x, color_bottom.y, color_bottom.z, alpha); glVertex3f(p2.x, p2.y, p2.z); glTexCoord2f(t3.x, t3.y); glColor4f(color_top.x, color_top.y, color_top.z, alpha); glVertex3f(p3.x, p3.y, p3.z); glEnd(); if(draw_outline) { glDisable(GL_TEXTURE_2D); glColor4f(1.0f, 1.0f, 1.0f, alpha); glBegin(GL_LINES); glVertex3f(p0.x, p0.y, p0.z); glVertex3f(p1.x, p1.y, p1.z); glVertex3f(p1.x, p1.y, p1.z); glVertex3f(p2.x, p2.y, p2.z); glVertex3f(p2.x, p2.y, p2.z); glVertex3f(p3.x, p3.y, p3.z); glVertex3f(p3.x, p3.y, p3.z); glVertex3f(p0.x, p0.y, p0.z); glEnd(); } { glMatrixMode(GL_PROJECTION); glPopMatrix(); } glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glDisable(GL_BLEND); } void DisplayTexture(GLuint texId, PxU32 size, PxU32 margin) { const PxU32 screenWidth = gScreenWidth; const PxU32 screenHeight = gScreenHeight; glBindTexture(GL_TEXTURE_2D, texId); // glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); // glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // glDisable(GL_CULL_FACE); const PxVec3 color(1.0f, 1.0f, 1.0f); // const float Alpha = 0.999f; // const float Alpha = 0.5f; const float Alpha = 1.0f; PxU32 PixelSizeX = size; PxU32 PixelSizeY = size; if(!size) { PixelSizeX = gScreenWidth; PixelSizeY = gScreenHeight; margin = 0; } const float x0 = float(screenWidth-PixelSizeX-margin)/float(screenWidth); const float y0 = float(screenHeight-PixelSizeY-margin)/float(screenHeight); const float x1 = float(screenWidth-margin)/float(screenWidth); const float y1 = float(screenHeight-margin)/float(screenHeight); DrawRectangle(x0, x1, y0, y1, color, color, Alpha, screenWidth, screenHeight, false, true); glDisable(GL_TEXTURE_2D); } } //namespace Snippets
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetFontData.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // auto generated don't touch static const int OGL_FONT_TEXTURE_WIDTH=256; static const int OGL_FONT_TEXTURE_HEIGHT=128; static const int OGL_FONT_CHARS_PER_ROW=16; static const int OGL_FONT_CHARS_PER_COL=8; static const int OGL_FONT_CHAR_BASE=32; int GLFontGlyphWidth[OGL_FONT_CHARS_PER_ROW*OGL_FONT_CHARS_PER_COL] = { 6,7,8,11,10,10,11,7,10,8,10,10,8,9,8,10, 11,11,11,11,11,11,11,11,11,11,8,8,10,10,10,10, 11,10,10,10,11,10,10,10,10,10,9,11,10,10,10,10, 10,11,11,10,10,10,10,10,10,10,10,10,10,7,10,10, 8,10,10,10,9,9,10,9,10,8,8,11,8,10,10,10, 10,9,10,10,9,10,10,10,10,10,9,9,6,9,10,10, 10,10,9,10,10,10,10,10,9,9,9,9,9,8,10,10, 10,11,10,10,10,10,10,10,10,10,10,10,9,10,10,10 }; unsigned char OGLFontData[OGL_FONT_TEXTURE_WIDTH * OGL_FONT_TEXTURE_HEIGHT] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,117,68,0,101,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,85,68,0,0,0,0,0,0,0,0,117,32,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,101,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,101,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,68,117,0,117,85,0,0,0, 0,0,0,0,0,0,0,68,169,254,185,136,48,0,0,0,0,0,0,0,16,152,185,85,0,0,0,117,169,0,0,0, 0,0,0,0,0,0,0,48,221,254,152,16,0,0,0,0,0,0,0,0,0,0,0,0,237,237,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,221,205,68,0,0,0,0,0,0,0,0,152,237,136,16,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,101,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0, 0,0,0,0,0,0,221,101,0,152,152,0,0,0,0,0,0,0,0,0,0,0,0,0,152,101,0,221,32,0,0,0, 0,0,0,0,0,0,85,254,117,254,68,117,101,0,0,0,0,0,0,0,169,117,16,221,48,0,48,221,16,0,0,0, 0,0,0,0,0,0,0,221,169,48,254,117,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,101,0,0,0,0,0,0,0,0,0,0,0,16,205,205,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,101,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0, 0,0,0,0,0,0,185,68,0,117,117,0,0,0,0,0,0,0,0,0,0,0,0,0,221,32,32,221,0,0,0,0, 0,0,0,0,0,0,169,205,0,254,0,0,0,0,0,0,0,0,0,0,254,0,0,117,117,0,205,68,0,0,0,0, 0,0,0,0,0,0,0,254,117,16,254,117,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,237,117,0,0,0,0,0,0,0,0,0,0,0,0,0,16,237,117,0,0,0,0,0,0, 0,0,0,0,0,0,185,117,68,101,101,221,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0, 0,0,0,0,0,0,101,32,0,68,68,0,0,0,0,0,0,0,0,0,0,32,117,117,254,117,169,205,117,32,0,0, 0,0,0,0,0,0,169,221,16,254,0,0,0,0,0,0,0,0,0,0,221,32,0,152,101,136,136,0,0,0,0,0, 0,0,0,0,0,0,0,205,205,117,237,32,0,0,0,0,0,0,0,0,0,0,0,0,117,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,237,0,0,0,0,0,0, 0,0,0,0,0,0,32,85,68,32,101,48,0,0,0,0,0,0,0,0,0,0,0,0,101,32,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,117,185,185,117,221,152,117,0,0,0, 0,0,0,0,0,0,48,237,205,254,0,0,0,0,0,0,0,0,0,0,101,205,136,205,85,205,0,0,0,0,0,0, 0,0,0,0,0,0,16,169,254,221,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,101,205,136,152,0,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,169,85,0,237,16,0,0,0,0, 0,0,0,0,0,0,0,48,221,254,152,16,0,0,0,0,0,0,0,0,0,32,68,16,221,48,0,0,0,0,0,0, 0,0,0,0,0,48,221,169,221,185,0,0,136,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,237,101,32,254,48,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,68,254,68,117,205,68,32,0,0,0, 0,0,0,0,0,0,0,0,0,254,237,237,48,0,0,0,0,0,0,0,0,0,0,169,117,136,205,205,48,0,0,0, 0,0,0,0,0,185,185,0,101,254,68,0,185,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,32,0,0,32,0,0,0,0,0,0,0,0,0,0,68,68,68,205,117,68,68,32,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,48,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,169,205,237,185,237,205,185,85,0,0,0, 0,0,0,0,0,0,0,0,0,254,48,237,152,0,0,0,0,0,0,0,0,0,101,185,85,185,0,68,205,0,0,0, 0,0,0,0,0,254,117,0,0,185,237,16,221,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,237,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,185,237,205,185,185,101,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,117,0,205,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,0,185,185,0,0,0,0,0,0,0,0,32,221,16,117,117,0,0,254,0,0,0, 0,0,0,0,0,221,185,0,0,16,237,205,237,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,169,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,254,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,205,48,16,237,0,0,0,0,0,0, 0,0,0,0,0,0,136,68,0,254,48,254,101,0,0,0,0,0,0,0,0,185,85,0,85,185,0,68,205,0,0,0, 0,0,0,0,0,117,254,117,0,32,185,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,101,254,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,152,221,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,68,221,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,221,0,101,152,0,0,0,0,0,0, 0,0,0,0,0,0,152,221,254,254,237,117,0,0,0,0,0,0,0,0,117,152,0,0,0,136,205,205,48,0,0,0, 0,0,0,0,0,0,117,221,254,221,117,136,254,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,205,169,0,0,0,0,0,0,0,0,0,0,0,0,0,48,254,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,68,16,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,32,237,152,16,0,0,0,0,0,0,0,0,0,0,68,237,136,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,16,254,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,221,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,16,152,254,101,0,0,0,0,0,0,0,0,221,221,85,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,169,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,152,101,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,16,32,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,48,205,254,221,101,0,0,0,0,0,0,0,0,0,0,0,0,48,117,169,117,0,0,0,0,0, 0,0,0,0,0,0,117,205,254,254,169,32,0,0,0,0,0,0,0,0,0,0,185,254,254,237,136,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,136,185,0,0,0,0,0,0,0,0,0,0,0,136,185,185,185,185,48,0,0,0,0, 0,0,0,0,0,0,16,117,237,254,221,101,0,0,0,0,0,0,0,0,0,0,185,185,185,185,185,185,101,0,0,0, 0,0,0,0,0,0,85,221,254,254,169,16,0,0,0,0,0,0,0,0,0,0,101,221,254,205,85,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,169,221,254,254,221,117,16,0,0,0, 0,0,0,0,0,16,237,117,0,68,254,68,0,0,0,0,0,0,0,0,0,0,221,221,152,254,117,0,0,0,0,0, 0,0,0,0,0,0,117,48,0,32,205,221,0,0,0,0,0,0,0,0,0,0,101,32,0,68,254,117,0,0,0,0, 0,0,0,0,0,0,0,0,101,254,254,0,0,0,0,0,0,0,0,0,0,0,185,185,117,117,117,32,0,0,0,0, 0,0,0,0,0,0,185,152,32,0,48,68,0,0,0,0,0,0,0,0,0,0,117,117,117,117,136,254,117,0,0,0, 0,0,0,0,0,32,254,101,0,68,254,152,0,0,0,0,0,0,0,0,0,85,254,68,0,117,254,32,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,32,0,0,101,254,136,0,0,0, 0,0,0,0,0,117,221,0,0,0,152,169,0,0,0,0,0,0,0,0,0,0,32,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,85,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0, 0,0,0,0,0,0,0,32,221,152,254,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,101,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,205,0,0,0,0, 0,0,0,0,0,117,254,0,0,0,185,185,0,0,0,0,0,0,0,0,0,205,152,0,0,0,169,152,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,0,0,0,0,185,185,0,0,0, 0,0,0,0,0,185,152,0,0,0,101,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,85,254,48,0,0,0,0,0,0,0,0,0,0,0,0,16,221,117,0,0,0,0, 0,0,0,0,0,0,0,185,117,117,254,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,169,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,237,68,0,0,0,0, 0,0,0,0,0,101,254,117,0,32,254,101,0,0,0,0,0,0,0,0,0,254,117,0,0,0,117,205,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,32,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,254,85,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,185,205,0,0,0,0,0,0,0,0,0,0,16,68,85,185,169,0,0,0,0,0, 0,0,0,0,0,0,117,185,0,117,254,0,0,0,0,0,0,0,0,0,0,0,185,185,117,32,0,0,0,0,0,0, 0,0,0,0,0,237,85,169,254,237,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,152,152,0,0,0,0,0, 0,0,0,0,0,0,152,254,152,205,117,0,0,0,0,0,0,0,0,0,0,237,152,0,0,0,136,254,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,32,152,237,85,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,185,221,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,237,117,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,152,237,48,0,0,0,0,0,0,0,0,0,0,48,185,205,237,117,0,0,0,0,0, 0,0,0,0,0,48,237,16,0,117,254,0,0,0,0,0,0,0,0,0,0,0,101,117,185,254,101,0,0,0,0,0, 0,0,0,0,0,254,221,68,0,117,254,117,0,0,0,0,0,0,0,0,0,0,0,0,68,254,32,0,0,0,0,0, 0,0,0,0,0,0,101,237,254,237,85,0,0,0,0,0,0,0,0,0,0,152,237,48,0,16,221,254,0,0,0,0, 0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0, 0,0,0,0,0,0,0,32,152,237,117,16,0,0,0,0,0,0,0,0,0,117,117,117,117,117,117,117,101,0,0,0, 0,0,0,0,0,0,68,185,221,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,254,85,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,152,237,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,237,136,0,0,0,0, 0,0,0,0,0,205,85,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,48,0,0,0,0, 0,0,0,0,0,254,152,0,0,0,169,221,0,0,0,0,0,0,0,0,0,0,0,0,185,152,0,0,0,0,0,0, 0,0,0,0,0,85,237,48,32,205,254,101,0,0,0,0,0,0,0,0,0,16,185,254,185,221,117,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,32,152,237,117,16,0,0,0,0,0,0,0,0,0,0,0,117,117,117,117,117,117,117,101,0,0,0, 0,0,0,0,0,0,0,0,68,185,221,101,0,0,0,0,0,0,0,0,0,0,0,0,205,152,0,0,0,0,0,0, 0,0,0,0,0,205,136,0,0,0,101,254,16,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,117,237,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,237,0,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0, 0,0,0,0,0,221,117,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,68,254,32,0,0,0,0,0,0, 0,0,0,0,0,221,152,0,0,0,221,237,0,0,0,0,0,0,0,0,0,0,0,48,68,0,117,185,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,101,221,185,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,16,117,237,152,32,0,0,0,0,0,0,0,0,0,0,0,185,101,0,0,0,0,0,0, 0,0,0,0,0,136,205,0,0,0,136,205,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,254,117,0,0,0,0, 0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0,0,0,0,0,0,0,0,185,152,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,117,0,0,0,0, 0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0, 0,0,0,0,0,0,0,101,221,185,68,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,254,185,0,0,0, 0,0,0,0,0,0,16,117,237,152,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,32,254,68,0,16,237,101,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,221,221,68,68,68,68,16,0,0,0,0,0,0,0,0,0,32,0,0,16,237,152,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,16,0,0,152,254,32,0,0,0,0, 0,0,0,0,0,68,237,48,0,16,237,117,0,0,0,0,0,0,0,0,0,0,48,254,85,0,0,0,0,0,0,0, 0,0,0,0,0,169,221,16,0,16,205,152,0,0,0,0,0,0,0,0,0,32,0,0,0,101,221,16,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,101,221,185,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,117,237,152,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,117,68,0,0,0,0,0,0, 0,0,0,0,0,0,101,237,185,237,136,0,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,254,117,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,68,0,0,0,0,0,0,0,0,0,254,205,185,254,185,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,254,185,205,237,85,0,0,0,0,0, 0,0,0,0,0,0,117,254,185,237,152,0,0,0,0,0,0,0,0,0,0,0,117,254,16,0,0,0,0,0,0,0, 0,0,0,0,0,16,205,237,185,237,185,16,0,0,0,0,0,0,0,0,0,117,237,185,221,185,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,101,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,152,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,68,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,32,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,68,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,48,68,32,0,0,0,0,0,0,0,0,0,0,0,0,32,68,48,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,254,32,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,169,136,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,221,254,221,85,0,0,0,0,0,0,0,0,0,0,0,85,185,85,0,0,0,0,0,0, 0,0,0,0,0,0,185,185,185,185,169,68,0,0,0,0,0,0,0,0,0,0,0,101,185,254,254,221,136,0,0,0, 0,0,0,0,0,0,185,185,185,185,117,32,0,0,0,0,0,0,0,0,0,0,185,185,185,185,185,185,101,0,0,0, 0,0,0,0,0,0,185,185,185,185,185,185,136,0,0,0,0,0,0,0,0,0,0,101,185,254,254,221,136,0,0,0, 0,0,0,0,0,0,185,101,0,0,0,185,101,0,0,0,0,0,0,0,0,0,185,185,185,185,185,185,101,0,0,0, 0,0,0,0,0,0,48,185,185,185,185,48,0,0,0,0,0,0,0,0,0,0,185,101,0,0,16,169,101,0,0,0, 0,0,0,0,0,0,185,101,0,0,0,0,0,0,0,0,0,0,0,0,0,185,169,0,0,0,32,185,136,0,0,0, 0,0,0,0,0,0,185,117,0,0,0,101,136,0,0,0,0,0,0,0,0,0,16,169,254,254,169,16,0,0,0,0, 0,0,0,0,0,0,152,205,32,0,68,237,0,0,0,0,0,0,0,0,0,0,0,169,254,169,0,0,0,0,0,0, 0,0,0,0,0,0,254,152,68,85,205,254,32,0,0,0,0,0,0,0,0,0,152,237,101,0,0,68,117,0,0,0, 0,0,0,0,0,0,254,152,68,101,185,237,48,0,0,0,0,0,0,0,0,0,254,152,68,68,68,68,32,0,0,0, 0,0,0,0,0,0,254,152,68,68,68,68,48,0,0,0,0,0,0,0,0,0,152,237,101,0,0,48,101,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,68,68,152,254,68,68,32,0,0,0, 0,0,0,0,0,0,16,68,68,117,254,68,0,0,0,0,0,0,0,0,0,0,254,117,0,0,152,205,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,48,0,0,117,254,185,0,0,0, 0,0,0,0,0,0,254,254,32,0,0,117,185,0,0,0,0,0,0,0,0,16,205,152,16,16,152,205,16,0,0,0, 0,0,0,0,0,68,221,16,0,117,185,221,68,0,0,0,0,0,0,0,0,0,16,254,205,254,16,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,254,117,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,221,169,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,0,85,237,48,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,205,136,0,0,205,205,185,0,0,0, 0,0,0,0,0,0,254,254,152,0,0,117,185,0,0,0,0,0,0,0,0,117,237,16,0,0,16,237,117,0,0,0, 0,0,0,0,0,152,117,0,136,117,0,205,68,0,0,0,0,0,0,0,0,0,101,237,48,254,101,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,32,254,101,0,0,0,0,0,0,0,0,169,221,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,16,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,169,221,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,32,237,117,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,221,0,32,237,117,185,0,0,0, 0,0,0,0,0,0,254,221,254,32,0,117,185,0,0,0,0,0,0,0,0,185,169,0,0,0,0,169,185,0,0,0, 0,0,0,0,0,221,32,16,221,0,0,205,68,0,0,0,0,0,0,0,0,0,169,136,0,221,169,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,48,205,185,0,0,0,0,0,0,0,0,0,237,152,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,254,152,68,68,68,48,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,237,152,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,185,169,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,16,254,68,117,169,117,185,0,0,0, 0,0,0,0,0,0,254,101,237,152,0,117,185,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,254,0,68,185,0,32,254,68,0,0,0,0,0,0,0,0,32,254,48,0,117,254,32,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,205,16,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,254,221,185,185,185,136,0,0,0,0, 0,0,0,0,0,0,254,221,185,185,185,185,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,221,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,169,152,221,101,117,185,0,0,0, 0,0,0,0,0,0,254,68,117,254,68,117,185,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,254,0,68,205,0,152,221,68,0,0,0,0,0,0,0,0,117,221,0,0,32,254,117,0,0,0,0, 0,0,0,0,0,0,254,117,0,48,185,237,32,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,152,68,68,68,68,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,136,136,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,185,237,48,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,101,237,254,16,117,185,0,0,0, 0,0,0,0,0,0,254,68,16,237,185,117,185,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,205,68,0,237,152,152,185,152,32,0,0,0,0,0,0,0,205,254,254,254,254,254,205,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,237,152,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,185,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,16,237,205,16,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,16,237,169,0,117,185,0,0,0, 0,0,0,0,0,0,254,68,0,117,254,185,185,0,0,0,0,0,0,0,0,205,152,0,0,0,0,152,205,0,0,0, 0,0,0,0,0,117,169,0,48,117,16,101,117,32,0,0,0,0,0,0,32,254,48,0,0,0,117,254,32,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0,0,0,0,0,117,254,48,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,221,169,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,101,254,48,0,0,0,185,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,48,0,0,0,0,0,0,0,0,0,0,254,117,0,68,254,152,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,0,0,0,0,117,185,0,0,0, 0,0,0,0,0,0,254,68,0,16,237,254,185,0,0,0,0,0,0,0,0,136,221,0,0,0,0,221,136,0,0,0, 0,0,0,0,0,16,205,152,16,0,85,32,0,0,0,0,0,0,0,0,117,221,0,0,0,0,32,254,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0,0,0,0,0,0,0,205,237,68,0,0,0,32,0,0,0, 0,0,0,0,0,0,254,117,0,32,169,237,32,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,205,237,68,0,0,185,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,16,0,0,117,237,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,117,254,101,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,0,0,0,0,0,117,185,0,0,0, 0,0,0,0,0,0,254,68,0,0,117,254,185,0,0,0,0,0,0,0,0,32,237,117,0,0,117,237,32,0,0,0, 0,0,0,0,0,0,16,152,254,254,169,32,0,0,0,0,0,0,0,0,205,117,0,0,0,0,0,185,205,0,0,0, 0,0,0,0,0,0,254,254,254,254,237,117,0,0,0,0,0,0,0,0,0,0,16,152,254,221,185,221,169,0,0,0, 0,0,0,0,0,0,254,254,254,237,152,32,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,152,254,205,185,237,152,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,117,0,0,0, 0,0,0,0,0,0,254,205,205,237,85,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,237,48,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,254,0,0,0,0,0,117,185,0,0,0, 0,0,0,0,0,0,254,68,0,0,0,221,185,0,0,0,0,0,0,0,0,0,48,237,205,205,237,48,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,32,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,32,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,68,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,117,117,101,0,0,0, 0,0,0,0,0,117,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,117,117,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,185,185,185,185,169,101,0,0,0,0,0,0,0,0,0,0,16,169,254,254,169,16,0,0,0,0, 0,0,0,0,0,0,185,185,185,185,152,48,0,0,0,0,0,0,0,0,0,0,16,152,254,254,237,169,0,0,0,0, 0,0,0,0,185,185,185,185,185,185,185,185,101,0,0,0,0,0,0,0,0,0,185,101,0,0,0,136,101,0,0,0, 0,0,0,0,152,117,0,0,0,0,0,85,152,0,0,0,0,0,0,0,185,48,0,0,0,0,0,48,136,0,0,0, 0,0,0,0,85,185,68,0,0,0,48,185,32,0,0,0,0,0,0,0,117,185,16,0,0,0,0,136,117,0,0,0, 0,0,0,0,0,136,185,185,185,185,185,185,101,0,0,0,0,0,0,0,0,0,0,0,254,185,117,117,101,0,0,0, 0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,117,221,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,152,68,68,117,254,136,0,0,0,0,0,0,0,0,16,205,152,16,16,152,205,16,0,0,0, 0,0,0,0,0,0,254,152,68,85,169,237,32,0,0,0,0,0,0,0,0,0,152,169,16,0,48,117,0,0,0,0, 0,0,0,0,68,68,68,152,254,68,68,68,32,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,136,254,16,0,0,0,0,169,136,0,0,0,0,0,0,0,205,117,0,0,0,0,0,117,136,0,0,0, 0,0,0,0,0,221,205,0,0,0,205,169,0,0,0,0,0,0,0,0,32,254,117,0,0,0,68,254,32,0,0,0, 0,0,0,0,0,48,68,68,68,68,152,254,85,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,136,254,0,0,0,0,0,0,0,0,117,237,16,0,0,16,237,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,254,117,0,0,0,0,0,0,0,0,0,254,68,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,48,254,101,0,0,0,32,254,48,0,0,0,0,0,0,0,185,136,0,0,0,0,0,117,117,0,0,0, 0,0,0,0,0,68,254,117,0,117,237,16,0,0,0,0,0,0,0,0,0,136,254,32,0,0,205,136,0,0,0,0, 0,0,0,0,0,0,0,0,0,32,237,169,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,185,237,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,136,254,0,0,0,0,0,0,0,0,185,169,0,0,0,0,169,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,254,117,0,0,0,0,0,0,0,0,0,237,169,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,221,169,0,0,0,117,221,0,0,0,0,0,0,0,0,117,185,0,68,185,48,0,185,68,0,0,0, 0,0,0,0,0,0,169,237,48,237,85,0,0,0,0,0,0,0,0,0,0,16,237,185,0,117,237,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,185,237,16,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,68,221,152,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,16,221,169,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,117,0,0,152,237,16,0,0,0,0,0,0,0,0,0,101,254,205,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,136,254,16,0,0,205,136,0,0,0,0,0,0,0,0,117,205,0,117,254,117,0,205,48,0,0,0, 0,0,0,0,0,0,32,237,254,185,0,0,0,0,0,0,0,0,0,0,0,0,101,254,85,237,101,0,0,0,0,0, 0,0,0,0,0,0,0,0,117,254,85,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,152,101,32,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,185,117,136,221,205,16,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,221,185,237,185,32,0,0,0,0,0,0,0,0,0,0,0,68,221,254,185,48,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,48,254,101,0,32,254,48,0,0,0,0,0,0,0,0,68,254,0,185,205,152,0,254,0,0,0,0, 0,0,0,0,0,0,0,136,254,85,0,0,0,0,0,0,0,0,0,0,0,0,0,205,254,205,0,0,0,0,0,0, 0,0,0,0,0,0,0,32,237,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,32,221,0,0,152,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,185,117,117,48,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,152,68,237,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,237,237,68,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,0,205,185,0,117,205,0,0,0,0,0,0,0,0,0,32,254,32,221,117,205,32,221,0,0,0,0, 0,0,0,0,0,0,16,237,237,221,0,0,0,0,0,0,0,0,0,0,0,0,0,85,254,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,169,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,152,101,0,0,32,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,205,152,0,0,0,0,152,205,0,0,0, 0,0,0,0,0,0,254,117,0,85,254,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,237,169,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0, 0,0,0,0,0,0,117,254,32,221,117,0,0,0,0,0,0,0,0,0,0,254,85,237,48,254,68,185,0,0,0,0, 0,0,0,0,0,0,169,205,68,254,117,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,85,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,32,221,0,0,0,0,152,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,136,221,0,0,0,0,221,136,0,0,0, 0,0,0,0,0,0,254,117,0,0,185,237,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,237,117,0,0,0,205,117,0,0,0, 0,0,0,0,0,0,32,254,152,254,32,0,0,0,0,0,0,0,0,0,0,205,169,185,0,254,169,136,0,0,0,0, 0,0,0,0,0,68,254,48,0,152,237,32,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0, 0,0,0,0,0,16,237,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,152,117,0,0,0,0,68,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,32,237,117,0,0,117,237,32,0,0,0, 0,0,0,0,0,0,254,117,0,0,32,237,169,0,0,0,0,0,0,0,0,0,101,16,0,0,48,254,101,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,152,221,16,0,48,254,32,0,0,0, 0,0,0,0,0,0,0,205,254,205,0,0,0,0,0,0,0,0,0,0,0,185,254,117,0,185,237,117,0,0,0,0, 0,0,0,0,16,221,117,0,0,16,237,185,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0, 0,0,0,0,0,169,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,237,205,205,237,85,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,85,0,0,0,0,0,0,0,0,221,254,185,185,254,136,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,0,16,205,237,185,254,101,0,0,0,0, 0,0,0,0,0,0,0,117,254,117,0,0,0,0,0,0,0,0,0,0,0,117,254,85,0,136,254,68,0,0,0,0, 0,0,0,0,136,221,16,0,0,0,101,254,85,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,85,237,152,48,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,68,68,16,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,68,16,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,16,237,32,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,254,254,254,254,254,254,254,254,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,185,254,101,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,221,185,185,136,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,117,152,0,0,0,0,0,0,0,0,185,185,185,237,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,68,68,48,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,16,68,0,0,0,0,0,0,0,0,68,68,68,68,48,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,136,169,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,117,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,101,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,32,117,117,117,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,117,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,185,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,101,185,48,0,0,0,0,0,0,0,0,0,0,0,117,68,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,117,117,117,117,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,205,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,85,254,185,117,117,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,117,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,117,117,117,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,32,117,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,169,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0, 0,0,0,0,0,254,117,85,221,254,185,16,0,0,0,0,0,0,0,0,0,0,0,85,205,254,254,221,101,0,0,0, 0,0,0,0,0,0,117,237,254,136,185,185,0,0,0,0,0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,254,117,0,0,0,0,0,0,0,0,0,101,237,254,152,136,185,0,0,0,0, 0,0,0,0,0,0,254,117,85,221,254,136,0,0,0,0,0,0,0,0,0,0,254,254,254,254,68,0,0,0,0,0, 0,0,0,0,0,117,254,254,254,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,117,237,48,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,185,237,32,152,254,85,0,0,0, 0,0,0,0,0,0,254,117,85,221,254,136,0,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0, 0,0,0,0,0,254,185,185,85,101,237,185,0,0,0,0,0,0,0,0,0,0,68,254,152,16,0,48,48,0,0,0, 0,0,0,0,0,85,254,101,0,117,254,185,0,0,0,0,0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,85,254,68,0,117,254,185,0,0,0,0, 0,0,0,0,0,0,254,185,185,68,136,254,101,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,101,237,48,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,185,101,221,185,152,169,185,0,0,0, 0,0,0,0,0,0,254,185,185,68,136,254,101,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,254,169,0,0,0,117,254,32,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0, 0,0,0,0,0,185,169,0,0,0,185,185,0,0,0,0,0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,169,169,0,0,0,185,185,0,0,0,0, 0,0,0,0,0,0,254,185,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,85,254,101,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,117,0,185,185,0,117,185,0,0,0, 0,0,0,0,0,0,254,185,0,0,0,254,117,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0,0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,169,237,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0,0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,185,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,136,205,237,48,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,117,237,0,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0, 0,0,0,0,0,221,169,0,0,16,221,185,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,221,169,0,0,16,221,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,16,205,237,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0, 0,0,0,0,0,254,237,85,0,68,237,117,0,0,0,0,0,0,0,0,0,0,68,254,152,32,0,32,68,0,0,0, 0,0,0,0,0,117,254,117,85,185,205,185,0,0,0,0,0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,117,254,117,85,205,185,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,32,237,205,16,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0, 0,0,0,0,0,254,117,169,254,237,117,0,0,0,0,0,0,0,0,0,0,0,0,68,185,254,254,221,136,0,0,0, 0,0,0,0,0,16,152,254,221,48,185,185,0,0,0,0,0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0, 0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0,0,0,0,0,0,136,254,237,101,185,185,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,48,237,205,16,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,254,68,0,185,117,0,117,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,221,136,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,0,0,117,254,68,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,85,0,0,169,237,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,185,254,254,205,85,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,185,254,254,205,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,117,117,0,0,0,0, 0,0,0,0,0,0,0,0,117,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,85,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,221,117,117,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,117,117,221,136,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,101,237,254,136,0,0,0,0,0,0,0,0,0,0,85,221,254,185,101,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,85,221,254,169,0,0,0,0,0,0,0,0,0,16,152,237,254,254,205,48,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,185,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,205,205,0,0,0,0,136,205,0,0,0,0,0,0,0,237,85,0,0,68,32,0,32,237,0,0,0, 0,0,0,0,0,152,254,48,0,0,85,254,48,0,0,0,0,0,0,0,0,152,221,0,0,0,0,117,221,0,0,0, 0,0,0,0,0,185,254,254,254,254,254,254,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,185,185,85,117,254,117,0,0,0,0,0,0,0,0,85,254,117,0,68,237,254,0,0,0,0, 0,0,0,0,0,0,0,254,185,205,101,117,185,0,0,0,0,0,0,0,0,0,152,221,32,0,0,68,32,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,101,254,48,0,0,0,237,101,0,0,0,0,0,0,0,185,117,0,48,254,136,0,68,185,0,0,0, 0,0,0,0,0,16,205,221,16,16,237,117,0,0,0,0,0,0,0,0,0,68,254,101,0,0,0,221,117,0,0,0, 0,0,0,0,0,0,0,0,0,48,237,152,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,169,0,0,0,169,221,0,0,0,0,0,0,0,0,185,169,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,254,205,16,0,32,101,0,0,0,0,0,0,0,0,0,185,221,32,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,16,237,152,0,0,101,237,16,0,0,0,0,0,0,0,117,169,0,117,185,205,0,117,117,0,0,0, 0,0,0,0,0,0,48,237,169,185,185,0,0,0,0,0,0,0,0,0,0,0,221,185,0,0,85,237,16,0,0,0, 0,0,0,0,0,0,0,0,16,205,152,0,0,0,0,0,0,0,0,0,0,0,0,85,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0, 0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,68,237,254,205,117,16,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,152,237,16,0,185,152,0,0,0,0,0,0,0,0,85,205,0,185,48,254,16,169,85,0,0,0, 0,0,0,0,0,0,0,101,254,237,32,0,0,0,0,0,0,0,0,0,0,0,101,254,32,0,185,152,0,0,0,0, 0,0,0,0,0,0,0,16,205,185,0,0,0,0,0,0,0,0,0,0,0,0,254,254,117,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,254,0,0,0,0, 0,0,0,0,0,117,221,221,185,32,0,48,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0,0,0,0,0,254,117,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,117,205,254,237,32,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,32,254,117,32,254,32,0,0,0,0,0,0,0,0,48,254,16,237,0,205,85,205,48,0,0,0, 0,0,0,0,0,0,0,117,254,237,48,0,0,0,0,0,0,0,0,0,0,0,16,237,136,48,254,32,0,0,0,0, 0,0,0,0,0,0,0,185,205,16,0,0,0,0,0,0,0,0,0,0,0,0,0,85,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0, 0,0,0,0,0,237,16,0,117,237,136,205,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,169,185,0,0,0,0,0,0,0,0,221,169,0,0,0,169,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,254,117,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0, 0,0,0,0,0,0,0,185,221,136,185,0,0,0,0,0,0,0,0,0,0,254,117,169,0,136,136,254,0,0,0,0, 0,0,0,0,0,0,48,254,101,221,205,16,0,0,0,0,0,0,0,0,0,0,0,152,237,169,169,0,0,0,0,0, 0,0,0,0,0,0,152,205,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,32,117,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,237,68,0,117,254,85,0,0,0,0,0,0,0,0,117,254,117,85,185,185,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,117,48,0,0,117,254,68,0,0,0, 0,0,0,0,0,0,0,221,205,32,0,0,0,0,0,0,0,0,0,0,0,0,221,221,85,117,169,254,117,0,0,0, 0,0,0,0,0,0,0,101,254,237,101,0,0,0,0,0,0,0,0,0,0,185,237,101,0,85,254,185,0,0,0,0, 0,0,0,0,0,16,221,136,0,48,254,152,0,0,0,0,0,0,0,0,0,0,0,48,254,254,68,0,0,0,0,0, 0,0,0,0,0,152,237,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,136,169,254,221,101,0,0,0,0,0,0,0,0,0,0,136,254,221,101,117,254,0,0,0,0, 0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,169,221,254,254,205,85,0,0,0,0, 0,0,0,0,0,0,0,48,205,254,254,254,0,0,0,0,0,0,0,0,0,0,48,221,254,152,16,254,117,0,0,0, 0,0,0,0,0,0,0,0,237,237,0,0,0,0,0,0,0,0,0,0,0,136,254,32,0,32,254,136,0,0,0,0, 0,0,0,0,0,152,205,0,0,0,117,254,101,0,0,0,0,0,0,0,0,0,0,0,205,221,0,0,0,0,0,0, 0,0,0,0,0,254,254,254,254,254,254,254,0,0,0,0,0,0,0,0,0,0,0,0,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,237,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,237,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,237,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,152,221,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,254,185,185,0,0,0,0, 0,0,0,0,0,0,0,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,254,101,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,205,48,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,68,0,0,0,0, 0,0,0,0,0,0,0,0,68,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,16,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,185,117,0,185,117,0,0,0,0,0,0,0,0,0,0,0,0,68,117,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,85,185,48,0,0,0,0,0,0,0,0,0,0,0,0,48,117,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,169,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,48,136,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,48,117,85,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,101,185,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,85,117,48,0,0,0,0,0,0,0,0,0,0,0,0,136,169,0,0,0,0,0,0,0, 0,0,0,0,0,0,48,32,0,48,32,0,0,0,0,0,0,0,0,0,0,0,0,117,0,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,101,185,254,254,221,136,0,0,0,0,0,0,0,0,0,0,185,48,0,185,48,0,0,0,0, 0,0,0,0,0,0,0,16,237,101,0,0,0,0,0,0,0,0,0,0,0,0,32,237,117,237,85,0,0,0,0,0, 0,0,0,0,0,0,101,136,0,101,136,0,0,0,0,0,0,0,0,0,0,0,0,16,205,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,16,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,32,237,117,237,85,0,0,0,0,0,0,0,0,0,0,0,48,185,0,48,185,0,0,0,0,0, 0,0,0,0,0,0,0,0,152,185,0,0,0,0,0,0,0,0,0,0,0,0,0,136,101,0,136,101,0,0,0,0, 0,0,0,0,0,0,0,85,237,117,237,32,0,0,0,0,0,0,0,0,0,0,0,16,205,117,0,0,0,0,0,0, 0,0,0,0,0,0,0,85,185,85,0,0,0,0,0,0,0,0,0,0,0,0,0,117,254,117,0,0,0,0,0,0, 0,0,0,0,0,0,152,237,101,0,0,68,117,0,0,0,0,0,0,0,0,0,0,117,32,0,117,32,0,0,0,0, 0,0,0,0,0,0,0,85,101,0,0,0,0,0,0,0,0,0,0,0,0,0,85,85,0,48,117,0,0,0,0,0, 0,0,0,0,0,0,68,101,0,68,101,0,0,0,0,0,0,0,0,0,0,0,0,0,32,117,16,0,0,0,0,0, 0,0,0,0,0,0,0,16,117,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,85,85,0,48,117,0,0,0,0,0,0,0,0,0,0,0,32,117,0,32,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,117,48,0,0,0,0,0,0,0,0,0,0,0,0,101,68,0,101,68,0,0,0,0, 0,0,0,0,0,0,0,117,48,0,85,85,0,0,0,0,0,0,0,0,0,0,0,0,32,117,16,0,0,0,0,0, 0,0,0,0,0,0,0,169,254,169,0,0,0,0,0,0,0,0,0,0,0,0,0,169,254,169,0,0,0,0,0,0, 0,0,0,0,0,68,254,85,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,16,254,205,254,16,0,0,0,0,0,0,0,0,0,0,0,16,254,205,254,16,0,0,0,0,0, 0,0,0,0,0,169,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0,0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0, 0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0,0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0, 0,0,0,0,0,32,169,237,254,237,117,0,0,0,0,0,0,0,0,0,0,0,0,85,205,254,254,221,101,0,0,0, 0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0,0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,68,205,254,237,152,16,0,0,0,0,0,0,0,0,0,0,254,254,254,254,117,0,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,117,0,0,0,0,0,0,0,0,0,0,0,254,254,254,254,117,0,0,0,0,0, 0,0,0,0,0,0,101,237,48,254,101,0,0,0,0,0,0,0,0,0,0,0,101,237,48,254,101,0,0,0,0,0, 0,0,0,0,0,221,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0,0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0, 0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0,0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0, 0,0,0,0,0,48,101,16,0,136,254,32,0,0,0,0,0,0,0,0,0,0,68,254,152,16,0,48,48,0,0,0, 0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0,0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0, 0,0,0,0,0,48,254,117,0,48,237,152,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,169,136,0,221,169,0,0,0,0,0,0,0,0,0,0,0,169,136,0,221,169,0,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,0,0,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,185,205,0,0,0,0,0,0,0,0, 0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0,0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0, 0,0,0,0,0,169,152,0,0,0,136,221,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,32,254,48,0,117,254,32,0,0,0,0,0,0,0,0,0,32,254,48,0,117,254,32,0,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0,0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0, 0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0,0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0, 0,0,0,0,0,0,68,152,185,205,254,68,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0,0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0, 0,0,0,0,0,254,221,185,185,185,221,254,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,117,221,0,0,32,254,117,0,0,0,0,0,0,0,0,0,117,221,0,0,32,254,117,0,0,0,0, 0,0,0,0,0,205,185,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0,0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0, 0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0,0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0, 0,0,0,0,0,117,237,85,0,68,254,68,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0,0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0, 0,0,0,0,0,254,152,68,68,68,68,68,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,205,254,254,254,254,254,205,0,0,0,0,0,0,0,0,0,205,254,254,254,254,254,205,0,0,0,0, 0,0,0,0,0,117,254,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0, 0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0,0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0, 0,0,0,0,0,237,117,0,0,68,254,68,0,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0, 0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,205,205,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,32,254,48,0,0,0,117,254,32,0,0,0,0,0,0,0,32,254,48,0,0,0,117,254,32,0,0,0, 0,0,0,0,0,16,205,237,68,0,0,0,32,0,0,0,0,0,0,0,0,0,221,221,85,117,169,254,117,0,0,0, 0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0,0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0, 0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0,0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0, 0,0,0,0,0,221,185,16,32,169,254,85,0,0,0,0,0,0,0,0,0,0,85,254,152,32,0,32,68,0,0,0, 0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0,0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0, 0,0,0,0,0,85,254,152,32,0,32,101,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,117,221,0,0,0,0,32,254,117,0,0,0,0,0,0,0,117,221,0,0,0,0,32,254,117,0,0,0, 0,0,0,0,0,0,32,185,254,205,185,221,169,0,0,0,0,0,0,0,0,0,48,221,254,152,16,254,117,0,0,0, 0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0,0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0, 0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0,0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0, 0,0,0,0,0,48,221,254,205,85,169,254,117,0,0,0,0,0,0,0,0,0,0,85,205,254,254,221,117,0,0,0, 0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0,0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0, 0,0,0,0,0,0,85,185,254,254,237,169,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0, 0,0,0,0,205,117,0,0,0,0,0,185,205,0,0,0,0,0,0,0,205,117,0,0,0,0,0,185,205,0,0,0, 0,0,0,0,0,0,0,0,68,185,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,205,16,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,32,136,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,48,237,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,143,251,198,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,85,185,117,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,169,152,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,0,68,254,0,0,0,0,0, 0,0,0,0,0,0,0,254,68,0,254,68,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,16,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,117,85,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,101,185,32,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,85,117,48,0,0,0,0,0,0,0,0,0,0,0,0,101,185,32,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,68,0,16,68,0,0,0,0,0, 0,0,0,0,0,0,0,68,16,0,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,185,185,185,185,185,185,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,32,185,185,185,185,101,0,0,0,0,0,0,0,0,0,32,237,117,237,85,0,0,0,0,0, 0,0,0,0,0,0,101,136,0,101,136,0,0,0,0,0,0,0,0,0,0,0,0,0,152,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,85,237,117,237,32,0,0,0,0,0,0,0,0,0,0,0,0,152,185,0,0,0,0,0,0, 0,0,0,0,0,0,0,185,48,0,185,48,0,0,0,0,0,0,0,0,0,0,16,169,254,254,169,16,0,0,0,0, 0,0,0,0,0,0,185,101,0,0,0,136,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,101,221,254,237,0,0,0,0,0,0,0,0,0,0,32,169,254,254,169,136,185,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,237,254,117,0,0,0, 0,0,0,0,0,0,254,152,68,68,68,68,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,254,68,68,32,0,0,0,0,0,0,0,0,0,85,85,0,48,117,0,0,0,0,0, 0,0,0,0,0,0,68,101,0,68,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,48,0,0,0,0,0, 0,0,0,0,0,0,0,117,48,0,85,85,0,0,0,0,0,0,0,0,0,0,0,0,0,117,48,0,0,0,0,0, 0,0,0,0,0,0,0,117,32,0,117,32,0,0,0,0,0,0,0,0,0,16,205,152,16,16,152,205,16,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,48,254,85,0,48,0,0,0,0,0,0,0,0,0,16,205,152,16,16,152,254,48,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,237,32,0,32,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,205,237,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,117,237,16,0,0,16,237,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,117,237,16,0,0,185,254,117,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,221,136,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,68,254,254,237,136,237,254,136,0,0,0, 0,0,0,0,0,0,48,254,152,254,0,0,0,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,152,221,0,0,0,0,117,221,0,0,0,0,0,0,0,0,185,169,0,0,0,0,169,185,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,0,85,205,254,254,169,221,48,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,185,169,0,0,85,221,205,185,0,0,0, 0,0,0,0,0,85,16,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,0,48,254,68,0,0,0,0,0,0, 0,0,0,0,0,0,254,152,68,68,68,48,0,0,0,0,0,0,0,0,0,16,32,0,169,254,117,48,254,48,0,0, 0,0,0,0,0,0,136,205,117,254,68,68,16,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,68,254,101,0,0,0,221,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,85,254,117,0,48,254,205,0,0,0,0, 0,0,0,0,0,0,48,152,254,68,32,0,0,0,0,0,0,0,0,0,0,254,117,0,16,221,85,117,254,0,0,0, 0,0,0,0,0,101,205,16,0,0,101,221,48,0,0,0,0,0,0,0,0,0,48,152,254,85,16,0,0,0,0,0, 0,0,0,0,0,0,254,221,185,185,185,136,0,0,0,0,0,0,0,0,0,0,0,48,152,254,68,68,254,117,0,0, 0,0,0,0,0,0,221,101,117,254,185,185,48,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,221,185,0,0,85,237,16,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,205,205,0,0,169,185,254,85,0,0,0, 0,0,0,0,0,0,136,221,254,185,101,0,0,0,0,0,0,0,0,0,0,254,117,0,136,185,0,117,254,0,0,0, 0,0,0,0,0,0,101,205,16,101,237,48,0,0,0,0,0,0,0,0,0,0,136,237,237,185,48,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,48,205,221,221,254,254,254,254,117,0,0, 0,0,0,0,0,85,254,16,117,254,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,101,254,32,0,185,152,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,117,254,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,254,117,0,117,185,0,254,117,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,254,117,48,254,32,0,117,254,0,0,0, 0,0,0,0,0,0,0,101,221,237,48,0,0,0,0,0,0,0,0,0,0,0,0,205,169,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,117,254,0,0,0,0,0,0, 0,0,0,0,0,152,237,185,221,254,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0,0,0,0,0,0,254,117,0,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,0,254,117,0,0,0, 0,0,0,0,0,0,16,237,136,48,254,32,0,0,0,0,0,0,0,0,0,205,152,0,0,0,0,152,205,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,185,117,0,0,0,0,0,0,0,0,254,117,68,237,16,0,254,117,0,0,0, 0,0,0,0,0,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,0,205,169,185,117,0,0,152,205,0,0,0, 0,0,0,0,0,0,0,48,221,205,16,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,117,254,16,0,0,0,0,0, 0,0,0,0,0,237,117,68,152,254,0,0,0,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0,0,0,0,0,0,205,185,0,0,0,68,254,85,0,0,0, 0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0,0,0,0,0,0,0,254,117,0,0,68,254,117,0,0,0, 0,0,0,0,0,0,0,152,237,169,169,0,0,0,0,0,0,0,0,0,0,136,221,0,0,0,0,221,136,0,0,0, 0,0,0,0,0,0,237,117,0,0,0,205,117,0,0,0,0,0,0,0,0,205,205,237,48,0,85,254,85,0,0,0, 0,0,0,0,0,0,0,152,169,0,0,0,0,0,0,0,0,0,0,0,0,136,254,221,16,0,0,221,136,0,0,0, 0,0,0,0,0,0,48,221,48,101,205,16,0,0,0,0,0,0,0,0,0,0,68,254,85,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0,0,0,0,0,0,221,221,68,205,254,152,0,48,68,0,0, 0,0,0,0,101,237,0,0,117,254,0,0,0,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0,0,0,0,0,0,85,254,117,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,221,221,85,117,169,254,117,0,0,0,0,0,0,0,0,0,221,221,85,117,169,254,117,0,0,0, 0,0,0,0,0,0,0,48,254,254,68,0,0,0,0,0,0,0,0,0,0,32,237,117,0,0,117,237,32,0,0,0, 0,0,0,0,0,0,152,221,16,0,48,254,32,0,0,0,0,0,0,0,0,101,254,169,0,32,205,205,0,0,0,0, 0,0,0,0,0,0,117,237,85,68,68,68,0,0,0,0,0,0,0,0,0,48,254,152,0,0,117,237,32,0,0,0, 0,0,0,0,0,48,221,48,0,0,101,205,16,0,0,0,0,0,0,0,0,0,117,254,32,0,0,0,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,185,0,0,0,0,0,0,0,0,48,221,237,136,136,237,254,205,85,0,0, 0,0,0,0,169,152,0,0,117,254,254,254,185,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0,0,0,0,0,0,0,85,205,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,48,221,254,152,16,254,117,0,0,0,0,0,0,0,0,0,48,221,254,152,16,254,117,0,0,0, 0,0,0,0,0,0,0,0,205,221,0,0,0,0,0,0,0,0,0,0,0,0,48,237,205,205,237,48,0,0,0,0, 0,0,0,0,0,0,16,205,237,185,254,101,0,0,0,0,0,0,0,0,0,152,185,221,254,237,152,16,0,0,0,0, 0,0,0,0,0,0,254,254,254,254,254,254,0,0,0,0,0,0,0,0,0,136,205,237,221,205,237,48,0,0,0,0, 0,0,0,0,0,117,48,0,0,0,0,101,85,0,0,0,0,0,0,0,0,0,136,237,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,237,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,48,68,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,16,0,68,68,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,185,185,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,152,221,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,117,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,117,254,205,48,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,32,0,0,0,0,0,0,0,0 };
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetFontRenderer.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SNIPPET_FONT_RENDERER_H #define SNIPPET_FONT_RENDERER_H class GLFontRenderer { private: static bool m_isInit; static unsigned int m_textureObject; static int m_screenWidth; static int m_screenHeight; static float m_color[4]; public: static bool init(); static void print(float x, float y, float fontSize, const char* pString, bool forceMonoSpace=false, int monoSpaceWidth=11, bool doOrthoProj=true); static void print_(float x, float y, float fontSize, const char* pString, bool forceMonoSpace=false, int monoSpaceWidth=11, bool doOrthoProj=true); static void setScreenResolution(int screenWidth, int screenHeight); static void setColor(float r, float g, float b, float a); }; #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrender/SnippetFontRenderer.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "SnippetFontData.h" #include "SnippetFontRenderer.h" #include "SnippetRender.h" bool GLFontRenderer::m_isInit=false; unsigned int GLFontRenderer::m_textureObject=0; int GLFontRenderer::m_screenWidth=640; int GLFontRenderer::m_screenHeight=480; float GLFontRenderer::m_color[4]={1.0f, 1.0f, 1.0f, 1.0f}; namespace { struct RGBAPixel { unsigned char R,G,B,A; }; #define PIXEL_OPAQUE 0xff } bool GLFontRenderer::init() { glGenTextures(1, (GLuint*)&m_textureObject); if(!m_textureObject) return false; glBindTexture(GL_TEXTURE_2D, m_textureObject); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // expand to rgba RGBAPixel* P = new RGBAPixel[OGL_FONT_TEXTURE_WIDTH*OGL_FONT_TEXTURE_HEIGHT]; for(int i=0;i<OGL_FONT_TEXTURE_WIDTH*OGL_FONT_TEXTURE_HEIGHT;i++) { if(1) { P[i].R = PIXEL_OPAQUE; P[i].G = PIXEL_OPAQUE; P[i].B = PIXEL_OPAQUE; P[i].A = OGLFontData[i]; } else { P[i].R = OGLFontData[i]; P[i].G = OGLFontData[i]; P[i].B = OGLFontData[i]; P[i].A = PIXEL_OPAQUE; } } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, OGL_FONT_TEXTURE_WIDTH, OGL_FONT_TEXTURE_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, P); delete [] P; m_isInit = true; return true; } void GLFontRenderer::print(float x, float y, float fontSize, const char* pString, bool forceMonoSpace, int monoSpaceWidth, bool doOrthoProj) { if(1) { const float Saved0 = m_color[0]; const float Saved1 = m_color[1]; const float Saved2 = m_color[2]; m_color[0] = 0.0f; m_color[1] = 0.0f; m_color[2] = 0.0f; // const float Offset = fontSize * 0.05f; // const float Offset = fontSize * 0.075f; const float Offset = fontSize * 0.1f; print_(x+Offset, y-Offset, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); //print_(x-Offset, y-Offset, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); //print_(x+Offset, y+Offset, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); //print_(x-Offset, y+Offset, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); m_color[0] = Saved0; m_color[1] = Saved1; m_color[2] = Saved2; } print_(x, y, fontSize, pString, forceMonoSpace, monoSpaceWidth, doOrthoProj); } void GLFontRenderer::print_(float x, float y, float fontSize, const char* pString, bool forceMonoSpace, int monoSpaceWidth, bool doOrthoProj) { x = x*m_screenWidth; y = y*m_screenHeight; fontSize = fontSize*m_screenHeight; if(!m_isInit) m_isInit = init(); unsigned int num = (unsigned int)(strlen(pString)); if(m_isInit && num > 0) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_textureObject); if(doOrthoProj) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, m_screenWidth, 0, m_screenHeight, -1, 1); } glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glEnable(GL_BLEND); glDisable(GL_CULL_FACE); glColor4f(m_color[0], m_color[1], m_color[2], m_color[3]); const float glyphHeightUV = ((float)OGL_FONT_CHARS_PER_COL)/OGL_FONT_TEXTURE_HEIGHT*2 - 1.0f/128.0f; //const float glyphHeightUV = ((float)OGL_FONT_CHARS_PER_COL)/OGL_FONT_TEXTURE_HEIGHT*2; float translate = 0.0f; float* pVertList = new float[num*3*6]; float* pTextureCoordList = new float[num*2*6]; int vertIndex = 0; int textureCoordIndex = 0; float translateDown = 0.0f; unsigned int count = 0; for(unsigned int i=0;i<num; i++) { const float glyphWidthUV = ((float)OGL_FONT_CHARS_PER_ROW)/OGL_FONT_TEXTURE_WIDTH; if (pString[i] == '\n') { translateDown-=0.005f*m_screenHeight+fontSize; translate = 0.0f; continue; } int c = pString[i]-OGL_FONT_CHAR_BASE; if (c < OGL_FONT_CHARS_PER_ROW*OGL_FONT_CHARS_PER_COL) { count++; float glyphWidth = (float)GLFontGlyphWidth[c]+1; if(forceMonoSpace) glyphWidth = (float)monoSpaceWidth; glyphWidth = glyphWidth*(fontSize/(((float)OGL_FONT_TEXTURE_WIDTH)/OGL_FONT_CHARS_PER_ROW))-0.01f; const float cxUV = float((c)%OGL_FONT_CHARS_PER_ROW)/OGL_FONT_CHARS_PER_ROW+0.008f; const float cyUV = float((c)/OGL_FONT_CHARS_PER_ROW)/OGL_FONT_CHARS_PER_COL+0.008f; pTextureCoordList[textureCoordIndex++] = cxUV; pTextureCoordList[textureCoordIndex++] = cyUV+glyphHeightUV; pVertList[vertIndex++] = x+0+translate; pVertList[vertIndex++] = y+0+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV+glyphWidthUV; pTextureCoordList[textureCoordIndex++] = cyUV; pVertList[vertIndex++] = x+fontSize+translate; pVertList[vertIndex++] = y+fontSize+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV; pTextureCoordList[textureCoordIndex++] = cyUV; pVertList[vertIndex++] = x+0+translate; pVertList[vertIndex++] = y+fontSize+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV; pTextureCoordList[textureCoordIndex++] = cyUV+glyphHeightUV; pVertList[vertIndex++] = x+0+translate; pVertList[vertIndex++] = y+0+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV+glyphWidthUV; pTextureCoordList[textureCoordIndex++] = cyUV+glyphHeightUV; pVertList[vertIndex++] = x+fontSize+translate; pVertList[vertIndex++] = y+0+translateDown; pVertList[vertIndex++] = 0; pTextureCoordList[textureCoordIndex++] = cxUV+glyphWidthUV; pTextureCoordList[textureCoordIndex++] = cyUV; pVertList[vertIndex++] = x+fontSize+translate; pVertList[vertIndex++] = y+fontSize+translateDown; pVertList[vertIndex++] = 0; translate+=glyphWidth; } } glEnableClientState(GL_VERTEX_ARRAY); // glVertexPointer(3, GL_FLOAT, num*6, pVertList); glVertexPointer(3, GL_FLOAT, 3*4, pVertList); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // glTexCoordPointer(2, GL_FLOAT, num*6, pTextureCoordList); glTexCoordPointer(2, GL_FLOAT, 2*4, pTextureCoordList); glDrawArrays(GL_TRIANGLES, 0, count*6); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); delete[] pVertList; delete[] pTextureCoordList; // glMatrixMode(GL_MODELVIEW); // glPopMatrix(); if(doOrthoProj) { glMatrixMode(GL_PROJECTION); glPopMatrix(); } glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); glEnable(GL_CULL_FACE); } } void GLFontRenderer::setScreenResolution(int screenWidth, int screenHeight) { m_screenWidth = screenWidth; m_screenHeight = screenHeight; } void GLFontRenderer::setColor(float r, float g, float b, float a) { m_color[0] = r; m_color[1] = g; m_color[2] = b; m_color[3] = a; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetloadcollection/SnippetLoadCollection.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates loading xml or binary serialized collections and instantiating the objects in a scene. // // It only compiles and runs on authoring platforms (windows, osx and linux). // The snippet supports connecting to PVD in order to display the scene. // // It is a simple command-line tool supporting the following options:: // SnippetLoadCollection [--pvdhost=<ip address> ] [--pvdport=<ip port> ] [--pvdtimeout=<time ms> ] [--generateExampleFiles] <filename>... // // --pvdhost=<ip address> Defines ip address of PVD, default is 127.0.0.1 // --pvdport=<ip port> Defines ip port of PVD, default is 5425 // --pvdtimeout=<time ms> Defines time out of PVD, default is 10 // --generateExampleFiles Generates a set of example files // <filename>... Input files containing serialized collections (either xml or binary) // // Multiple collection files can be specified. The snippet is currently restricted to load a list of collections which obey // the following rule: The first collection needs to be complete. All following collections - if any - may only maintain // dependencies to objects in the first collection. // // The set of example files that can be generated consists of // collection.xml|collection.bin: Can be used individually. // collectionA.xml|collectionA.bin: Can also be used individually but only contain materials and shapes without actors. // collectionB.xml|collectionB.bin: Need to be used together with collectionA files. The actors contained in collectionB // maintain references to objects in the collectionA. // // **************************************************************************** #include "PxPhysicsAPI.h" #include <iostream> #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #define MAX_INPUT_FILES 16 using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxSerializationRegistry* gSerializationRegistry = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxPvd* gPvd = NULL; static PxU8* gMemBlocks[MAX_INPUT_FILES]; static PxU32 gNbMemBlocks = 0; struct CmdLineParameters { const char* pvdhost; PxU32 pvdport; PxU32 pvdtimeout; const char* inputFiles[MAX_INPUT_FILES]; PxU32 nbFiles; bool generateExampleFiles; CmdLineParameters() : pvdhost(PVD_HOST) , pvdport(5425) , pvdtimeout(10) , nbFiles(0) , generateExampleFiles(false) {} } gParameters; static bool match(const char* opt, const char* ref) { std::string s1(opt); std::string s2(ref); return !s1.compare(0, s2.length(), s2); } static void printHelpMsg() { printf("SnippetLoadCollection usage:\n" "SnippetLoadCollection " "[--pvdhost=<ip address> ] " "[--pvdport=<ip port> ]" "[--pvdtimeout=<time ms> ] " "[--generateExampleFiles]" "<filename>...\n\n" "Load binary or xml serialized collections and instatiate the objects in a PhysX scene.\n"); printf("--pvdhost=<ip address> \n"); printf(" Defines ip address of PVD, default is 127.0.0.1 \n"); printf("--pvdport=<ip port> \n"); printf(" Defines ip port of PVD, default is 5425\n"); printf("--pvdtimeout=<time ms> \n"); printf(" Defines timeout of PVD, default is 10\n"); printf("--generateExampleFiles\n"); printf(" Generates a set of example files\n"); printf("<filename>...\n"); printf(" Input files (xml or binary), if a collection contains shared objects, it needs to be provided with the first file. \n\n"); } static bool parseCommandLine(CmdLineParameters& result, int argc, const char *const*argv) { if( argc <= 1 ) { printHelpMsg(); return false; } for(int i = 1; i < argc; ++i) { if(argv[i][0] != '-' || argv[i][1] != '-') { if (result.nbFiles < MAX_INPUT_FILES) { result.inputFiles[result.nbFiles++] = argv[i]; } else printf( "[WARNING] more input files are specified than supported (maximum %d). Ignoring the file %s\n", MAX_INPUT_FILES, argv[i] ); } else if(match(argv[i], "--pvdhost=")) { const char* hostStr = argv[i] + strlen("--pvdhost="); if(hostStr) result.pvdhost = hostStr; } else if(match(argv[i], "--pvdport=")) { const char* portStr = argv[i] + strlen("--pvdport="); if (portStr) result.pvdport = PxU32(atoi(portStr)); } else if(match(argv[i], "--pvdtimeout=")) { const char* timeoutStr = argv[i] + strlen("--pvdtimeout="); if (timeoutStr) result.pvdtimeout = PxU32(atoi(timeoutStr)); } else if(match(argv[i], "--generateExampleFiles")) { result.generateExampleFiles = true; } else { printf( "[ERROR] Unknown command line parameter \"%s\"\n", argv[i] ); printHelpMsg(); return false; } } if(result.nbFiles == 0 && !result.generateExampleFiles) { printf( "[ERROR] parameter missing.\n" ); printHelpMsg(); return false; } return true; } static bool checkFile(bool& isBinary, const char* filename) { PxDefaultFileInputData fileStream(filename); if (fileStream.getLength() == 0) { printf( "[ERROR] input file %s can't be opened!\n", filename); return false; } char testString[17]; fileStream.read(testString, 16); testString[16] = 0; if (strcmp("SEBD", testString) == 0) { isBinary = true; return true; } if (strcmp("<PhysXCollection", testString) == 0) { isBinary = false; return true; } printf( "[ERROR] input file %s seems neither an xml nor a binary serialized collection file!\n", filename); return false; } static PxCollection* deserializeCollection(PxInputData& inputData, bool isBinary, PxCollection* sharedCollection, PxSerializationRegistry& sr) { PxCollection* collection = NULL; if(isBinary) { PxU32 length = inputData.getLength(); PxU8* memBlock = static_cast<PxU8*>(malloc(length+PX_SERIAL_FILE_ALIGN-1)); gMemBlocks[gNbMemBlocks++] = memBlock; void* alignedBlock = reinterpret_cast<void*>((size_t(memBlock)+PX_SERIAL_FILE_ALIGN-1)&~(PX_SERIAL_FILE_ALIGN-1)); inputData.read(alignedBlock, length); collection = PxSerialization::createCollectionFromBinary(alignedBlock, sr, sharedCollection); } else { PxTolerancesScale scale; PxCookingParams params(scale); collection = PxSerialization::createCollectionFromXml(inputData, params, sr, sharedCollection); } return collection; } void initPhysics() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0, -9.81f, 0); gDispatcher = PxDefaultCpuDispatcherCreate(1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gSerializationRegistry = PxSerialization::createSerializationRegistry(*gPhysics); } void cleanupPhysics() { PX_RELEASE(gSerializationRegistry); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); // releases of all objects for(PxU32 i=0; i<gNbMemBlocks; i++) free(gMemBlocks[i]); // now that the objects have been released, it's safe to release the space they occupy if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetLoadCollection done.\n"); } static void serializeCollection(PxCollection& collection, PxCollection* externalRefs, const char* filename, bool toBinary) { PxDefaultFileOutputStream outputStream(filename); if (!outputStream.isValid()) { printf( "[ERROR] Could not open file %s!\n", filename); return; } bool bret; if (toBinary) { bret = PxSerialization::serializeCollectionToBinary(outputStream, collection, *gSerializationRegistry, externalRefs); } else { bret = PxSerialization::serializeCollectionToXml(outputStream, collection, *gSerializationRegistry, NULL, externalRefs); } if(bret) printf( "Generated: \"%s\"\n", filename); else printf( "[ERROR] Failure when generating %s!\n", filename); } static void generateExampleFiles() { PxCollection* collection = PxCreateCollection(); PxCollection* collectionA = PxCreateCollection(); PxCollection* collectionB = PxCreateCollection(); PX_ASSERT( (collection != NULL) && (collectionA != NULL) && (collectionB != NULL) ); PxMaterial *material = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PX_ASSERT( material ); PxShape* planeShape = gPhysics->createShape(PxPlaneGeometry(), *material); PxShape* boxShape = gPhysics->createShape(PxBoxGeometry(2.f, 2.f, 2.f), *material); PxRigidStatic* rigidStatic = PxCreateStatic(*gPhysics, PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxHalfPi, PxVec3(0.f, 0.f, 1.f))), *planeShape); PxRigidDynamic* rigidDynamic = PxCreateDynamic(*gPhysics, PxTransform(PxVec3(0.f, 2.f, 0.f)), *boxShape, 1.f); collection->add(*material); collection->add(*planeShape); collection->add(*boxShape); collection->add(*rigidStatic); collection->add(*rigidDynamic); PxSerialization::complete(*collection, *gSerializationRegistry); PX_ASSERT(PxSerialization::isSerializable(*collection, *gSerializationRegistry)); collectionA->add(*material); collectionA->add(*planeShape); collectionA->add(*boxShape); PxSerialization::complete(*collectionA, *gSerializationRegistry); PxSerialization::createSerialObjectIds(*collectionA, PxSerialObjectId(1)); PX_ASSERT(PxSerialization::isSerializable(*collectionA, *gSerializationRegistry)); collectionB->add(*rigidStatic); collectionB->add(*rigidDynamic); PxSerialization::complete(*collectionB, *gSerializationRegistry, collectionA); PX_ASSERT(PxSerialization::isSerializable(*collectionB, *gSerializationRegistry, collectionA)); serializeCollection(*collection, NULL, "collection.xml", false); serializeCollection(*collectionA, NULL, "collectionA.xml", false); serializeCollection(*collectionB, collectionA, "collectionB.xml", false); serializeCollection(*collection, NULL, "collection.bin", true); serializeCollection(*collectionA, NULL, "collectionA.bin", true); serializeCollection(*collectionB, collectionA, "collectionB.bin", true); collection->release(); collectionA->release(); collectionB->release(); } int snippetMain(int argc, const char *const* argv) { if(!parseCommandLine(gParameters, argc, argv)) return 1; initPhysics(); if(gParameters.generateExampleFiles) generateExampleFiles(); // collection that may have shared objects PxCollection* firstCollection = NULL; for(PxU32 i=0; i<gParameters.nbFiles; i++) { const char* filename = gParameters.inputFiles[i]; bool isBinary; bool validFile = checkFile(isBinary, filename); if (!validFile) break; PxDefaultFileInputData inputStream(filename); PxCollection* collection = deserializeCollection(inputStream, isBinary, firstCollection, *gSerializationRegistry); if (!collection) { printf( "[ERROR] deserialization failure! filename: %s\n", filename); break; } else { printf( "Loaded: \"%s\"\n", filename); } gScene->addCollection(*collection); if (i == 0) { firstCollection = collection; } else { collection->release(); } } if (firstCollection) firstCollection->release(); for (unsigned i = 0; i < 20; i++) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } cleanupPhysics(); return 0; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsoftbodyattachment/SnippetSoftBodyAttachment.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet demonstrates how to tie rigid and softbodies together. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetsoftbody/SnippetSoftBody.h" #include "../snippetsoftbody/MeshGenerator.h" #include "extensions/PxTetMakerExt.h" #include "extensions/PxTetrahedronMeshExt.h" #include "extensions/PxSoftBodyExt.h" using namespace physx; using namespace meshgenerator; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxCudaContextManager* gCudaContextManager = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; std::vector<SoftBody> gSoftBodies; static PxFilterFlags softBodyRigidBodyFilter(PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(attributes1); PX_UNUSED(constantBlock); PX_UNUSED(constantBlockSize); if (filterData0.word2 != 0 && filterData0.word2 != filterData1.word2) return PxFilterFlag::eKILL; pairFlags |= PxPairFlag::eCONTACT_DEFAULT; return PxFilterFlag::eDEFAULT; } void addSoftBody(PxSoftBody* softBody, const PxFEMParameters& femParams, PxFEMSoftBodyMaterial* femMaterial, const PxTransform& transform, const PxReal density, const PxReal scale, const PxU32 iterCount/*, PxMaterial* tetMeshMaterial*/) { PxShape* shape = softBody->getShape(); PxVec4* simPositionInvMassPinned; PxVec4* simVelocityPinned; PxVec4* collPositionInvMassPinned; PxVec4* restPositionPinned; PxSoftBodyExt::allocateAndInitializeHostMirror(*softBody, gCudaContextManager, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); const PxReal maxInvMassRatio = 50.f; softBody->setParameter(femParams); shape->setSoftBodyMaterials(&femMaterial, 1); softBody->setSolverIterationCounts(iterCount); PxSoftBodyExt::transform(*softBody, transform, scale, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); PxSoftBodyExt::updateMass(*softBody, density, maxInvMassRatio, simPositionInvMassPinned); PxSoftBodyExt::copyToDevice(*softBody, PxSoftBodyDataFlag::eALL, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); SoftBody sBody(softBody, gCudaContextManager); gSoftBodies.push_back(sBody); PX_PINNED_HOST_FREE(gCudaContextManager, simPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, simVelocityPinned); PX_PINNED_HOST_FREE(gCudaContextManager, collPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, restPositionPinned); } static PxSoftBody* createSoftBody(const PxCookingParams& params, const PxArray<PxVec3>& triVerts, const PxArray<PxU32>& triIndices, bool useCollisionMeshForSimulation = false) { PxFEMSoftBodyMaterial* material = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); material->setDamping(0.005f); PxSoftBodyMesh* softBodyMesh; PxU32 numVoxelsAlongLongestAABBAxis = 8; PxSimpleTriangleMesh surfaceMesh; surfaceMesh.points.count = triVerts.size(); surfaceMesh.points.data = triVerts.begin(); surfaceMesh.triangles.count = triIndices.size() / 3; surfaceMesh.triangles.data = triIndices.begin(); if (useCollisionMeshForSimulation) { softBodyMesh = PxSoftBodyExt::createSoftBodyMeshNoVoxels(params, surfaceMesh, gPhysics->getPhysicsInsertionCallback()); } else { softBodyMesh = PxSoftBodyExt::createSoftBodyMesh(params, surfaceMesh, numVoxelsAlongLongestAABBAxis, gPhysics->getPhysicsInsertionCallback()); } //Alternatively one can cook a softbody mesh in a single step //tetMesh = cooking.createSoftBodyMesh(simulationMeshDesc, collisionMeshDesc, softbodyDesc, physics.getPhysicsInsertionCallback()); PX_ASSERT(softBodyMesh); if (!gCudaContextManager) return NULL; PxSoftBody* softBody = gPhysics->createSoftBody(*gCudaContextManager); if (softBody) { PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE; PxFEMSoftBodyMaterial* materialPtr = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); PxTetrahedronMeshGeometry geometry(softBodyMesh->getCollisionMesh()); PxShape* shape = gPhysics->createShape(geometry, &materialPtr, 1, true, shapeFlags); if (shape) { softBody->attachShape(*shape); shape->setSimulationFilterData(PxFilterData(0, 0, 2, 0)); } softBody->attachSimulationMesh(*softBodyMesh->getSimulationMesh(), *softBodyMesh->getSoftBodyAuxData()); gScene->addActor(*softBody); PxFEMParameters femParams; addSoftBody(softBody, femParams, material, PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxIdentity)), 100.f, 1.0f, 30); softBody->setSoftBodyFlag(PxSoftBodyFlag::eDISABLE_SELF_COLLISION, true); } return softBody; } static PxRigidDynamic* createRigidCube(PxReal halfExtent, const PxVec3& position) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); shape->setSimulationFilterData(PxFilterData(0, 0, 1, 0)); PxTransform localTm(position); PxRigidDynamic* body = gPhysics->createRigidDynamic(localTm); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); shape->release(); return body; } static void connectCubeToSoftBody(PxRigidDynamic* cube, PxReal cubeHalfExtent, const PxVec3& cubePosition, PxSoftBody* softBody, PxU32 pointGridResolution = 10) { float f = 2.0f * cubeHalfExtent / (pointGridResolution - 1); for (PxU32 ix = 0; ix < pointGridResolution; ++ix) { PxReal x = ix * f - cubeHalfExtent; for (PxU32 iy = 0; iy < pointGridResolution; ++iy) { PxReal y = iy * f - cubeHalfExtent; for (PxU32 iz = 0; iz < pointGridResolution; ++iz) { PxReal z = iz * f - cubeHalfExtent; PxVec3 p(x, y, z); PxVec4 bary; PxI32 tet = PxTetrahedronMeshExt::findTetrahedronContainingPoint(softBody->getCollisionMesh(), p + cubePosition, bary); if (tet >= 0) softBody->addTetRigidAttachment(cube, tet, bary, p); } } } } static void createSoftbodies(const PxCookingParams& params) { PxArray<PxVec3> triVerts; PxArray<PxU32> triIndices; PxReal maxEdgeLength = 1; createCube(triVerts, triIndices, PxVec3(0, 9.5, 0), 2.5); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); PxSoftBody* softBodyCube = createSoftBody(params, triVerts, triIndices, true); createSphere(triVerts, triIndices, PxVec3(0,4.5,0), 2.5, maxEdgeLength); PxSoftBody* softBodySphere = createSoftBody(params, triVerts, triIndices); createConeY(triVerts, triIndices, PxVec3(0, 12.5, 0), 2.0f, 3.5); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); PxSoftBody* softBodyCone = createSoftBody(params, triVerts, triIndices); PxReal halfExtent = 1; PxVec3 cubePosA(0, 7.25, 0); PxVec3 cubePosB(0, 11.75, 0); PxRigidDynamic* rigidCubeA = createRigidCube(halfExtent, cubePosA); PxRigidDynamic* rigidCubeB = createRigidCube(halfExtent, cubePosB); connectCubeToSoftBody(rigidCubeA, 2*halfExtent, cubePosA, softBodySphere); connectCubeToSoftBody(rigidCubeA, 2*halfExtent, cubePosA, softBodyCube); connectCubeToSoftBody(rigidCubeB, 2*halfExtent, cubePosB, softBodyCube); connectCubeToSoftBody(rigidCubeB, 2*halfExtent, cubePosB, softBodyCone); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); // initialize cuda PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (gCudaContextManager && !gCudaContextManager->contextIsValid()) { gCudaContextManager->release(); gCudaContextManager = NULL; printf("Failed to initialize cuda context.\n"); } PxTolerancesScale scale; gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, scale, true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxCookingParams params(scale); params.meshWeldTolerance = 0.001f; params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES); params.buildTriangleAdjacencies = false; params.buildGPUData = true; PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); if (!sceneDesc.cudaContextManager) sceneDesc.cudaContextManager = gCudaContextManager; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_ACTIVE_ACTORS; sceneDesc.sceneQueryUpdateMode = PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.gpuMaxNumPartitions = 8; sceneDesc.filterShader = softBodyRigidBodyFilter; sceneDesc.solverType = PxSolverType::ePGS; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createSoftbodies(params); } void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; gScene->simulate(dt); gScene->fetchResults(true); for (PxU32 i = 0; i < gSoftBodies.size(); i++) { SoftBody* sb = &gSoftBodies[i]; sb->copyDeformedVerticesFromGPU(); } } void cleanupPhysics(bool /*interactive*/) { for (PxU32 i = 0; i < gSoftBodies.size(); i++) gSoftBodies[i].release(); gSoftBodies.clear(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); gCudaContextManager->release(); PX_RELEASE(gFoundation); printf("Snippet Softbody-Rigid-Attachments done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsoftbodyattachment/SnippetSoftBodyAttachmentRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetsoftbody/SnippetSoftBody.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern std::vector<SoftBody> gSoftBodies; namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); const PxVec3 dynColor(1.0f, 0.5f, 0.25f); const PxVec3 rcaColor(0.6f*0.75f, 0.8f*0.75f, 1.0f*0.75f); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } for (PxU32 i = 0; i < gSoftBodies.size(); i++) { SoftBody* sb = &gSoftBodies[i]; Snippets::renderSoftBody(sb->mSoftBody, sb->mPositionsInvMass, true, rcaColor); } Snippets::finishRender(); } void cleanup() { delete sCamera; cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(10.0f, 10.0f, 10.0f), PxVec3(-0.6f, -0.2f, -0.7f)); Snippets::setupDefault("PhysX Snippet Softbody-Rigid-Attachments", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); cleanup(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsplitsim/SnippetSplitSimRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC); if(nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); const PxVec3 kinematicColor(0.6f*0.5f, 0.8f*0.5f, 1.0f*0.5f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); for(PxU32 i=0; i<nbActors; ++i) { PxRigidActor* actor = actors[i]; PxRigidDynamic* dyn = actor->is<PxRigidDynamic>(); if(dyn->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC) Snippets::renderActors(&actor, 1, true, kinematicColor, NULL, false); else Snippets::renderActors(&actor, 1, true, dynColor, NULL, false); } } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(34.110470f, 22.652895f, 19.877836f), PxVec3(-0.709846f, -0.583771f, -0.394120f)); Snippets::setupDefault("PhysX Snippet Split Sim", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsplitsim/SnippetSplitSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // ******************************************************************************************************* // In addition to the simulate() function, which performs both collision detection and dynamics update, // the PhysX SDK provides an api for separate execution of the collision detection and dynamics update steps. // We shall refer to this feature as "split sim". This snippet demonstrates two ways to use the split sim feature // so that application work can be performed concurrently with the collision detection step. // The snippet creates a list of kinematic box actors along with a number of dynamic actors that // interact with the kinematic actors. //The defines OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG and OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG //demonstrate two distinct modes of split sim operation: // (1)Enabling OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG allows the collision detection step to run in parallel // with the renderer and with the update of the kinematic target poses without introducing any lag between // application time and physics time. This is equivalent to calling simulate() and fetchResults() with the key // difference being that the application can schedule work to run concurrently with the collision detection. // A consequence of this approach is that the first frame is more expensive than subsequent frames because it has to // perform blocking collision detection and dynamics update calls. // (2)OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG also allows the collision to run in parallel with // the renderer and the update of the kinematic target poses but this time with a lag between physics time and // application time; that is, the physics is always a single timestep behind the application because the first // frame merely starts the collision detection for the subsequent frame. A consequence of this approach is that // the first frame is cheaper than subsequent frames. // ******************************************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" //This will allow the split sim to overlap collision and render and game logic. #define OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG 1 #define OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG 0 using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; #define NB_KINE_X 16 #define NB_KINE_Y 16 #define KINE_SCALE 3.1f static bool isFirstFrame = true; PxRigidDynamic* gKinematics[NB_KINE_Y][NB_KINE_X]; PxTransform gKinematicTargets[NB_KINE_Y][NB_KINE_X]; void createDynamics() { const PxU32 NbX = 8; const PxU32 NbY = 8; const PxVec3 dims(0.2f, 0.1f, 0.2f); const PxReal sphereRadius = 0.2f; const PxReal capsuleRadius = 0.2f; const PxReal halfHeight = 0.5f; const PxU32 NbLayers = 3; const float YScale = 0.4f; const float YStart = 6.0f; PxShape* boxShape = gPhysics->createShape(PxBoxGeometry(dims), *gMaterial); PxShape* sphereShape = gPhysics->createShape(PxSphereGeometry(sphereRadius), *gMaterial); PxShape* capsuleShape = gPhysics->createShape(PxCapsuleGeometry(capsuleRadius, halfHeight), *gMaterial); PX_UNUSED(boxShape); PX_UNUSED(sphereShape); PX_UNUSED(capsuleShape); for(PxU32 j=0;j<NbLayers;j++) { const float angle = float(j)*0.08f; const PxQuat rot = PxGetRotYQuat(angle); const float ScaleX = 4.0f; const float ScaleY = 4.0f; for(PxU32 y=0;y<NbY;y++) { for(PxU32 x=0;x<NbX;x++) { const float xf = (float(x)-float(NbX)*0.5f)*ScaleX; const float yf = (float(y)-float(NbY)*0.5f)*ScaleY; PxRigidDynamic* dynamic = NULL; PxU32 v = j&3; PxVec3 pos = PxVec3(xf, YStart + float(j)*YScale, yf); switch(v) { case 0: { PxTransform pose(pos, rot); dynamic = gPhysics->createRigidDynamic(pose); dynamic->attachShape(*boxShape); break; } case 1: { PxTransform pose(pos, PxQuat(PxIdentity)); dynamic = gPhysics->createRigidDynamic(pose); dynamic->attachShape(*sphereShape); break; } default: { PxTransform pose(pos, rot); dynamic = gPhysics->createRigidDynamic(pose); dynamic->attachShape(*capsuleShape); break; } }; PxRigidBodyExt::updateMassAndInertia(*dynamic, 10.f); gScene->addActor(*dynamic); } } } } void createGroudPlane() { PxTransform pose = PxTransform(PxVec3(0.0f, 0.0f, 0.0f),PxQuat(PxHalfPi, PxVec3(0.0f, 0.0f, 1.0f))); PxRigidStatic* actor = gPhysics->createRigidStatic(pose); PxShape* shape = PxRigidActorExt::createExclusiveShape(*actor, PxPlaneGeometry(), *gMaterial); PX_UNUSED(shape); gScene->addActor(*actor); } void createKinematics() { const PxU32 NbX = NB_KINE_X; const PxU32 NbY = NB_KINE_Y; const PxVec3 dims(1.5f, 0.2f, 1.5f); const PxQuat rot = PxQuat(PxIdentity); const float YScale = 0.4f; PxShape* shape = gPhysics->createShape(PxBoxGeometry(dims), *gMaterial); const float ScaleX = KINE_SCALE; const float ScaleY = KINE_SCALE; for(PxU32 y=0;y<NbY;y++) { for(PxU32 x=0;x<NbX;x++) { const float xf = (float(x)-float(NbX)*0.5f)*ScaleX; const float yf = (float(y)-float(NbY)*0.5f)*ScaleY; PxTransform pose(PxVec3(xf, 0.2f + YScale, yf), rot); PxRigidDynamic* body = gPhysics->createRigidDynamic(pose); body->attachShape(*shape); gScene->addActor(*body); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gKinematics[y][x] = body; } } } void updateKinematicTargets(PxReal timeStep) { const float YScale = 0.4f; PxTransform motion; motion.q = PxQuat(PxIdentity); static float gTime = 0.0f; gTime += timeStep; const PxU32 NbX = NB_KINE_X; const PxU32 NbY = NB_KINE_Y; const float Coeff = 0.2f; const float ScaleX = KINE_SCALE; const float ScaleY = KINE_SCALE; for(PxU32 y=0;y<NbY;y++) { for(PxU32 x=0;x<NbX;x++) { const float xf = (float(x)-float(NbX)*0.5f)*ScaleX; const float yf = (float(y)-float(NbY)*0.5f)*ScaleY; const float h = sinf(gTime*2.0f + float(x)*Coeff + + float(y)*Coeff)*2.0f; motion.p = PxVec3(xf, h + 2.0f + YScale, yf); gKinematicTargets[y][x] = motion; } } } void applyKinematicTargets() { const PxU32 NbX = NB_KINE_X; const PxU32 NbY = NB_KINE_Y; for(PxU32 y=0;y<NbY;y++) { for(PxU32 x=0;x<NbX;x++) { PxRigidDynamic* kine = gKinematics[y][x]; const PxTransform& target = gKinematicTargets[y][x]; kine->setKinematicTarget(target); } } } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createKinematics(); createDynamics(); } #if OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG void stepPhysics(bool /*interactive*/) { const PxReal timeStep = 1.0f/60.0f; if(isFirstFrame) { //Run the first frame's collision detection gScene->collide(timeStep); isFirstFrame = false; } //update the kinematice target pose in parallel with collision running updateKinematicTargets(timeStep); gScene->fetchCollision(true); //apply the computed and buffered kinematic target poses applyKinematicTargets(); gScene->advance(); gScene->fetchResults(true); //Run the deferred collision detection for the next frame. This will run in parallel with render. gScene->collide(timeStep); } #elif OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG void stepPhysics(bool /*interactive*/) { PxReal timeStep = 1.0/60.0f; //update the kinematice target pose in parallel with collision running updateKinematicTargets(timeStep); if(!isFirstFrame) { gScene->fetchCollision(true); //apply the computed and buffered kinematic target poses applyKinematicTargets(); gScene->advance(); gScene->fetchResults(true); } else applyKinematicTargets(); isFirstFrame = false; //Run the deferred collision detection for the next frame. This will run in parallel with render. gScene->collide(timeStep); } #else void stepPhysics(bool /*interactive*/) { PxReal timeStep = 1.0/60.0f; //update the kinematice target pose in parallel with collision running gScene->collide(timeStep); updateKinematicTargets(timeStep); gScene->fetchCollision(true); //apply the computed and buffered kinematic target poses applyKinematicTargets(); gScene->advance(); gScene->fetchResults(true); } #endif void cleanupPhysics(bool /*interactive*/) { #if OVERLAP_COLLISION_AND_RENDER_WITH_NO_LAG || OVERLAP_COLLISION_AND_RENDER_WITH_ONE_FRAME_LAG //Close out remainder of previously running scene. If we don't do this, it will be implicitly done //in gScene->release() but a warning will be issued. gScene->fetchCollision(true); gScene->advance(); gScene->fetchResults(true); #endif PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetSplitSim done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomconvex/SnippetCustomConvexRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void debugRender(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if (nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } debugRender(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-20.0f, 20.0f, -20.0f), PxVec3(0.6f, -0.4f, 0.6f)); Snippets::setupDefault("PhysX Snippet CustomConvex", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } struct RenderMesh { std::vector<PxVec3> positions, normals; }; RenderMesh* createRenderCylinder(float height, float radius, float margin) { struct InternalRenderHelper { InternalRenderHelper(float height_, float radius_, float margin_) : height(height_), radius(radius_), margin(margin_) { mesh = new RenderMesh(); halfHeight = height * 0.5f; sides = (int)ceilf(6.2832f / (2 * acosf((radius - err) / radius))); step = 6.2832f / sides; } float height, radius, margin; RenderMesh* mesh; std::vector<PxVec3> positions; std::vector<PxVec3> normals; float halfHeight; float err = 0.001f; int sides; float step; void addVertex(int index) { mesh->positions.push_back(positions[index]); mesh->normals.push_back(normals[index]); } void addTop(const PxVec3& p0, const PxVec3& n0, const PxVec3& p1, const PxVec3& n1, const PxVec3& ax) { int base = int(positions.size()); positions.push_back(p0); normals.push_back(n0); for (int i = 0; i < sides; ++i) { positions.push_back(PxQuat(i * step, ax).rotate(p1)); normals.push_back(PxQuat(i * step, ax).rotate(n1)); } for (int i = 0; i < sides; ++i) { addVertex(base); addVertex(base + 1 + i); addVertex(base + 1 + (i + 1) % sides); } } void addRing(const PxVec3& p0, const PxVec3& n0, const PxVec3& ax) { int base = int(positions.size()); for (int i = 0; i < sides; ++i) { positions.push_back(PxQuat(i * step, ax).rotate(p0)); normals.push_back(PxQuat(i * step, ax).rotate(n0)); } for (int i = 0; i < sides; ++i) { addVertex(base - sides + i); addVertex(base + i); addVertex(base - sides + (i + 1) % sides); addVertex(base - sides + (i + 1) % sides); addVertex(base + i); addVertex(base + (i + 1) % sides); } } void addBottom(const PxVec3& p0, const PxVec3& n0, const PxVec3& /*ax*/) { int base = int(positions.size()); positions.push_back(p0); normals.push_back(n0); for (int i = 0; i < sides; ++i) { addVertex(base - sides + i); addVertex(base); addVertex(base - sides + (i + 1) % sides); } } void run() { int sides2 = margin > 0 ? (int)ceilf(1.5708f / (2 * acosf((margin - err) / margin))) : 1; float step2 = 1.5708f / sides2; addTop(PxVec3(halfHeight + margin, 0, 0), PxVec3(1, 0, 0), PxVec3(halfHeight + margin, radius, 0), PxVec3(1, 0, 0), PxVec3(1, 0, 0)); for (int i = 1; i <= sides2; ++i) { PxVec3 n = PxQuat(i * step2, PxVec3(0, 0, 1)).rotate(PxVec3(1, 0, 0)); addRing(PxVec3(halfHeight, radius, 0) + n * margin, n, PxVec3(1, 0, 0)); } for (int i = 0; i <= sides2; ++i) { PxVec3 n = PxQuat(i * step2, PxVec3(0, 0, 1)).rotate(PxVec3(0, 1, 0)); addRing(PxVec3(-halfHeight, radius, 0) + n * margin, n, PxVec3(1, 0, 0)); } addBottom(PxVec3(-halfHeight - margin, 0, 0), PxVec3(-1, 0, 0), PxVec3(1, 0, 0)); } }; InternalRenderHelper renderHelper(height, radius, margin); renderHelper.run(); return renderHelper.mesh; } RenderMesh* createRenderCone(float height, float radius, float margin) { struct InternalRenderHelper { InternalRenderHelper(float height_, float radius_, float margin_) : height(height_), radius(radius_), margin(margin_) { mesh = new RenderMesh(); halfHeight = height * 0.5f; sides = (int)ceilf(6.2832f / (2 * acosf(((radius + margin) - err) / (radius + margin)))); step = 6.2832f / sides; } float height, radius, margin; RenderMesh* mesh; std::vector<PxVec3> positions; std::vector<PxVec3> normals; float halfHeight; float err = 0.001f; int sides; float step; void addVertex(int index) { mesh->positions.push_back(positions[index]); mesh->normals.push_back(normals[index]); } void addTop(const PxVec3& p0, const PxVec3& n0, const PxVec3& p1, const PxVec3& n1, const PxVec3& ax) { int base = int(positions.size()); positions.push_back(p0); normals.push_back(n0); for (int i = 0; i < sides; ++i) { positions.push_back(PxQuat(i * step, ax).rotate(p1)); normals.push_back(PxQuat(i * step, ax).rotate(n1)); } for (int i = 0; i < sides; ++i) { addVertex(base); addVertex(base + 1 + i); addVertex(base + 1 + (i + 1) % sides); } } void addRing(const PxVec3& p0, const PxVec3& n0, const PxVec3& ax) { int base = int(positions.size()); for (int i = 0; i < sides; ++i) { positions.push_back(PxQuat(i * step, ax).rotate(p0)); normals.push_back(PxQuat(i * step, ax).rotate(n0)); } for (int i = 0; i < sides; ++i) { addVertex(base - sides + i); addVertex(base + i); addVertex(base - sides + (i + 1) % sides); addVertex(base - sides + (i + 1) % sides); addVertex(base + i); addVertex(base + (i + 1) % sides); } } void addBottom(const PxVec3& p0, const PxVec3& n0, const PxVec3& /*ax*/) { int base = int(positions.size()); positions.push_back(p0); normals.push_back(n0); for (int i = 0; i < sides; ++i) { addVertex(base - sides + i); addVertex(base); addVertex(base - sides + (i + 1) % sides); } } void run() { addTop(PxVec3(halfHeight + margin, 0, 0), PxVec3(1, 0, 0), PxVec3(halfHeight + margin, 0, 0), PxVec3(1, 0, 0), PxVec3(1, 0, 0)); float cosAlph = radius / sqrtf(height * height + radius * radius); float alph = acosf(cosAlph); int sides2 = margin > 0 ? (int)ceilf(alph / (2 * acosf((margin - err) / margin))) : 1; float step2 = alph / sides2; for (int i = 1; i <= sides2; ++i) { PxVec3 n = PxQuat(i * step2, PxVec3(0, 0, 1)).rotate(PxVec3(1, 0, 0)); addRing(PxVec3(halfHeight, 0, 0) + n * margin, n, PxVec3(1, 0, 0)); } sides2 = margin > 0 ? (int)ceilf((3.1416f - alph) / (2 * acosf((margin - err) / margin))) : 1; step2 = (3.1416f - alph) / sides2; for (int i = 0; i <= sides2; ++i) { PxVec3 n = PxQuat(alph + i * step2, PxVec3(0, 0, 1)).rotate(PxVec3(1, 0, 0)); addRing(PxVec3(-halfHeight, radius, 0) + n * margin, n, PxVec3(1, 0, 0)); } addBottom(PxVec3(-halfHeight - margin, 0, 0), PxVec3(-1, 0, 0), PxVec3(1, 0, 0)); } }; InternalRenderHelper renderHelper(height, radius, margin); renderHelper.run(); return renderHelper.mesh; } void destroyRenderMesh(RenderMesh* mesh) { delete mesh; } void renderMesh(const RenderMesh& mesh, const PxTransform& pose, bool sleeping) { const PxVec3 color(1.0f, 0.5f, 0.25f); const PxMat44 shapePose(pose); glPushMatrix(); glMultMatrixf(&shapePose.column0.x); if (sleeping) { const PxVec3 darkColor = color * 0.25f; glColor4f(darkColor.x, darkColor.y, darkColor.z, 1.0f); } else { glColor4f(color.x, color.y, color.z, 1.0f); } glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 3 * sizeof(float), mesh.positions.data()); glNormalPointer(GL_FLOAT, 3 * sizeof(float), mesh.normals.data()); glDrawArrays(GL_TRIANGLES, 0, int(mesh.positions.size())); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glPopMatrix(); bool shadows = true; if (shadows) { const PxVec3 shadowDir(0.0f, -0.7071067f, -0.7071067f); const PxReal shadowMat[] = { 1,0,0,0, -shadowDir.x / shadowDir.y,0,-shadowDir.z / shadowDir.y,0, 0,0,1,0, 0,0,0,1 }; glPushMatrix(); glMultMatrixf(shadowMat); glMultMatrixf(&shapePose.column0.x); glDisable(GL_LIGHTING); //glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glColor4f(0.1f, 0.1f, 0.1f, 1.0f); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 3 * sizeof(float), mesh.positions.data()); glNormalPointer(GL_FLOAT, 3 * sizeof(float), mesh.normals.data()); glDrawArrays(GL_TRIANGLES, 0, int(mesh.positions.size())); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glEnable(GL_LIGHTING); glPopMatrix(); } } static void PxVertex3f(const PxVec3& v) { ::glVertex3f(v.x, v.y, v.z); }; static void PxScalef(const PxVec3& v) { ::glScalef(v.x, v.y, v.z); }; void renderRaycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxRaycastHit* hit) { glDisable(GL_LIGHTING); if (hit) { glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * hit->distance); PxVertex3f(hit->position); PxVertex3f(hit->position + hit->normal); glEnd(); } else { glColor4f(0.6f, 0.0f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * maxDist); glEnd(); } glEnable(GL_LIGHTING); } void renderSweepBox(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxVec3& halfExtents, const PxSweepHit* hit) { glDisable(GL_LIGHTING); if (hit) { glColor4f(0.0f, 0.6f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * hit->distance); PxVertex3f(hit->position); PxVertex3f(hit->position + hit->normal); glEnd(); PxTransform boxPose(origin + unitDir * hit->distance); PxMat44 boxMat(boxPose); glPushMatrix(); glMultMatrixf(&boxMat.column0.x); PxScalef(halfExtents * 2); glutWireCube(1); glPopMatrix(); } else { glColor4f(0.0f, 0.3f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * maxDist); glEnd(); } glEnable(GL_LIGHTING); } void renderOverlapBox(const PxVec3& origin, const PxVec3& halfExtents, bool hit) { glDisable(GL_LIGHTING); if (hit) { glColor4f(0.0f, 0.0f, 1.0f, 1.0f); PxTransform boxPose(origin); PxMat44 boxMat(boxPose); glPushMatrix(); glMultMatrixf(&boxMat.column0.x); PxScalef(halfExtents * 2); glutWireCube(1); glPopMatrix(); } else { glColor4f(0.0f, 0.0f, 0.6f, 1.0f); PxTransform boxPose(origin); PxMat44 boxMat(boxPose); glPushMatrix(); glMultMatrixf(&boxMat.column0.x); PxScalef(halfExtents * 2); glutWireCube(1); glPopMatrix(); } glEnable(GL_LIGHTING); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomconvex/CustomConvex.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef CUSTOM_CONVEX_H #define CUSTOM_CONVEX_H #include "PxPhysicsAPI.h" struct CustomConvex : physx::PxCustomGeometry::Callbacks, physx::PxGjkQuery::Support { float margin; CustomConvex(float margin); // override PxCustomGeometry::Callbacks virtual physx::PxBounds3 getLocalBounds(const physx::PxGeometry&) const; virtual bool generateContacts(const physx::PxGeometry& geom0, const physx::PxGeometry& geom1, const physx::PxTransform& pose0, const physx::PxTransform& pose1, const physx::PxReal contactDistance, const physx::PxReal meshContactMargin, const physx::PxReal toleranceLength, physx::PxContactBuffer& contactBuffer) const; virtual physx::PxU32 raycast(const physx::PxVec3& origin, const physx::PxVec3& unitDir, const physx::PxGeometry& geom, const physx::PxTransform& pose, physx::PxReal maxDist, physx::PxHitFlags hitFlags, physx::PxU32 maxHits, physx::PxGeomRaycastHit* rayHits, physx::PxU32 stride, physx::PxRaycastThreadContext*) const; virtual bool overlap(const physx::PxGeometry& geom0, const physx::PxTransform& pose0, const physx::PxGeometry& geom1, const physx::PxTransform& pose1, physx::PxOverlapThreadContext*) const; virtual bool sweep(const physx::PxVec3& unitDir, const physx::PxReal maxDist, const physx::PxGeometry& geom0, const physx::PxTransform& pose0, const physx::PxGeometry& geom1, const physx::PxTransform& pose1, physx::PxGeomSweepHit& sweepHit, physx::PxHitFlags hitFlags, const physx::PxReal inflation, physx::PxSweepThreadContext*) const; virtual void visualize(const physx::PxGeometry&, physx::PxRenderOutput&, const physx::PxTransform&, const physx::PxBounds3&) const {} virtual bool usePersistentContactManifold(const physx::PxGeometry&, physx::PxReal&) const { return true; } // override PxGjkQuery::Support virtual physx::PxReal getMargin() const; }; struct CustomCylinder : CustomConvex { float height, radius; CustomCylinder(float _height, float _radius, float _margin) : CustomConvex(_margin), height(_height), radius(_radius) {} // override PxCustomGeometry::Callbacks DECLARE_CUSTOM_GEOMETRY_TYPE virtual void computeMassProperties(const physx::PxGeometry& geometry, physx::PxMassProperties& massProperties) const; // override PxGjkQuery::Support virtual physx::PxVec3 supportLocal(const physx::PxVec3& dir) const; }; struct CustomCone : CustomConvex { float height, radius; CustomCone(float _height, float _radius, float _margin) : CustomConvex(_margin), height(_height), radius(_radius) {} // override PxCustomGeometry::Callbacks DECLARE_CUSTOM_GEOMETRY_TYPE virtual void computeMassProperties(const physx::PxGeometry& geometry, physx::PxMassProperties& massProperties) const; // override PxGjkQuery::Support virtual physx::PxVec3 supportLocal(const physx::PxVec3& dir) const; }; #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomconvex/CustomConvex.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "collision/PxCollisionDefs.h" #include "PxImmediateMode.h" #include "geometry/PxGjkQuery.h" #include "extensions/PxGjkQueryExt.h" #include "geometry/PxCustomGeometry.h" #include "CustomConvex.h" #include "geomutils/PxContactBuffer.h" using namespace physx; CustomConvex::CustomConvex(float _margin) : margin(_margin) {} PxBounds3 CustomConvex::getLocalBounds(const PxGeometry&) const { const PxVec3 min(supportLocal(PxVec3(-1, 0, 0)).x, supportLocal(PxVec3(0, -1, 0)).y, supportLocal(PxVec3(0, 0, -1)).z); const PxVec3 max(supportLocal(PxVec3(1, 0, 0)).x, supportLocal(PxVec3(0, 1, 0)).y, supportLocal(PxVec3(0, 0, 1)).z); PxBounds3 bounds(min, max); bounds.fattenSafe(getMargin()); return bounds; } bool CustomConvex::generateContacts(const PxGeometry& geom0, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1, const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength, PxContactBuffer& contactBuffer) const { switch (int(geom1.getType())) { case PxGeometryType::eSPHERE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eCONVEXMESH: { PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1); if (PxGjkQueryExt::generateContacts(*this, geomSupport, pose0, pose1, contactDistance, toleranceLength, contactBuffer)) return true; break; } case PxGeometryType::ePLANE: { const PxPlane plane = PxPlane(1.0f, 0.0f, 0.0f, 0.0f).transform(pose1); const PxPlane localPlane = plane.inverseTransform(pose0); const PxVec3 point = supportLocal(-localPlane.n); const float dist = localPlane.distance(point); const float radius = getMargin(); if (dist < radius) { const PxVec3 n = localPlane.n; const PxVec3 p = point + n * (radius - dist) * 0.5f; PxContactPoint contact; contact.point = pose0.transform(p); contact.normal = pose0.rotate(n); contact.separation = dist - radius; contactBuffer.contact(contact); return true; } break; } case PxGeometryType::eCUSTOM: { const PxCustomGeometry& customGeom1 = static_cast<const PxCustomGeometry&>(geom1); if (customGeom1.getCustomType() == CustomCylinder::TYPE() || customGeom1.getCustomType() == CustomCone::TYPE()) // It's a CustomConvex { CustomConvex* custom1 = static_cast<CustomConvex*>(customGeom1.callbacks); if (PxGjkQueryExt::generateContacts(*this, *custom1, pose0, pose1, contactDistance, toleranceLength, contactBuffer)) return true; } else { struct ContactRecorder : immediate::PxContactRecorder { PxContactBuffer* contactBuffer; ContactRecorder(PxContactBuffer& _contactBuffer) : contactBuffer(&_contactBuffer) {} virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/) { for (PxU32 i = 0; i < nbContacts; ++i) contactBuffer->contact(contactPoints[i]); return true; } } contactRecorder(contactBuffer); PxCache contactCache; struct ContactCacheAllocator : PxCacheAllocator { PxU8 buffer[1024]; ContactCacheAllocator() { memset(buffer, 0, sizeof(buffer)); } virtual PxU8* allocateCacheData(const PxU32 /*byteSize*/) { return reinterpret_cast<PxU8*>(size_t(buffer + 0xf) & ~0xf); } } contactCacheAllocator; const PxGeometry* pGeom0 = &geom0; const PxGeometry* pGeom1 = &geom1; immediate::PxGenerateContacts(&pGeom1, &pGeom0, &pose1, &pose0, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); for (int i = 0; i < int(contactBuffer.count); ++i) contactBuffer.contacts[i].normal = -contactBuffer.contacts[i].normal; } break; } default: break; } return false; } PxU32 CustomConvex::raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& /*geom*/, const PxTransform& pose, PxReal maxDist, PxHitFlags /*hitFlags*/, PxU32 /*maxHits*/, PxGeomRaycastHit* rayHits, PxU32 /*stride*/, PxRaycastThreadContext*) const { PxReal t; PxVec3 n, p; if (PxGjkQuery::raycast(*this, pose, origin, unitDir, maxDist, t, n, p)) { PxGeomRaycastHit& hit = *rayHits; hit.distance = t; hit.position = p; hit.normal = n; return 1; } return 0; } bool CustomConvex::overlap(const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext*) const { switch (int(geom1.getType())) { case PxGeometryType::eSPHERE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eCONVEXMESH: { PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1); if (PxGjkQuery::overlap(*this, geomSupport, pose0, pose1)) return true; break; } default: break; } return false; } bool CustomConvex::sweep(const PxVec3& unitDir, const PxReal maxDist, const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxGeomSweepHit& sweepHit, PxHitFlags /*hitFlags*/, const PxReal inflation, PxSweepThreadContext*) const { switch (int(geom1.getType())) { case PxGeometryType::eSPHERE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eCONVEXMESH: { PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1, inflation); PxReal t; PxVec3 n, p; if (PxGjkQuery::sweep(*this, geomSupport, pose0, pose1, unitDir, maxDist, t, n, p)) { PxGeomSweepHit& hit = sweepHit; hit.distance = t; hit.position = p; hit.normal = n; return true; } break; } default: break; } return false; } PxReal CustomConvex::getMargin() const { return margin; } IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CustomCylinder) //PxU32 CustomCylinder::getCustomType() const //{ // return 1; //} void CustomCylinder::computeMassProperties(const physx::PxGeometry& /*geometry*/, physx::PxMassProperties& massProperties) const { float H = height + 2.0f * margin, R = radius + margin; massProperties.mass = PxPi * R * R * H; massProperties.inertiaTensor = PxMat33(PxZero); massProperties.centerOfMass = PxVec3(PxZero); massProperties.inertiaTensor[0][0] = massProperties.mass * R * R / 2.0f; massProperties.inertiaTensor[1][1] = massProperties.inertiaTensor[2][2] = massProperties.mass * (3 * R * R + H * H) / 12.0f; } PxVec3 CustomCylinder::supportLocal(const PxVec3& dir) const { float halfHeight = height * 0.5f; PxVec3 d = dir.getNormalized(); if (PxSign2(d.x) != 0 && PxSign2(d.y) == 0 && PxSign2(d.z) == 0) return PxVec3(PxSign2(d.x) * halfHeight, 0, 0); return PxVec3(PxSign2(d.x) * halfHeight, 0, 0) + PxVec3(0, d.y, d.z).getNormalized() * radius; } IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CustomCone) void CustomCone::computeMassProperties(const physx::PxGeometry&, physx::PxMassProperties& massProperties) const { float H = height + 2.0f * margin, R = radius + margin; massProperties.mass = PxPi * R * R * H / 3.0f; massProperties.inertiaTensor = PxMat33(PxZero); massProperties.centerOfMass = PxVec3(PxZero); massProperties.inertiaTensor[0][0] = massProperties.mass * R * R * 3.0f / 10.0f; massProperties.inertiaTensor[1][1] = massProperties.inertiaTensor[2][2] = massProperties.mass * (R * R * 3.0f / 20.0f + H * H * 3.0f / 80.0f); massProperties.centerOfMass[0] = -height / 4.0f; } PxVec3 CustomCone::supportLocal(const PxVec3& dir) const { float halfHeight = height * 0.5f; float cosAlph = radius / sqrtf(height * height + radius * radius); PxVec3 d = dir.getNormalized(); if (d.x > cosAlph || (PxSign2(d.x) != 0 && PxSign2(d.y) == 0 && PxSign2(d.z) == 0)) return PxVec3(PxSign2(d.x) * halfHeight, 0, 0); return PxVec3(-halfHeight, 0, 0) + PxVec3(0, d.y, d.z).getNormalized() * radius; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomconvex/SnippetCustomConvex.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet shows how to use GJK queries to create custom convex geometry. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "geometry/PxGjkQuery.h" #include "CustomConvex.h" #include "extensions/PxCustomGeometryExt.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; //static std::vector<CustomConvex*> gConvexes; static std::vector<PxCustomGeometryExt::BaseConvexCallbacks*> gConvexes; static std::vector<PxRigidActor*> gActors; struct RenderMesh; static std::vector<RenderMesh*> gMeshes; RenderMesh* createRenderCylinder(float radius, float height, float margin); RenderMesh* createRenderCone(float height, float radius, float margin); void destroyRenderMesh(RenderMesh* mesh); void renderMesh(const RenderMesh& mesh, const PxTransform& pose, bool sleeping); void renderRaycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxRaycastHit* hit); void renderSweepBox(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxVec3& halfExtents, const PxSweepHit* hit); void renderOverlapBox(const PxVec3& origin, const PxVec3& halfExtents, bool hit); static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0), PxReal density = 1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createCylinderActor(float height, float radius, float margin, const PxTransform& pose) { //CustomCylinder* cylinder = new CustomCylinder(height, radius, margin); PxCustomGeometryExt::CylinderCallbacks* cylinder = new PxCustomGeometryExt::CylinderCallbacks(height, radius, 0, margin); gConvexes.push_back(cylinder); PxRigidDynamic* actor = gPhysics->createRigidDynamic(pose); actor->setActorFlag(PxActorFlag::eVISUALIZATION, true); PxShape* shape = PxRigidActorExt::createExclusiveShape(*actor, PxCustomGeometry(*cylinder), *gMaterial); shape->setFlag(PxShapeFlag::eVISUALIZATION, true); PxRigidBodyExt::updateMassAndInertia(*actor, 100); gScene->addActor(*actor); gActors.push_back(actor); RenderMesh* mesh = createRenderCylinder(height, radius, margin); gMeshes.push_back(mesh); } static void createConeActor(float height, float radius, float margin, const PxTransform& pose) { //CustomCone* cone = new CustomCone(height, radius, margin); PxCustomGeometryExt::ConeCallbacks* cone = new PxCustomGeometryExt::ConeCallbacks(height, radius, 0, margin); gConvexes.push_back(cone); PxRigidDynamic* actor = gPhysics->createRigidDynamic(pose); actor->setActorFlag(PxActorFlag::eVISUALIZATION, true); PxShape* shape = PxRigidActorExt::createExclusiveShape(*actor, PxCustomGeometry(*cone), *gMaterial); shape->setFlag(PxShapeFlag::eVISUALIZATION, true); PxRigidBodyExt::updateMassAndInertia(*actor, 100); gScene->addActor(*actor); gActors.push_back(actor); RenderMesh* mesh = createRenderCone(height, radius, margin); gMeshes.push_back(mesh); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gScene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 1.0f); gScene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.0f); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Some custom convexes float heights[] = { 1.0f, 1.25f, 1.5f, 1.75f }; float radiuss[] = { 0.3f, 0.35f, 0.4f, 0.45f }; float margins[] = { 0.0f, 0.05f, 0.1f, 0.15f }; for (int i = 0; i < 50; ++i) { float height = heights[rand() % (sizeof(heights) / sizeof(heights[0]))]; float raduis = radiuss[rand() % (sizeof(radiuss) / sizeof(radiuss[0]))]; float margin = margins[rand() % (sizeof(margins) / sizeof(margins[0]))]; float angle = PX_PIDIV2; createCylinderActor(height, raduis, margin, (PxTransform(PxVec3(-2.0f, 2.0f + i * 2, 2.0f), PxQuat(angle, PxVec3(0.0f, 0.0f, 1.0f))))); } for (int i = 0; i < 50; ++i) { float height = heights[rand() % (sizeof(heights) / sizeof(heights[0]))]; float raduis = radiuss[rand() % (sizeof(radiuss) / sizeof(radiuss[0]))]; float margin = margins[rand() % (sizeof(margins) / sizeof(margins[0]))]; float angle = PX_PIDIV2; createConeActor(height, raduis, margin, (PxTransform(PxVec3(2.0f, 2.0f + i * 2, -2.0f), PxQuat(angle, PxVec3(0, 0, 1))))); } // Ground plane PxRigidStatic* planeActor = gPhysics->createRigidStatic(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0.0f, 0.0f, 1.0f)))); PxRigidActorExt::createExclusiveShape(*planeActor, PxPlaneGeometry(), *gMaterial); gScene->addActor(*planeActor); } void debugRender() { for (int i = 0; i < int(gConvexes.size()); ++i) { PxRigidActor* actor = gActors[i]; RenderMesh* mesh = gMeshes[i]; renderMesh(*mesh, actor->getGlobalPose(), !actor->is<PxRigidDynamic>() || actor->is<PxRigidDynamic>()->isSleeping()); } int count = 20; for (int i = 0; i < count; ++i) { float x = -count / 2.0f; PxVec3 origin(x + i, 0.5f, x); PxVec3 unitDir(0, 0, 1); float maxDist = (float)count; PxRaycastBuffer buffer; gScene->raycast(origin, unitDir, maxDist, buffer); renderRaycast(origin, unitDir, maxDist, buffer.hasBlock ? &buffer.block : nullptr); } for (int i = 0; i < count; ++i) { float x = -count / 2.0f; PxVec3 origin(x, 0.5f, x + i); PxVec3 unitDir(1, 0, 0); float maxDist = (float)count; PxVec3 halfExtents(0.2f, 0.1f, 0.4f); PxSweepBuffer buffer; gScene->sweep(PxBoxGeometry(halfExtents), PxTransform(origin), unitDir, maxDist, buffer); renderSweepBox(origin, unitDir, maxDist, halfExtents, buffer.hasBlock ? &buffer.block : nullptr); } for (int i = 0; i < count; ++i) { float x = -count / 2.0f; for (int j = 0; j < count; ++j) { PxVec3 origin(x + i, 0.0f, x + j); PxVec3 halfExtents(0.4f, 0.1f, 0.4f); PxOverlapBuffer buffer; gScene->overlap(PxBoxGeometry(halfExtents), PxTransform(origin), buffer, PxQueryFilterData(PxQueryFlag::eANY_HIT | PxQueryFlag::eDYNAMIC)); renderOverlapBox(origin, halfExtents, buffer.hasAnyHits()); } } } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { while (!gConvexes.empty()) { delete gConvexes.back(); gConvexes.pop_back(); } while (!gMeshes.empty()) { destroyRenderMesh(gMeshes.back()); gMeshes.pop_back(); } while (!gActors.empty()) { PX_RELEASE(gActors.back()); gActors.pop_back(); } PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetCustomConvex done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch (toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(1.0f), camera.rotate(PxVec3(0, 0, -1)) * 100, 3.0f); break; } } int snippetMain(int, const char* const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for (PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char* const*) { return 0; } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetfrustumquery/SnippetFrustumQueryRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderScene(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); renderScene(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet Frustum Query", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetfrustumquery/SnippetFrustumQuery.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates how to use a PxBVH to implement view-frustum culling. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif //#define BENCHMARK_MODE using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; namespace { class CustomScene { public: CustomScene(); ~CustomScene(); void release(); void addGeom(const PxGeometry& geom, const PxTransform& pose); void createBVH(); void render() const; struct Object { PxGeometryHolder mGeom; PxTransform mPose; }; PxArray<Object> mObjects; PxBVH* mBVH; }; CustomScene::CustomScene() : mBVH(NULL) { } CustomScene::~CustomScene() { } void CustomScene::release() { PX_RELEASE(mBVH); mObjects.reset(); PX_DELETE_THIS; } void CustomScene::addGeom(const PxGeometry& geom, const PxTransform& pose) { Object obj; obj.mGeom.storeAny(geom); obj.mPose = pose; mObjects.pushBack(obj); } void CustomScene::createBVH() { const PxU32 nbObjects = mObjects.size(); PxBounds3* bounds = new PxBounds3[nbObjects]; for(PxU32 i=0;i<nbObjects;i++) { Object& obj = mObjects[i]; PxGeometryQuery::computeGeomBounds(bounds[i], obj.mGeom.any(), obj.mPose); } PxBVHDesc bvhDesc; bvhDesc.bounds.count = nbObjects; bvhDesc.bounds.data = bounds; bvhDesc.bounds.stride = sizeof(PxBounds3); bvhDesc.enlargement = 0.0f; mBVH = PxCreateBVH(bvhDesc); delete [] bounds; } enum FrustumPlaneIndex { FRUSTUM_PLANE_LEFT = 0, FRUSTUM_PLANE_RIGHT = 1, FRUSTUM_PLANE_TOP = 2, FRUSTUM_PLANE_BOTTOM = 3, FRUSTUM_PLANE_NEAR = 4, FRUSTUM_PLANE_FAR = 5, }; void CustomScene::render() const { #ifdef RENDER_SNIPPET if(0) { // This codepath to draw all objects without culling const PxVec3 color(1.0f, 0.5f, 0.25f); for(PxU32 i=0;i<mObjects.size();i++) { const CustomScene::Object& obj = mObjects[i]; Snippets::renderGeoms(1, &obj.mGeom, &obj.mPose, false, color); } return; } // Extract planes from the view/proj matrices. You could also build them from the frustum's vertices. PxPlane planes[6]; { float VM[16]; glGetFloatv(GL_MODELVIEW_MATRIX, VM); const PxMat44 ViewMatrix(VM); float PM[16]; glGetFloatv(GL_PROJECTION_MATRIX, PM); const PxMat44 ProjMatrix(PM); const PxMat44 combo = ProjMatrix * ViewMatrix; planes[FRUSTUM_PLANE_LEFT].n.x = -(combo.column0[3] + combo.column0[0]); planes[FRUSTUM_PLANE_LEFT].n.y = -(combo.column1[3] + combo.column1[0]); planes[FRUSTUM_PLANE_LEFT].n.z = -(combo.column2[3] + combo.column2[0]); planes[FRUSTUM_PLANE_LEFT].d = -(combo.column3[3] + combo.column3[0]); planes[FRUSTUM_PLANE_RIGHT].n.x = -(combo.column0[3] - combo.column0[0]); planes[FRUSTUM_PLANE_RIGHT].n.y = -(combo.column1[3] - combo.column1[0]); planes[FRUSTUM_PLANE_RIGHT].n.z = -(combo.column2[3] - combo.column2[0]); planes[FRUSTUM_PLANE_RIGHT].d = -(combo.column3[3] - combo.column3[0]); planes[FRUSTUM_PLANE_TOP].n.x = -(combo.column0[3] - combo.column0[1]); planes[FRUSTUM_PLANE_TOP].n.y = -(combo.column1[3] - combo.column1[1]); planes[FRUSTUM_PLANE_TOP].n.z = -(combo.column2[3] - combo.column2[1]); planes[FRUSTUM_PLANE_TOP].d = -(combo.column3[3] - combo.column3[1]); planes[FRUSTUM_PLANE_BOTTOM].n.x = -(combo.column0[3] + combo.column0[1]); planes[FRUSTUM_PLANE_BOTTOM].n.y = -(combo.column1[3] + combo.column1[1]); planes[FRUSTUM_PLANE_BOTTOM].n.z = -(combo.column2[3] + combo.column2[1]); planes[FRUSTUM_PLANE_BOTTOM].d = -(combo.column3[3] + combo.column3[1]); planes[FRUSTUM_PLANE_NEAR].n.x = -(combo.column0[3] + combo.column0[2]); planes[FRUSTUM_PLANE_NEAR].n.y = -(combo.column1[3] + combo.column1[2]); planes[FRUSTUM_PLANE_NEAR].n.z = -(combo.column2[3] + combo.column2[2]); planes[FRUSTUM_PLANE_NEAR].d = -(combo.column3[3] + combo.column3[2]); planes[FRUSTUM_PLANE_FAR].n.x = -(combo.column0[3] - combo.column0[2]); planes[FRUSTUM_PLANE_FAR].n.y = -(combo.column1[3] - combo.column1[2]); planes[FRUSTUM_PLANE_FAR].n.z = -(combo.column2[3] - combo.column2[2]); planes[FRUSTUM_PLANE_FAR].d = -(combo.column3[3] - combo.column3[2]); for(PxU32 i=0;i<6;i++) planes[i].normalize(); } if(mBVH) { struct LocalCB : PxBVH::OverlapCallback { LocalCB(const CustomScene& scene) : mScene(scene) { mVisibles.reserve(10000); } virtual bool reportHit(PxU32 boundsIndex) { mVisibles.pushBack(boundsIndex); return true; } const CustomScene& mScene; PxArray<PxU32> mVisibles; LocalCB& operator=(const LocalCB&){return *this;} }; LocalCB cb(*this); #ifdef BENCHMARK_MODE unsigned long long time = __rdtsc(); #endif mBVH->cull(6, planes, cb); char buffer[256]; #ifdef BENCHMARK_MODE time = __rdtsc() - time; sprintf(buffer, "%d visible objects (%d)\n", cb.mVisibles.size(), int(time/1024)); #else sprintf(buffer, "%d visible objects\n", cb.mVisibles.size()); #endif const PxVec3 color(1.0f, 0.5f, 0.25f); for(PxU32 i=0;i<cb.mVisibles.size();i++) { const CustomScene::Object& obj = mObjects[cb.mVisibles[i]]; Snippets::renderGeoms(1, &obj.mGeom, &obj.mPose, false, color); } if(1) { const PxU32 nbObjects = mBVH->getNbBounds(); for(PxU32 i=0;i<nbObjects;i++) Snippets::DrawBounds(mBVH->getBounds()[i]); } Snippets::print(buffer); } #endif } } static PxConvexMesh* createConvexMesh(const PxVec3* verts, const PxU32 numVerts, const PxCookingParams& params) { PxConvexMeshDesc convexDesc; convexDesc.points.count = numVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; return PxCreateConvexMesh(params, convexDesc); } static PxConvexMesh* createCylinderMesh(const PxF32 width, const PxF32 radius, const PxCookingParams& params) { PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } return createConvexMesh(points, 32, params); } static void initScene() { } static void releaseScene() { } static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static CustomScene* gScene = NULL; void renderScene() { if(gScene) gScene->render(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; gConvexMesh = createCylinderMesh(3.0f, 1.0f, params); { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } gScene = new CustomScene; #ifdef BENCHMARK_MODE { SnippetUtils::BasicRandom rnd(42); PxVec3 v; const float coeff = 30.0f; for(int i=0;i<1000;i++) { rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxBoxGeometry(PxVec3(1.0f, 2.0f, 0.5f)), PxTransform(v+PxVec3(0.0f, 0.0f, 0.0f))); rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxSphereGeometry(1.5f), PxTransform(v+PxVec3(4.0f, 0.0f, 0.0f))); rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(v+PxVec3(-4.0f, 0.0f, 0.0f))); rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxConvexMeshGeometry(gConvexMesh), PxTransform(v+PxVec3(0.0f, 0.0f, 4.0f))); rnd.unitRandomPt(v); v*=coeff; gScene->addGeom(PxTriangleMeshGeometry(gTriangleMesh), PxTransform(v+PxVec3(0.0f, 0.0f, -4.0f))); } } #else { gScene->addGeom(PxBoxGeometry(PxVec3(1.0f, 2.0f, 0.5f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f))); gScene->addGeom(PxSphereGeometry(1.5f), PxTransform(PxVec3(4.0f, 0.0f, 0.0f))); gScene->addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(PxVec3(-4.0f, 0.0f, 0.0f))); gScene->addGeom(PxConvexMeshGeometry(gConvexMesh), PxTransform(PxVec3(0.0f, 0.0f, 4.0f))); gScene->addGeom(PxTriangleMeshGeometry(gTriangleMesh), PxTransform(PxVec3(0.0f, 0.0f, -4.0f))); } #endif gScene->createBVH(); initScene(); } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gScene); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetFrustumQuery done.\n"); } void keyPress(unsigned char /*key*/, const PxTransform& /*camera*/) { /* if(key >= 1 && key <= gScenarioCount) { gScenario = key - 1; releaseScene(); initScene(); } if(key == 'r' || key == 'R') { releaseScene(); initScene(); }*/ } int snippetMain(int, const char*const*) { printf("Frustum query snippet.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometrycollision/SnippetCustomGeometryCollisionRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void debugRender(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if (nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } debugRender(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(70.0f, 70.0f, 70.0f), PxVec3(-0.6f, -0.3f, -0.6f)); Snippets::setupDefault("PhysX Snippet GeometryCollision", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometrycollision/SnippetCustomGeometryCollision.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet shows how to implement custom geometries generateContacts // callback, using PhysX Immediate Mode contacts generation. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "PxImmediateMode.h" #include "geomutils/PxContactBuffer.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" using namespace physx; /* 10x10 grid of boxes with even boxes removed. */ struct CheckerBoard : PxCustomGeometry::Callbacks { int boardSize; float boxExtent; DECLARE_CUSTOM_GEOMETRY_TYPE CheckerBoard() : boardSize(10), boxExtent(10.0f) {} struct ContactRecorder : immediate::PxContactRecorder { PxContactBuffer* contactBuffer; ContactRecorder(PxContactBuffer& _contactBuffer) : contactBuffer(&_contactBuffer) {} virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/) { for (PxU32 i = 0; i < nbContacts; ++i) if (!contactBuffer->contact(contactPoints[i])) return false; return true; } }; struct ContactCacheAllocator : PxCacheAllocator { PxU8 buffer[1024]; ContactCacheAllocator() { memset(buffer, 0, sizeof(buffer)); } virtual PxU8* allocateCacheData(const PxU32 /*byteSize*/) { return (PxU8*)(size_t(buffer + 0xf) & ~0xf); } }; PxBounds3 getBoardLocalBounds() const { return PxBounds3(-PxVec3(boardSize * boxExtent * 0.5f, boxExtent * 0.5f, boardSize * boxExtent * 0.5f), PxVec3(boardSize * boxExtent * 0.5f, boxExtent * 0.5f, boardSize * boxExtent * 0.5f)); } virtual PxBounds3 getLocalBounds(const PxGeometry&) const { return getBoardLocalBounds(); } virtual bool generateContacts(const PxGeometry&, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1, const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength, PxContactBuffer& contactBuffer) const { PxBoxGeometry boxGeom(PxVec3(boxExtent * 0.5f)); PxGeometry* pGeom0 = &boxGeom; const PxGeometry* pGeom1 = &geom1; PxTransform pose1in0 = pose0.transformInv(pose1); PxBounds3 bounds1; PxGeometryQuery::computeGeomBounds(bounds1, geom1, pose1in0, contactDistance); ContactRecorder contactRecorder(contactBuffer); PxCache contactCache; ContactCacheAllocator contactCacheAllocator; PxBounds3 bounds0 = getBoardLocalBounds(); PxVec3 s = bounds1.minimum + bounds0.getExtents(); PxVec3 e = bounds1.maximum + bounds0.getExtents(); int sx = int(PxFloor(s.x / boxExtent)); int sy = int(PxFloor(s.y / boxExtent)); int sz = int(PxFloor(s.z / boxExtent)); int ex = int(PxFloor(e.x / boxExtent)); int ey = int(PxFloor(e.y / boxExtent)); int ez = int(PxFloor(e.z / boxExtent)); for (int x = sx; x <= ex; ++x) for (int y = sy; y <= ey; ++y) for (int z = sz; z <= ez; ++z) if (x >= 0 && x < boardSize && y >= 0 && y < boardSize && z >= 0 && z < boardSize && (x + z) & 1 && y == 0) { PxVec3 boxPos = PxVec3((x + 0.5f) * boxExtent, (y + 0.5f) * boxExtent, (z + 0.5f) * boxExtent) - bounds0.getExtents(); PxTransform p0 = pose0.transform(PxTransform(boxPos)); immediate::PxGenerateContacts(&pGeom0, &pGeom1, &p0, &pose1, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); } return true; } virtual PxU32 raycast(const PxVec3&, const PxVec3&, const PxGeometry&, const PxTransform&, PxReal, PxHitFlags, PxU32, PxGeomRaycastHit*, PxU32, PxRaycastThreadContext*) const { return 0; } virtual bool overlap(const PxGeometry&, const PxTransform&, const PxGeometry&, const PxTransform&, PxOverlapThreadContext*) const { return false; } virtual bool sweep(const PxVec3&, const PxReal, const PxGeometry&, const PxTransform&, const PxGeometry&, const PxTransform&, PxGeomSweepHit&, PxHitFlags, const PxReal, PxSweepThreadContext*) const { return false; } virtual void visualize(const PxGeometry&, PxRenderOutput&, const PxTransform&, const PxBounds3&) const {} virtual void computeMassProperties(const physx::PxGeometry&, physx::PxMassProperties&) const {} virtual bool usePersistentContactManifold(const PxGeometry&, PxReal&) const { return false; } }; IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CheckerBoard) static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidStatic* gActor = NULL; static CheckerBoard gCheckerBoard; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0), PxReal density = 1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i < size; i++) { for (PxU32 j = 0; j < size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f * 3, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Create checker board actor PxRigidStatic* checkerBoardActor = gPhysics->createRigidStatic(PxTransform(PxVec3(0, gCheckerBoard.boxExtent * 0.5f, 0))); PxRigidActorExt::createExclusiveShape(*checkerBoardActor, PxCustomGeometry(gCheckerBoard), *gMaterial); gScene->addActor(*checkerBoardActor); gActor = checkerBoardActor; // Ground plane PxRigidStatic* planeActor = gPhysics->createRigidStatic(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 0, 1)))); PxRigidActorExt::createExclusiveShape(*planeActor, PxPlaneGeometry(), *gMaterial); gScene->addActor(*planeActor); createStack(PxTransform(PxVec3(0, 22, 0)), 10, 2.0f); } void debugRender() { float boxExtent = gCheckerBoard.boxExtent; PxBounds3 boardBounds = gCheckerBoard.getBoardLocalBounds(); PxGeometryHolder geom; geom.storeAny(PxBoxGeometry(PxVec3(boxExtent * 0.5f))); for (int x = 0; x < gCheckerBoard.boardSize; ++x) for (int y = 0; y < 1; ++y) for (int z = 0; z < gCheckerBoard.boardSize; ++z) if ((x + z) & 1) { PxVec3 boxPos = PxVec3((x + 0.5f) * boxExtent, (y + 0.5f) * boxExtent, (z + 0.5f) * boxExtent) - boardBounds.getExtents(); PxTransform pose = gActor->getGlobalPose().transform(PxTransform(boxPos)); Snippets::renderGeoms(1, &geom, &pose, false, PxVec3(0.5f)); } } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetGeometryCollision done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch (toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0, 0, -1)) * 200, 3.0f); break; } } int snippetMain(int, const char* const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for (PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char* const*) { return 0; } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmultithreading/SnippetMultiThreading.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet shows how to coordinate threads performing asynchronous // work during the scene simulation. After simulate() is called, user threads // are started that perform ray-casts against the scene. The call to // fetchResults() is delayed until all ray-casts have completed. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; struct RaycastThread { SnippetUtils::Sync* mWorkReadySyncHandle; SnippetUtils::Thread* mThreadHandle; }; const PxU32 gNumThreads = 1; RaycastThread gThreads[gNumThreads]; SnippetUtils::Sync* gWorkDoneSyncHandle; const PxI32 gRayCount = 1024; volatile PxI32 gRaysAvailable; volatile PxI32 gRaysCompleted; static PxVec3 randVec3() { return (PxVec3(float(rand())/float(RAND_MAX), float(rand())/float(RAND_MAX), float(rand())/float(RAND_MAX))*2.0f - PxVec3(1.0f)).getNormalized(); } static void threadExecute(void* data) { RaycastThread* raycastThread = static_cast<RaycastThread*>(data); // Perform random raycasts against the scene until stop. for(;;) { // Wait here for the sync to be set then reset the sync // to ensure that we only perform raycast work after the // sync has been set again. SnippetUtils::syncWait(raycastThread->mWorkReadySyncHandle); SnippetUtils::syncReset(raycastThread->mWorkReadySyncHandle); // If the thread has been signaled to quit then exit this function. if (SnippetUtils::threadQuitIsSignalled(raycastThread->mThreadHandle)) break; // Perform a fixed number of random raycasts against the scene // and share the work between multiple threads. while (SnippetUtils::atomicDecrement(&gRaysAvailable) >= 0) { PxVec3 dir = randVec3(); PxRaycastBuffer buf; gScene->raycast(PxVec3(0.0f), dir.getNormalized(), 1000.0f, buf, PxHitFlag::eDEFAULT); // If this is the last raycast then signal this to the main thread. if (SnippetUtils::atomicIncrement(&gRaysCompleted) == gRayCount) { SnippetUtils::syncSet(gWorkDoneSyncHandle); } } } // Quit the current thread. SnippetUtils::threadQuit(raycastThread->mThreadHandle); } void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void createPhysicsAndScene() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); for(PxU32 i=0;i<5;i++) createStack(PxTransform(PxVec3(0,0,i*10.0f)), 10, 2.0f); } void createRaycastThreads() { // Create and start threads that will perform raycasts. // Create a sync for each thread so that a signal may be sent // from the main thread to the raycast thread that it can start // performing raycasts. for (PxU32 i=0; i < gNumThreads; ++i) { //Create a sync. gThreads[i].mWorkReadySyncHandle = SnippetUtils::syncCreate(); //Create and start a thread. gThreads[i].mThreadHandle = SnippetUtils::threadCreate(threadExecute, &gThreads[i]); } // Create another sync so that the raycast threads can signal to the main // thread that they have finished performing their raycasts. gWorkDoneSyncHandle = SnippetUtils::syncCreate(); } void initPhysics() { createPhysicsAndScene(); createRaycastThreads(); } void stepPhysics() { // Start simulation gScene->simulate(1.0f/60.0f); // Start ray-cast threads gRaysAvailable = gRayCount; gRaysCompleted = 0; // Signal to each raycast thread that they can start performing raycasts. for (PxU32 i=0; i < gNumThreads; ++i) { SnippetUtils::syncSet(gThreads[i].mWorkReadySyncHandle); } // Wait for raycast threads to finish. SnippetUtils::syncWait(gWorkDoneSyncHandle); SnippetUtils::syncReset(gWorkDoneSyncHandle); // Fetch simulation results gScene->fetchResults(true); } void cleanupPhysics() { // Signal threads to quit. for (PxU32 i=0; i < gNumThreads; ++i) { SnippetUtils::threadSignalQuit(gThreads[i].mThreadHandle); SnippetUtils::syncSet(gThreads[i].mWorkReadySyncHandle); } // Clean up raycast threads and syncs. for (PxU32 i=0; i < gNumThreads; ++i) { SnippetUtils::threadWaitForQuit(gThreads[i].mThreadHandle); SnippetUtils::threadRelease(gThreads[i].mThreadHandle); SnippetUtils::syncRelease(gThreads[i].mWorkReadySyncHandle); } // Clean up the sync for the main thread. SnippetUtils::syncRelease(gWorkDoneSyncHandle); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetMultiThreading done.\n"); } int snippetMain(int, const char*const*) { initPhysics(); for(PxU32 i=0; i<100; ++i) stepPhysics(); cleanupPhysics(); return 0; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetjoint/SnippetJoint.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates simple use of joints in physx // // It creates a chain of objects joined by limited spherical joints, a chain // joined by fixed joints which is breakable, and a chain of damped D6 joints // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } // spherical joint limited to an angle of at most pi/4 radians (45 degrees) static PxJoint* createLimitedSpherical(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1) { PxSphericalJoint* j = PxSphericalJointCreate(*gPhysics, a0, t0, a1, t1); j->setLimitCone(PxJointLimitCone(PxPi/4, PxPi/4)); j->setSphericalJointFlag(PxSphericalJointFlag::eLIMIT_ENABLED, true); return j; } // fixed, breakable joint static PxJoint* createBreakableFixed(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1) { PxFixedJoint* j = PxFixedJointCreate(*gPhysics, a0, t0, a1, t1); j->setBreakForce(1000, 100000); j->setConstraintFlag(PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES, true); j->setConstraintFlag(PxConstraintFlag::eDISABLE_PREPROCESSING, true); return j; } // D6 joint with a spring maintaining its position static PxJoint* createDampedD6(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1) { PxD6Joint* j = PxD6JointCreate(*gPhysics, a0, t0, a1, t1); j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); j->setDrive(PxD6Drive::eSLERP, PxD6JointDrive(0, 1000, FLT_MAX, true)); return j; } typedef PxJoint* (*JointCreateFunction)(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1); // create a chain rooted at the origin and extending along the x-axis, all transformed by the argument t. static void createChain(const PxTransform& t, PxU32 length, const PxGeometry& g, PxReal separation, JointCreateFunction createJoint) { PxVec3 offset(separation/2, 0, 0); PxTransform localTm(offset); PxRigidDynamic* prev = NULL; for(PxU32 i=0;i<length;i++) { PxRigidDynamic* current = PxCreateDynamic(*gPhysics, t*localTm, g, *gMaterial, 1.0f); (*createJoint)(prev, prev ? PxTransform(offset) : t, current, PxTransform(-offset)); gScene->addActor(*current); prev = current; localTm.p.x += separation; } } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createChain(PxTransform(PxVec3(0.0f, 20.0f, 0.0f)), 5, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createLimitedSpherical); createChain(PxTransform(PxVec3(0.0f, 20.0f, -10.0f)), 5, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createBreakableFixed); createChain(PxTransform(PxVec3(0.0f, 20.0f, -20.0f)), 5, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createDampedD6); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetJoint done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0,0,-1))*200); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetjoint/SnippetJointRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(34.613838f, 27.653027f, 9.363596f), PxVec3(-0.754040f, -0.401930f, -0.519496f)); Snippets::setupDefault("PhysX Snippet Joint", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbfmultimat/SnippetPBFMultiMat.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates fluid simulation using multiple materials. It // creates a container and drops a body of water. The dynamics of the fluid // is computed using Position-based Fluid (PBF) which is a purely // particle-based algorithm. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "extensions/PxParticleExt.h" using namespace physx; using namespace ExtGpu; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxPBDParticleSystem* gParticleSystem = NULL; static PxParticleBuffer* gParticleBuffer = NULL; static bool gIsRunning = true; static void initScene() { PxCudaContextManager* cudaContextManager = NULL; if (PxGetSuggestedCudaDeviceOrdinal(gFoundation->getErrorCallback()) >= 0) { // initialize CUDA PxCudaContextManagerDesc cudaContextManagerDesc; cudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (cudaContextManager && !cudaContextManager->contextIsValid()) { cudaContextManager->release(); cudaContextManager = NULL; } } if (cudaContextManager == NULL) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Failed to initialize CUDA!\n"); } PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.cudaContextManager = cudaContextManager; sceneDesc.staticStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; gScene = gPhysics->createScene(sceneDesc); } static void initParticles(const PxU32 numX, const PxU32 numY, const PxU32 numZ, const PxVec3& position = PxVec3(0, 0, 0), const PxReal particleSpacing = 0.2f, const PxReal fluidDensity = 1000.f) { PxCudaContextManager* cudaContextManager = gScene->getCudaContextManager(); if (cudaContextManager == NULL) return; const PxU32 maxParticles = numX * numY * numZ; gParticleSystem = gPhysics->createPBDParticleSystem(*cudaContextManager, 96); // General particle system setting const PxReal restOffset = 0.5f * particleSpacing / 0.6f; const PxReal solidRestOffset = restOffset; const PxReal fluidRestOffset = restOffset * 0.6f; const PxReal particleMass = fluidDensity * 1.333f * 3.14159f * particleSpacing * particleSpacing * particleSpacing; gParticleSystem->setRestOffset(restOffset); gParticleSystem->setContactOffset(restOffset + 0.01f); gParticleSystem->setParticleContactOffset(PxMax(solidRestOffset + 0.01f, fluidRestOffset / 0.6f)); gParticleSystem->setSolidRestOffset(solidRestOffset); gParticleSystem->setFluidRestOffset(fluidRestOffset); gParticleSystem->enableCCD(false); gScene->addActor(*gParticleSystem); // Create particles and add them to the particle system PxU32* phase = cudaContextManager->allocPinnedHostBuffer<PxU32>(maxParticles); PxVec4* positionInvMass = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); PxVec4* velocity = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); // We are applying different material parameters for each section const PxU32 maxMaterials = 3; PxU32 phases[maxMaterials]; for (PxU32 i = 0; i < maxMaterials; ++i) { PxPBDMaterial* mat = gPhysics->createPBDMaterial(0.05f, i / (maxMaterials - 1.0f), 0.f, 10.002f* (i + 1), 0.5f, 0.005f * i, 0.01f, 0.f, 0.f); phases[i] = gParticleSystem->createPhase(mat, PxParticlePhaseFlags(PxParticlePhaseFlag::eParticlePhaseFluid | PxParticlePhaseFlag::eParticlePhaseSelfCollide)); } PxReal x = position.x; PxReal y = position.y; PxReal z = position.z; for (PxU32 i = 0; i < numX; ++i) { for (PxU32 j = 0; j < numY; ++j) { for (PxU32 k = 0; k < numZ; ++k) { const PxU32 index = i * (numY * numZ) + j * numZ + k; const PxU16 matIndex = (PxU16)(i * maxMaterials / numX); const PxVec4 pos(x, y, z, 1.0f / particleMass); phase[index] = phases[matIndex]; positionInvMass[index] = pos; velocity[index] = PxVec4(0.0f); z += particleSpacing; } z = position.z; y += particleSpacing; } y = position.y; x += particleSpacing; } ExtGpu::PxParticleBufferDesc bufferDesc; bufferDesc.maxParticles = maxParticles; bufferDesc.numActiveParticles = maxParticles; bufferDesc.positions = positionInvMass; bufferDesc.velocities = velocity; bufferDesc.phases = phase; gParticleBuffer = physx::ExtGpu::PxCreateAndPopulateParticleBuffer(bufferDesc, cudaContextManager); gParticleSystem->addParticleBuffer(gParticleBuffer); cudaContextManager->freePinnedHostBuffer(positionInvMass); cudaContextManager->freePinnedHostBuffer(velocity); cudaContextManager->freePinnedHostBuffer(phase); } PxParticleSystem* getParticleSystem() { return gParticleSystem; } PxParticleBuffer* getParticleBuffer() { return gParticleBuffer; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); initScene(); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Setup PBF const PxReal fluidDensity = 1000.0f; initParticles(60, 80, 30, PxVec3(-2.5f, 3.f, -2.5f), 0.1f, fluidDensity); // Setup container gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 1.f, 0.f, 0.f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(1.f, 0.f, 0.f, 6.f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(-1.f, 0.f, 0.f, 6.f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, 1.f, 6.f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, -1.f, 6.f), *gMaterial)); // Setup rigid bodies const PxReal dynamicsDensity = fluidDensity * 0.2f; const PxReal boxSize = 1.0f; const PxReal boxMass = boxSize * boxSize * boxSize * dynamicsDensity; PxShape* shape = gPhysics->createShape(PxBoxGeometry(0.5f * boxSize, 0.5f * boxSize, 0.5f * boxSize), *gMaterial); for (int i = 0; i < 5; ++i) { PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(i - 3.0f, 10, 1))); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, boxMass); gScene->addActor(*body); } shape->release(); } void stepPhysics(bool /*interactive*/) { if (gIsRunning) { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); gScene->fetchResultsParticleSystem(); } } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetPBFFluid done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { switch(toupper(key)) { case 'P': gIsRunning = !gIsRunning; break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbfmultimat/SnippetPBFMultiMatRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "cudamanager/PxCudaContext.h" #include "cudamanager/PxCudaContextManager.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #define CUDA_SUCCESS 0 using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern PxParticleSystem* getParticleSystem(); extern PxParticleBuffer* getParticleBuffer(); namespace { Snippets::Camera* sCamera; PxArray<PxVec4>* sPosBufferH; PxArray<PxVec3>* sPosBuffer3H; PxArray<PxVec4>* sVelBufferH; PxArray<PxU32>* sPhasesH; PxArray<PxVec3>* sColorBuffer3H; void copyVec4ToVec3(PxArray<PxVec3>& vec3s, const PxArray<PxVec4>& vec4s) { for (PxU32 i = 0; i < vec4s.size(); ++i) vec3s[i] = vec4s[i].getXYZ(); } PxU32 getGroup(PxU32 phase) { return phase & PxParticlePhaseFlag::eParticlePhaseGroupMask; } void mapVec4ToColor3(PxArray<PxVec3>& colors, const PxArray<PxVec4>& vec4s, const PxArray<PxU32>& phases) { for (PxU32 i = 0; i < vec4s.size(); ++i) { float mag = vec4s[i].getXYZ().magnitude(); float c = PxMin(0.1f * mag, 1.0f); switch (getGroup(phases[i]) % 6) { case 0: colors[i] = PxVec3(1.0f, c, c); break; case 1: colors[i] = PxVec3(c, 1.0f, c); break; case 2: colors[i] = PxVec3(c, c, 1.0f); break; case 3: colors[i] = PxVec3(c, 1.0f, 1.0f); break; case 4: colors[i] = PxVec3(1.0f, c, 1.0f); break; case 5: colors[i] = PxVec3(1.0f, 1.0f, c); break; default: colors[i] = PxVec3(c, c, c); } } } void onBeforeRenderParticles() { PxParticleSystem* particleSystem = getParticleSystem(); if (particleSystem) { PxParticleBuffer* userBuffer = getParticleBuffer(); PxVec4* positions = userBuffer->getPositionInvMasses(); PxVec4* vels = userBuffer->getVelocities(); PxU32* phases = userBuffer->getPhases(); const PxU32 numParticles = userBuffer->getNbActiveParticles(); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxCudaContextManager* cudaContextManager = scene->getCudaContextManager(); cudaContextManager->acquireContext(); PxCudaContext* cudaContext = cudaContextManager->getCudaContext(); cudaContext->memcpyDtoH(sPosBufferH->begin(), CUdeviceptr(positions), sizeof(PxVec4) * numParticles); cudaContext->memcpyDtoH(sVelBufferH->begin(), CUdeviceptr(vels), sizeof(PxVec4) * numParticles); cudaContext->memcpyDtoH(sPhasesH->begin(), CUdeviceptr(phases), sizeof(PxU32) * numParticles); copyVec4ToVec3(*sPosBuffer3H, *sPosBufferH); mapVec4ToColor3(*sColorBuffer3H, *sVelBufferH, *sPhasesH); cudaContextManager->releaseContext(); } } void renderParticles() { Snippets::DrawPoints(*sPosBuffer3H, *sColorBuffer3H, 2.0f); } void allocParticleBuffers() { PxParticleSystem* particleSystem = getParticleSystem(); //const PxU32 maxParticles = particleSystem->getMaxParticles(); if (particleSystem) { PxParticleBuffer* userBuffer = getParticleBuffer(); const PxU32 maxParticles = userBuffer->getMaxParticles(); sPosBufferH = new PxArray<PxVec4>(maxParticles); sPosBuffer3H = new PxArray<PxVec3>(maxParticles); sVelBufferH = new PxArray<PxVec4>(maxParticles); sColorBuffer3H = new PxArray<PxVec3>(maxParticles); sPhasesH = new PxArray<PxU32>(maxParticles); } } void clearupParticleBuffers() { delete sPosBuffer3H; delete sPosBufferH; delete sVelBufferH; delete sColorBuffer3H; delete sPhasesH; } void renderCallback() { onBeforeRenderParticles(); stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } renderParticles(); Snippets::finishRender(); } void cleanup() { delete sCamera; clearupParticleBuffers(); cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(15.0f, 10.0f, 15.0f), PxVec3(-0.6f,-0.2f,-0.6f)); Snippets::setupDefault("PhysX Snippet PBFFluid", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); allocParticleBuffers(); glutMainLoop(); cleanup(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetquerysystemcustomcompound/SnippetQuerySystemCustomCompoundRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderScene(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); renderScene(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet QuerySystemCustomCompound", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetquerysystemcustomcompound/SnippetQuerySystemCustomCompound.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet demonstrates how to re-implement a 'compound pruner' in // Gu::QuerySystem using PxCustomGeometry objects. // // Please get yourself familiar with SnippetQuerySystemAllQueries first. // // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "GuQuerySystem.h" #include "GuFactory.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; using namespace Gu; #ifdef RENDER_SNIPPET using namespace Snippets; #endif #define MAX_SHAPES_PER_COMPOUND 8 static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static const bool gManualBoundsComputation = false; static const bool gUseDelayedUpdates = true; static const float gBoundsInflation = 0.001f; static bool gPause = false; static bool gOneFrame = false; enum QueryScenario { RAYCAST_CLOSEST, RAYCAST_ANY, RAYCAST_MULTIPLE, SWEEP_CLOSEST, SWEEP_ANY, SWEEP_MULTIPLE, OVERLAP_ANY, OVERLAP_MULTIPLE, NB_SCENES }; static QueryScenario gSceneIndex = RAYCAST_CLOSEST; // Tweak number of created objects per scene static const PxU32 gFactor[NB_SCENES] = { 2, 1, 2, 2, 1, 2, 1, 2 }; // Tweak amplitude of created objects per scene static const float gAmplitude[NB_SCENES] = { 4.0f, 4.0f, 4.0f, 4.0f, 8.0f, 4.0f, 4.0f, 4.0f }; static const PxVec3 gCamPos[NB_SCENES] = { PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-3.404853f, 4.865191f, 17.692263f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), }; static const PxVec3 gCamDir[NB_SCENES] = { PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), }; #define MAX_NB_OBJECTS 32 static void fromLocalToGlobalSpace(PxLocationHit& hit, const PxTransform& pose) { hit.position = pose.transform(hit.position); hit.normal = pose.rotate(hit.normal); } /////////////////////////////////////////////////////////////////////////////// // The following functions determine how we use the pruner payloads in this snippet static PX_FORCE_INLINE void setupPayload(PrunerPayload& payload, PxU32 objectIndex, const PxGeometry* geom) { payload.data[0] = objectIndex; payload.data[1] = size_t(geom); } static PX_FORCE_INLINE PxU32 getObjectIndexFromPayload(const PrunerPayload& payload) { return PxU32(payload.data[0]); } static PX_FORCE_INLINE const PxGeometry& getGeometryFromPayload(const PrunerPayload& payload) { return *reinterpret_cast<const PxGeometry*>(payload.data[1]); } /////////////////////////////////////////////////////////////////////////////// static CachedFuncs gCachedFuncs; namespace { struct CustomRaycastHit : PxGeomRaycastHit { PxU32 mObjectIndex; }; struct CustomSweepHit : PxGeomSweepHit { PxU32 mObjectIndex; }; // We now derive CustomScene from PxCustomGeometry::Callbacks. class CustomScene : public Adapter, public PxCustomGeometry::Callbacks { public: CustomScene(); ~CustomScene() {} // Adapter virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const; //~Adapter void release(); void addCompound(const PxTransform& pose, bool isDynamic); void render(); void updateObjects(); void runQueries(); bool raycastClosest(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomRaycastHit& hit) const; bool raycastAny(const PxVec3& origin, const PxVec3& unitDir, float maxDist) const; bool raycastMultiple(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxArray<CustomRaycastHit>& hits) const; bool sweepClosest(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, CustomSweepHit& hit) const; bool sweepAny(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) const; bool sweepMultiple(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, PxArray<CustomSweepHit>& hits) const; bool overlapAny(const PxGeometry& geom, const PxTransform& pose) const; bool overlapMultiple(const PxGeometry& geom, const PxTransform& pose, PxArray<PxU32>& hits) const; // We derive our objects from PxCustomGeometry, to get easy access to the data in the PxCustomGeometry::Callbacks // functions. This generally wouldn't work in the regular PxScene / PhysX code since the geometries are copied around and the // system doesn't know about potential user-data surrounding the PxCustomGeometry objects. But the Gu::QuerySystem only // passes PxGeometry pointers around so it works here. // A more traditional usage of PxCustomGeometry would be to derive our Object from PxCustomGeometry::Callbacks (see e.g. // SnippetCustomConvex). Both approaches would work here. struct Object : public PxCustomGeometry { // Shape-related data // In this simple snippet we just keep all shapes in linear C-style arrays. A more efficient version could use a PxBVH here. PxBounds3 mCompoundLocalBounds; PxGeometryHolder mShapeGeoms[MAX_SHAPES_PER_COMPOUND]; PxTransform mLocalPoses[MAX_SHAPES_PER_COMPOUND]; PxU32 mNbShapes; // Compound/actor data. Note how mData is Gu::QuerySystem handle for the compound. We don't have // ActorShapeData values for each sub-shape, the Gu::QuerySystem doesn't know about these. ActorShapeData mData; PxVec3 mTouchedColor; bool mTouched; }; PxU32 mNbObjects; Object mObjects[MAX_NB_OBJECTS]; QuerySystem* mQuerySystem; PxU32 mPrunerIndex; DECLARE_CUSTOM_GEOMETRY_TYPE // PxCustomGeometry::Callbacks virtual PxBounds3 getLocalBounds(const PxGeometry& geom) const { // In this snippet we only fill the QuerySystem with our PxCustomGeometry-based objects. In a more complex app // we could have to test the type and cast to the appropriate type if needed. PX_ASSERT(geom.getType()==PxGeometryType::eCUSTOM); // Because our internal Objects are derived from custom geometries we have easy access to mCompoundLocalBounds: const Object& obj = static_cast<const Object&>(geom); return obj.mCompoundLocalBounds; } virtual bool generateContacts(const PxGeometry&, const PxGeometry&, const PxTransform&, const PxTransform&, const PxReal, const PxReal, const PxReal, PxContactBuffer&) const { // This is for contact generation, we don't use that here. return false; } virtual PxU32 raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& geom, const PxTransform& pose, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* rayHits, PxU32 stride, PxRaycastThreadContext* context) const { // There are many ways to implement this callback. This is just one example. // We retrieve our object, same as in "getLocalBounds" above. PX_ASSERT(geom.getType()==PxGeometryType::eCUSTOM); const Object& obj = static_cast<const Object&>(geom); // From the point-of-view of the QuerySystem a custom geometry is a single object, but from the point-of-view // of the user it can be anything, including a sub-scene (or as in this snippet, a compound). // The old API flags must be adapted to this new scenario, and we need to re-interpret what they all mean. // As discussed in SnippetQuerySystemAllQueries we don't use PxHitFlag::eMESH_MULTIPLE in the snippets, i.e. // from the point-of-view of the Gu::QuerySystem this raycast function against a unique (custom) geometry // should not return multiple hits. And indeed, "maxHits" is always 1 here. PX_UNUSED(stride); PX_UNUSED(maxHits); PX_ASSERT(maxHits==1); // The new flag PxHitFlag::eANY_HIT tells the system to report any hit from any geometry that contains more // than one primitive. This is equivalent to the old PxHitFlag::eMESH_ANY flag, but this is now also applicable // to PxCustomGeometry objects, not just triangle meshes. const bool anyHit = hitFlags & PxHitFlag::eANY_HIT; // We derive the object's index from the object's pointer. This is the counterpart of 'getObjectIndexFromPayload' // for regular geometries. We don't have a payload here since our sub-shapes are part of our compound // and hidden from the Gu::QuerySystem. Note that this is only used to highlight touched objects in the // render code, so this is all custom for this snippet and not mandatory in any way. const PxU32 objectIndex = PxU32(&obj - mObjects); // The ray is in world space, but the compound's shapes are in local space. We transform the ray from world space // to the compound's local space to do the raycast queries against these sub-shapes. const PxVec3 localOrigin = pose.transformInv(origin); const PxVec3 localDir = pose.q.rotateInv(unitDir); PxGeomRaycastHit localHit; PxGeomRaycastHit bestLocalHit; bestLocalHit.distance = maxDist; bool hasLocalHit = false; for(PxU32 i=0;i<obj.mNbShapes;i++) { // We need to replicate for our compound/sub-scene what was done in the calling code for a regular leaf node. // In particular that leaf code called 'validatePayload' (implemented later in the snippet) to retrieve the // geometry from a payload. We don't need to do that here since we have direct access to the geometries. // However we would still need to implement a preFilter function if needed, to replicate the second part of // 'validatePayload'. We aren't using a preFilter in this snippet though so this is missing here. const PxGeometry& currentGeom = obj.mShapeGeoms[i].any(); const PxTransform& currentPose = obj.mLocalPoses[i]; // We now raycast() against a sub-shape. Note how we only ask for one hit here, because eMESH_MULTIPLE was // not used in the snippet. We could call PxGeometryQuery::raycast here but it is more efficient to go through // the Gu-level function pointers directly, since it bypasses the PX_SIMD_GUARD entirely. We added one of these // when the query started (in CustomScene::runQueries()) so we can ignore them all in subsequent raycast calls. const RaycastFunc func = gCachedFuncs.mCachedRaycastFuncs[currentGeom.getType()]; const PxU32 nbHits = func(currentGeom, currentPose, localOrigin, localDir, bestLocalHit.distance, hitFlags, 1, &localHit, sizeof(PxGeomRaycastHit), context); if(nbHits && localHit.distance<bestLocalHit.distance) { // We detected a valid hit. To simplify the code we decided to reuse the 'reportHits' function from our // own pruner raycast callback, which are passed to us by the query system as the context parameter. These // are the callbacks passed to 'mQuerySystem->raycast' later in this snippet. Specifically they will be // either DefaultPrunerRaycastClosestCallback, DefaultPrunerRaycastAnyCallback, or our own // CustomRaycastMultipleCallback objects. All of them are DefaultPrunerRaycastCallback. PX_ASSERT(context); DefaultPrunerRaycastCallback* raycastCB = static_cast<DefaultPrunerRaycastCallback*>(context); // We moved the ray to the compound's local space so the hit is in this local compound space. We // need to transform the data back into world space. We cannot immediately tell in which raycast mode we are so // we do this conversion immediately. This is a bit less efficient than what we did in SnippetQuerySystemAllQueries, // where that conversion was delayed in the raycastClosest / raycastAny modes. We could be more efficient here // as well but it would make the code more complicated. fromLocalToGlobalSpace(localHit, pose); // We need a payload to call the 'reportHits' function so we create an artificial one here: PrunerPayload payload; setupPayload(payload, objectIndex, &currentGeom); // Reusing the reportHits function is mainly an easy way for us to report multiple hits from here. As // we mentioned above 'maxHits' is 1 and we cannot write out multiple hits to the 'rayHits' buffer, so // this is one alternative. In the 'multiple hits' codepath our own reportHits function will return false. // In that case we don't touch 'hasLocalHit' and we don't update 'bestLocalHit', so the code will use the same // (non shrunk) distance for next raycast calls in this loop, and we will return 0 from the query in // the end. The calling code doesn't need to know that we kept all the hits: we tell it that we // didn't find hits and it doesn't have to do any further processing. if(raycastCB->reportHits(payload, 1, &localHit)) { // This is the single-hit codepath. We still need to know if we're coming from 'raycastAny' or from // 'raycastClosest'. if(anyHit) { // In 'raycastAny' mode we just write out the current hit and early exit. *rayHits = localHit; return 1; } // Otherwise in 'raycastClosest' mode we update the best hit, which will shrink the current distance, // and go on. We delay writing out the best hit (we don't have it yet). bestLocalHit = localHit; hasLocalHit = true; } } } // Last part of 'raycastClosest' mode, process best hit. if(hasLocalHit) { // In SnippetQuerySystemAllQueries this is where we'd convert the best hit back to world-space. In this // snippet we already did that above, so we only need to write out the best hit. *rayHits = bestLocalHit; } return hasLocalHit ? 1 : 0; } virtual bool overlap(const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext* context) const { // Bits similar to what we covered in the raycast callback above are not commented anymore here. PX_ASSERT(geom0.getType()==PxGeometryType::eCUSTOM); const Object& obj = static_cast<const Object&>(geom0); const PxU32 objectIndex = PxU32(&obj - mObjects); // This is the geom we passed to the OVERLAP_ANY / OVERLAP_MULTIPLE codepaths later in this snippet, i.e. // this is our own query volume. const PxGeometry& queryGeom = geom1; // Similar to what we did for the ray in the raycast callback, we need to convert the world-space query volume to our // compound's local space. Note our we convert the whole PxTransform here, not just the position (contrary to what we // did for raycasts). const PxTransform queryLocalPose(pose0.transformInv(pose1)); for(PxU32 i=0;i<obj.mNbShapes;i++) { const PxGeometry& currentGeom = obj.mShapeGeoms[i].any(); const PxTransform& currentPose = obj.mLocalPoses[i]; if(Gu::overlap(queryGeom, queryLocalPose, currentGeom, currentPose, gCachedFuncs.mCachedOverlapFuncs, context)) { PrunerPayload payload; setupPayload(payload, objectIndex, &currentGeom); // We use the same approach as for the raycast callback above. This time the context will be // either CustomOverlapAnyCallback or CustomOverlapMultipleCallback. Either way they are // DefaultPrunerOverlapCallback objects. PX_ASSERT(context); DefaultPrunerOverlapCallback* overlapCB = static_cast<DefaultPrunerOverlapCallback*>(context); // The 'overlapAny' case will return false, in which case we don't need to go through the // remaining sub-shapes. if(!overlapCB->reportHit(payload)) return true; } } return false; } virtual bool sweep(const PxVec3& unitDir, const PxReal maxDist, const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxReal inflation, PxSweepThreadContext* context) const { // Sweeps are a combination of raycast (for the unitDir / maxDist parameters) and overlaps (for the // query-volume-related parameters). Bits already covered in the raycast and overlap callbacks above // will not be commented again here. PX_UNUSED(inflation); PX_ASSERT(geom0.getType()==PxGeometryType::eCUSTOM); const Object& obj = static_cast<const Object&>(geom0); const PxU32 objectIndex = PxU32(&obj - mObjects); const bool anyHit = hitFlags & PxHitFlag::eANY_HIT; // Bit subtle here: the internal system converts swept spheres to swept capsules (there is no internal // codepath for spheres to make the code smaller). So if we use a PxSphereGeometry in the SWEEP_CLOSEST // SWEEP_ANY / SWEEP_MULTIPLE codepaths later in this snippet, we actually receive it as a PxCapsuleGeometry // whose halfHeight = 0 here. This is not important in this snippet because we will use PxGeometryQuery::sweep // below, but it would be important if we'd decide to use the cached Gu-level functions (like we did for raycasts // and overlaps). const PxGeometry& queryGeom = geom1; // Convert both the query volume & ray to local space. const PxTransform queryLocalPose(pose0.transformInv(pose1)); const PxVec3 localDir = pose0.q.rotateInv(unitDir); PxGeomSweepHit localHit; PxGeomSweepHit bestLocalHit; bestLocalHit.distance = maxDist; bool hasLocalHit = false; for(PxU32 i=0;i<obj.mNbShapes;i++) { const PxGeometry& currentGeom = obj.mShapeGeoms[i].any(); const PxTransform& currentPose = obj.mLocalPoses[i]; // Bit subtle here: we don't want to replicate the whole PxGeometryQuery::sweep() function directly // here so contrary to what we previously did, we do not use the gCachedFuncs sweep pointers directly. // We can still pass PxGeometryQueryFlag::Enum(0) to the system to tell it we already took care of the // SIMD guards. This optimization is not as important for sweeps as it was for raycasts, because the // sweeps themselves are generally much more expensive than raycasts, so the relative cost of the SIMD // guard is not as high. const PxU32 retVal = PxGeometryQuery::sweep(localDir, bestLocalHit.distance, queryGeom, queryLocalPose, currentGeom, currentPose, localHit, hitFlags, 0.0f, PxGeometryQueryFlag::Enum(0), context); if(retVal && localHit.distance<bestLocalHit.distance) { fromLocalToGlobalSpace(localHit, pose0); PrunerPayload payload; setupPayload(payload, objectIndex, &currentGeom); // Same approach as before, this time involving our own sweep callbacks. PX_ASSERT(context); DefaultPrunerSweepCallback* sweepCB = static_cast<DefaultPrunerSweepCallback*>(context); if(sweepCB->reportHit(payload, localHit)) { if(anyHit) { sweepHit = localHit; return 1; } bestLocalHit = localHit; hasLocalHit = true; } } } if(hasLocalHit) { sweepHit = bestLocalHit; } return hasLocalHit ? 1 : 0; } virtual void visualize(const PxGeometry&, PxRenderOutput&, const PxTransform&, const PxBounds3&) const { } virtual void computeMassProperties(const PxGeometry&, PxMassProperties&) const { } virtual bool usePersistentContactManifold(const PxGeometry&, PxReal&) const { return false; } //~PxCustomGeometry::Callbacks }; IMPLEMENT_CUSTOM_GEOMETRY_TYPE(CustomScene) const PxGeometry& CustomScene::getGeometry(const PrunerPayload& payload) const { PX_ASSERT(!gManualBoundsComputation); return getGeometryFromPayload(payload); } void CustomScene::release() { PX_DELETE(mQuerySystem); PX_DELETE_THIS; } CustomScene::CustomScene() : mNbObjects(0) { const PxU64 contextID = PxU64(this); mQuerySystem = PX_NEW(QuerySystem)(contextID, gBoundsInflation, *this); Pruner* pruner = createAABBPruner(contextID, true, COMPANION_PRUNER_INCREMENTAL, BVH_SPLATTER_POINTS, 4); mPrunerIndex = mQuerySystem->addPruner(pruner, 0); const PxU32 nb = gFactor[gSceneIndex]; for(PxU32 i=0;i<nb;i++) { addCompound(PxTransform(PxVec3(0.0f, 0.0f, 0.0f)), true); } #ifdef RENDER_SNIPPET Camera* camera = getCamera(); camera->setPose(gCamPos[gSceneIndex], gCamDir[gSceneIndex]); #endif } void CustomScene::addCompound(const PxTransform& pose, bool isDynamic) { PX_ASSERT(mQuerySystem); Object& obj = mObjects[mNbObjects]; obj.callbacks = this; PrunerPayload payload; setupPayload(payload, mNbObjects, static_cast<const PxCustomGeometry*>(&obj)); { const PxBoxGeometry boxGeom(PxVec3(1.0f, 2.0f, 0.5f)); const PxTransform boxGeomPose(PxVec3(0.0f, 0.0f, 0.0f)); const PxSphereGeometry sphereGeom(1.5f); const PxTransform sphereGeomPose(PxVec3(3.0f, 0.0f, 0.0f)); const PxCapsuleGeometry capsuleGeom(1.0f, 1.0f); const PxTransform capsuleGeomPose(PxVec3(-3.0f, 0.0f, 0.0f)); const PxConvexMeshGeometry convexGeom(gConvexMesh); const PxTransform convexGeomPose(PxVec3(0.0f, 0.0f, 3.0f)); const PxTriangleMeshGeometry meshGeom(gTriangleMesh); const PxTransform meshGeomPose(PxVec3(0.0f, 0.0f, -3.0f)); obj.mShapeGeoms[0].storeAny(boxGeom); obj.mShapeGeoms[1].storeAny(sphereGeom); obj.mShapeGeoms[2].storeAny(capsuleGeom); obj.mShapeGeoms[3].storeAny(convexGeom); obj.mShapeGeoms[4].storeAny(meshGeom); obj.mLocalPoses[0] = boxGeomPose; obj.mLocalPoses[1] = sphereGeomPose; obj.mLocalPoses[2] = capsuleGeomPose; obj.mLocalPoses[3] = convexGeomPose; obj.mLocalPoses[4] = meshGeomPose; obj.mNbShapes = 5; // Precompute local bounds for our compound PxBounds3 localCompoundBounds = PxBounds3::empty(); for(PxU32 i=0;i<obj.mNbShapes;i++) { PxBounds3 localShapeBounds; PxGeometryQuery::computeGeomBounds(localShapeBounds, obj.mShapeGeoms[i].any(), obj.mLocalPoses[i]); localCompoundBounds.include(localShapeBounds); } obj.mCompoundLocalBounds = localCompoundBounds; } if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, obj, pose, 0.0f, 1.0f + gBoundsInflation); obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, &bounds); } else { obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, NULL); } mNbObjects++; } void CustomScene::updateObjects() { if(!mQuerySystem) return; if(gPause && !gOneFrame) { mQuerySystem->update(true, true); return; } gOneFrame = false; static float time = 0.0f; time += 0.005f; const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; if(!getDynamic(getPrunerInfo(obj.mData))) continue; // const float coeff = float(i)/float(nbObjects); const float coeff = float(i); const float amplitude = gAmplitude[gSceneIndex]; // Compute an arbitrary new pose for this object PxTransform pose; { const float phase = PxPi * 2.0f * float(i)/float(nbObjects); pose.p.z = 0.0f; pose.p.y = sinf(phase+time*1.17f)*amplitude; pose.p.x = cosf(phase+time*1.17f)*amplitude; PxMat33 rotX; PxSetRotX(rotX, time+coeff); PxMat33 rotY; PxSetRotY(rotY, time*1.17f+coeff); PxMat33 rotZ; PxSetRotZ(rotZ, time*0.33f+coeff); PxMat33 rot = rotX * rotY * rotZ; pose.q = PxQuat(rot); pose.q.normalize(); } if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, obj, pose, 0.0f, 1.0f + gBoundsInflation); mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, &bounds); } else { mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, NULL); } } mQuerySystem->update(true, true); } namespace { struct CustomPrunerFilterCallback : public PrunerFilterCallback { virtual const PxGeometry* validatePayload(const PrunerPayload& payload, PxHitFlags& /*hitFlags*/) { return &getGeometryFromPayload(payload); } }; } static CustomPrunerFilterCallback gFilterCallback; /////////////////////////////////////////////////////////////////////////////// bool CustomScene::raycastClosest(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomRaycastHit& hit) const { DefaultPrunerRaycastClosestCallback CB(gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist, PxHitFlag::eDEFAULT); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); if(CB.mFoundHit) { static_cast<PxGeomRaycastHit&>(hit) = CB.mClosestHit; hit.mObjectIndex = getObjectIndexFromPayload(CB.mClosestPayload); } return CB.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// bool CustomScene::raycastAny(const PxVec3& origin, const PxVec3& unitDir, float maxDist) const { DefaultPrunerRaycastAnyCallback CB(gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); return CB.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomRaycastMultipleCallback : public DefaultPrunerRaycastCallback { PxGeomRaycastHit mLocalHit; PxArray<CustomRaycastHit>& mHits; CustomRaycastMultipleCallback(PxArray<CustomRaycastHit>& hits, PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance) : DefaultPrunerRaycastCallback(filterCB, funcs, origin, dir, distance, 1, &mLocalHit, PxHitFlag::eDEFAULT, false), mHits (hits) {} virtual bool reportHits(const PrunerPayload& payload, PxU32 nbHits, PxGeomRaycastHit* hits) { PX_ASSERT(nbHits==1); PX_UNUSED(nbHits); CustomRaycastHit customHit; static_cast<PxGeomRaycastHit&>(customHit) = hits[0]; customHit.mObjectIndex = getObjectIndexFromPayload(payload); mHits.pushBack(customHit); return false; } PX_NOCOPY(CustomRaycastMultipleCallback) }; } bool CustomScene::raycastMultiple(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxArray<CustomRaycastHit>& hits) const { CustomRaycastMultipleCallback CB(hits, gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); return hits.size()!=0; } /////////////////////////////////////////////////////////////////////////////// namespace { template<class CallbackT> static bool _sweepClosestT(CustomSweepHit& hit, const CustomScene& cs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CallbackT pcb(gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist, PxHitFlag::eDEFAULT | PxHitFlag::ePRECISE_SWEEP, false); cs.mQuerySystem->sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); if(pcb.mFoundHit) { static_cast<PxGeomSweepHit&>(hit) = pcb.mClosestHit; hit.mObjectIndex = getObjectIndexFromPayload(pcb.mClosestPayload); } return pcb.mFoundHit; } } bool CustomScene::sweepClosest(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, CustomSweepHit& hit) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepClosestT<DefaultPrunerSphereSweepCallback>(hit, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepClosestT<DefaultPrunerCapsuleSweepCallback>(hit, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepClosestT<DefaultPrunerBoxSweepCallback>(hit, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepClosestT<DefaultPrunerConvexSweepCallback>(hit, *this, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { template<class CallbackT> static bool _sweepAnyT(const CustomScene& cs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CallbackT pcb(gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist, PxHitFlag::eANY_HIT | PxHitFlag::ePRECISE_SWEEP, true); cs.mQuerySystem->sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); return pcb.mFoundHit; } } bool CustomScene::sweepAny(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepAnyT<DefaultPrunerSphereSweepCallback>(*this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepAnyT<DefaultPrunerCapsuleSweepCallback>(*this, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepAnyT<DefaultPrunerBoxSweepCallback>(*this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepAnyT<DefaultPrunerConvexSweepCallback>(*this, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { template<class BaseCallbackT> struct CustomSweepMultipleCallback : public BaseCallbackT { PxArray<CustomSweepHit>& mHits; CustomSweepMultipleCallback(PxArray<CustomSweepHit>& hits, PrunerFilterCallback& filterCB, const GeomSweepFuncs& funcs, const PxGeometry& geom, const PxTransform& pose, const ShapeData& queryVolume, const PxVec3& dir, float distance) : BaseCallbackT (filterCB, funcs, geom, pose, queryVolume, dir, distance, PxHitFlag::eDEFAULT|PxHitFlag::ePRECISE_SWEEP, false), mHits (hits) {} virtual bool reportHit(const PrunerPayload& payload, PxGeomSweepHit& hit) { CustomSweepHit customHit; static_cast<PxGeomSweepHit&>(customHit) = hit; customHit.mObjectIndex = getObjectIndexFromPayload(payload); mHits.pushBack(customHit); return false; } PX_NOCOPY(CustomSweepMultipleCallback) }; template<class CallbackT> static bool _sweepMultipleT(PxArray<CustomSweepHit>& hits, const CustomScene& cs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CustomSweepMultipleCallback<CallbackT> pcb(hits, gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist); cs.mQuerySystem->sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); return hits.size()!=0; } } bool CustomScene::sweepMultiple(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, PxArray<CustomSweepHit>& hits) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepMultipleT<DefaultPrunerSphereSweepCallback>(hits, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepMultipleT<DefaultPrunerCapsuleSweepCallback>(hits, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepMultipleT<DefaultPrunerBoxSweepCallback>(hits, *this, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepMultipleT<DefaultPrunerConvexSweepCallback>(hits, *this, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomOverlapAnyCallback : public DefaultPrunerOverlapCallback { bool mFoundHit; CustomOverlapAnyCallback(PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose) : DefaultPrunerOverlapCallback(filterCB, funcs, geometry, pose), mFoundHit(false) {} virtual bool reportHit(const PrunerPayload& /*payload*/) { mFoundHit = true; return false; } }; } bool CustomScene::overlapAny(const PxGeometry& geom, const PxTransform& pose) const { CustomOverlapAnyCallback pcb(gFilterCallback, gCachedFuncs.mCachedOverlapFuncs, geom, pose); const ShapeData queryVolume(geom, pose, 0.0f); mQuerySystem->overlap(queryVolume, pcb, NULL); return pcb.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomOverlapMultipleCallback : public DefaultPrunerOverlapCallback { PxArray<PxU32>& mHits; CustomOverlapMultipleCallback(PxArray<PxU32>& hits, PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose) : DefaultPrunerOverlapCallback(filterCB, funcs, geometry, pose), mHits(hits) {} virtual bool reportHit(const PrunerPayload& payload) { mHits.pushBack(getObjectIndexFromPayload(payload)); return true; } PX_NOCOPY(CustomOverlapMultipleCallback) }; } bool CustomScene::overlapMultiple(const PxGeometry& geom, const PxTransform& pose, PxArray<PxU32>& hits) const { CustomOverlapMultipleCallback pcb(hits, gFilterCallback, gCachedFuncs.mCachedOverlapFuncs, geom, pose); const ShapeData queryVolume(geom, pose, 0.0f); mQuerySystem->overlap(queryVolume, pcb, NULL); return hits.size()!=0; } /////////////////////////////////////////////////////////////////////////////// void CustomScene::runQueries() { if(!mQuerySystem) return; const PxVec3 touchedColor(0.25f, 0.5f, 1.0f); for(PxU32 i=0;i<mNbObjects;i++) { mObjects[i].mTouched = false; mObjects[i].mTouchedColor = touchedColor; } PX_SIMD_GUARD if(0) mQuerySystem->commitUpdates(); switch(gSceneIndex) { case RAYCAST_CLOSEST: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; CustomRaycastHit hit; const bool hasHit = raycastClosest(origin, unitDir, maxDist, hit); #ifdef RENDER_SNIPPET if(hasHit) { DrawLine(origin, hit.position, PxVec3(1.0f)); DrawLine(hit.position, hit.position + hit.normal, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 0.5f); mObjects[hit.mObjectIndex].mTouched = true; } else { DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case RAYCAST_ANY: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const bool hasHit = raycastAny(origin, unitDir, maxDist); #ifdef RENDER_SNIPPET if(hasHit) DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f, 0.0f, 0.0f)); else DrawLine(origin, origin + unitDir * maxDist, PxVec3(0.0f, 1.0f, 0.0f)); #else PX_UNUSED(hasHit); #endif } break; case RAYCAST_MULTIPLE: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; PxArray<CustomRaycastHit> hits; const bool hasHit = raycastMultiple(origin, unitDir, maxDist, hits); #ifdef RENDER_SNIPPET if(hasHit) { DrawLine(origin, origin + unitDir * maxDist, PxVec3(0.5f)); const PxU32 nbHits = hits.size(); for(PxU32 i=0;i<nbHits;i++) { const CustomRaycastHit& hit = hits[i]; DrawLine(hit.position, hit.position + hit.normal, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 0.5f); mObjects[hit.mObjectIndex].mTouched = true; } } else { DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_CLOSEST: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; //const PxSphereGeometry sweptGeom(0.5f); const PxCapsuleGeometry sweptGeom(0.5f, 0.5f); const PxTransform pose(origin); CustomSweepHit hit; const bool hasHit = sweepClosest(sweptGeom, pose, unitDir, maxDist, hit); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); if(hasHit) { const PxVec3 sweptPos = origin + unitDir * hit.distance; DrawLine(origin, sweptPos, PxVec3(1.0f)); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, PxVec3(1.0f, 0.0f, 0.0f)); DrawLine(hit.position, hit.position + hit.normal*2.0f, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 2.0f); mObjects[hit.mObjectIndex].mTouched = true; } else { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(1.0f)); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, PxVec3(0.0f, 1.0f, 0.0f)); } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_ANY: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const PxBoxGeometry sweptGeom(PxVec3(0.5f)); //const PxSphereGeometry sweptGeom(0.5f); PxQuat q(1.1f, 0.1f, 0.8f, 1.4f); q.normalize(); const PxTransform pose(origin, q); const bool hasHit = sweepAny(sweptGeom, pose, unitDir, maxDist); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); const PxU32 nb = 20; for(PxU32 i=0;i<nb;i++) { const float coeff = float(i)/float(nb-1); const PxVec3 sweptPos = origin + unitDir * coeff * maxDist; const PxTransform impactPose(sweptPos, q); renderGeoms(1, &gh, &impactPose, false, color); } } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_MULTIPLE: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; // const PxCapsuleGeometry sweptGeom(0.5f, 0.5f); const PxSphereGeometry sweptGeom(0.5f); const PxTransform pose(origin); PxArray<CustomSweepHit> hits; const bool hasHit = sweepMultiple(sweptGeom, pose, unitDir, maxDist, hits); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); if(hasHit) { { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(0.5f)); } const PxVec3 touchedColors[] = { PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f), PxVec3(1.0f, 0.0f, 1.0f), PxVec3(0.0f, 1.0f, 1.0f), PxVec3(1.0f, 1.0f, 0.0f), PxVec3(1.0f, 1.0f, 1.0f), PxVec3(0.5f, 0.5f, 0.5f), }; const PxU32 nbHits = hits.size(); for(PxU32 i=0;i<nbHits;i++) { const PxVec3& shapeTouchedColor = touchedColors[i]; const CustomSweepHit& hit = hits[i]; const PxVec3 sweptPos = origin + unitDir * hit.distance; const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, shapeTouchedColor); DrawLine(hit.position, hit.position + hit.normal*2.0f, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 2.0f); mObjects[hit.mObjectIndex].mTouched = true; mObjects[hit.mObjectIndex].mTouchedColor = shapeTouchedColor; } } else { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case OVERLAP_ANY: { const PxVec3 origin(0.0f, 4.0f, 0.0f); //const PxSphereGeometry queryGeom(0.5f); //const PxCapsuleGeometry queryGeom(0.5f, 0.5f); const PxBoxGeometry queryGeom(1.0f, 0.25f, 0.5f); const PxTransform pose(origin); const bool hasHit = overlapAny(queryGeom, pose); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(queryGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); renderGeoms(1, &gh, &pose, false, color); } #else PX_UNUSED(hasHit); #endif } break; case OVERLAP_MULTIPLE: { const PxVec3 origin(0.0f, 4.0f, 0.0f); // const PxSphereGeometry queryGeom(0.5f); const PxCapsuleGeometry queryGeom(0.5f, 0.5f); const PxTransform pose(origin); PxArray<PxU32> hits; const bool hasHit = overlapMultiple(queryGeom, pose, hits); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(queryGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); renderGeoms(1, &gh, &pose, false, color); for(PxU32 i=0;i<hits.size();i++) mObjects[hits[i]].mTouched = true; } #else PX_UNUSED(hasHit); #endif } break; case NB_SCENES: // Blame pedantic compilers { } break; } } void CustomScene::render() { updateObjects(); runQueries(); #ifdef RENDER_SNIPPET const PxVec3 color(1.0f, 0.5f, 0.25f); const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; PrunerPayloadData ppd; mQuerySystem->getPayloadData(obj.mData, &ppd); //DrawBounds(*ppd.mBounds); const PxVec3& objectColor = obj.mTouched ? obj.mTouchedColor : color; // renderGeoms doesn't support PxCustomGeometry so we deal with this here: PxTransform shapeGlobalPoses[MAX_SHAPES_PER_COMPOUND]; for(PxU32 j=0;j<obj.mNbShapes;j++) { // This is basically PxShapeExt::getGlobalPose with the actor's global pose == *ppd.mTransform shapeGlobalPoses[j] = (*ppd.mTransform) * obj.mLocalPoses[j]; } renderGeoms(obj.mNbShapes, obj.mShapeGeoms, shapeGlobalPoses, false, objectColor); } //mQuerySystem->visualize(true, true, PxRenderOutput) #endif } } static CustomScene* gScene = NULL; void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; { { const PxF32 width = 3.0f; const PxF32 radius = 1.0f; PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } PxConvexMeshDesc convexDesc; convexDesc.points.count = 32; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = points; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; gConvexMesh = PxCreateConvexMesh(params, convexDesc); } { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } } gScene = new CustomScene; } void renderScene() { if(gScene) gScene->render(); #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F8 to select a scenario."); switch(PxU32(gSceneIndex)) { case RAYCAST_CLOSEST: { Snippets::print("Current scenario: raycast closest"); }break; case RAYCAST_ANY: { Snippets::print("Current scenario: raycast any"); }break; case RAYCAST_MULTIPLE: { Snippets::print("Current scenario: raycast multiple"); }break; case SWEEP_CLOSEST: { Snippets::print("Current scenario: sweep closest"); }break; case SWEEP_ANY: { Snippets::print("Current scenario: sweep any"); }break; case SWEEP_MULTIPLE: { Snippets::print("Current scenario: sweep multiple"); }break; case OVERLAP_ANY: { Snippets::print("Current scenario: overlap any"); }break; case OVERLAP_MULTIPLE: { Snippets::print("Current scenario: overlap multiple"); }break; } #endif } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetQuerySystemCustomCompound done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(gScene) { if(key=='p' || key=='P') { gPause = !gPause; } else if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } else { if(key>=1 && key<=NB_SCENES) { gSceneIndex = QueryScenario(key-1); PX_RELEASE(gScene); gScene = new CustomScene; } } } } int snippetMain(int, const char*const*) { printf("Query System Custom Compound snippet.\n"); printf("Press F1 to F8 to select a scene:\n"); printf(" F1......raycast closest\n"); printf(" F2..........raycast any\n"); printf(" F3.....raycast multiple\n"); printf(" F4........sweep closest\n"); printf(" F5............sweep any\n"); printf(" F6.......sweep multiple\n"); printf(" F7..........overlap any\n"); printf(" F8.....overlap multiple\n"); printf("\n"); printf("Press P to Pause.\n"); printf("Press O to step the simulation One frame.\n"); printf("Press the cursor keys to move the camera.\n"); printf("Use the mouse/left mouse button to rotate the camera.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/SnippetVehicleRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern bool initPhysics(); extern void stepPhysics(); extern void cleanupPhysics(); extern PxScene* gScene; namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(); Snippets::startRender(sCamera); PxU32 nbActors = gScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); gScene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(10.0f, 10.0f, 10.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet Vehicle2", sCamera, NULL, renderCallback, exitCallback); if (initPhysics()) { glutMainLoop(); } } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/SnippetVehicleHelpers.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PxPhysicsAPI.h" namespace snippetvehicle2 { physx::PxFilterFlags VehicleFilterShader( physx::PxFilterObjectAttributes attributes0, physx::PxFilterData filterData0, physx::PxFilterObjectAttributes attributes1, physx::PxFilterData filterData1, physx::PxPairFlags& pairFlags, const void* constantBlock, physx::PxU32 constantBlockSize); bool parseVehicleDataPath(int argc, const char *const* argv, const char* snippetName, const char*& vehicleDataPath); }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/SnippetVehicleHelpers.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include <ctype.h> #include "../snippetvehicle2common/SnippetVehicleHelpers.h" using namespace physx; namespace snippetvehicle2 { PxFilterFlags VehicleFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(filterData0); PX_UNUSED(attributes1); PX_UNUSED(filterData1); PX_UNUSED(pairFlags); PX_UNUSED(constantBlock); PX_UNUSED(constantBlockSize); return PxFilterFlag::eSUPPRESS; } bool parseVehicleDataPath(int argc, const char *const* argv, const char* snippetName, const char*& vehicleDataPath) { if (argc != 2 || 0 != strncmp(argv[1], "--vehicleDataPath", strlen("--vehicleDataPath"))) { printf("%s usage:\n" "%s " "--vehicleDataPath=<path to the [PHYSX_ROOT]/snippets/media/vehicledata folder containing the vehiclejson files to be loaded> \n", snippetName, snippetName); return false; } vehicleDataPath = argv[1] + strlen("--vehicleDataPath="); return true; } }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/base/Base.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "Base.h" namespace snippetvehicle2 { BaseVehicleParams BaseVehicleParams::transformAndScale (const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const { BaseVehicleParams r = *this; r.axleDescription = axleDescription; r.frame = trgFrame; r.scale = trgScale; r.suspensionStateCalculationParams = suspensionStateCalculationParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.brakeResponseParams[0] = brakeResponseParams[0].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.brakeResponseParams[1] = brakeResponseParams[1].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.steerResponseParams = steerResponseParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.ackermannParams[0] = ackermannParams[0].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); for (PxU32 i = 0; i < r.axleDescription.nbWheels; i++) { const PxU32 wheelId = r.axleDescription.wheelIdsInAxleOrder[i]; r.suspensionParams[wheelId] = suspensionParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.suspensionComplianceParams[wheelId] = suspensionComplianceParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.suspensionForceParams[wheelId] = suspensionForceParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.tireForceParams[wheelId] = tireForceParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.wheelParams[wheelId] = wheelParams[wheelId].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); } r.rigidBodyParams = rigidBodyParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); return r; } bool BaseVehicle::initialize() { if (!mBaseParams.isValid()) return false; //Set the base state to default. mBaseState.setToDefault(); return true; } void BaseVehicle::step(const PxReal dt, const PxVehicleSimulationContext& context) { mComponentSequence.update(dt, context); } }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/base/Base.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct BaseVehicleParams { PxVehicleAxleDescription axleDescription; PxVehicleFrame frame; PxVehicleScale scale; PxVehicleSuspensionStateCalculationParams suspensionStateCalculationParams; //Command response PxVehicleBrakeCommandResponseParams brakeResponseParams[2]; PxVehicleSteerCommandResponseParams steerResponseParams; PxVehicleAckermannParams ackermannParams[1]; //Suspension PxVehicleSuspensionParams suspensionParams[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleSuspensionComplianceParams suspensionComplianceParams[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleSuspensionForceParams suspensionForceParams[PxVehicleLimits::eMAX_NB_WHEELS]; //Tires PxVehicleTireForceParams tireForceParams[PxVehicleLimits::eMAX_NB_WHEELS]; //Wheels PxVehicleWheelParams wheelParams[PxVehicleLimits::eMAX_NB_WHEELS]; //Rigid body PxVehicleRigidBodyParams rigidBodyParams; BaseVehicleParams transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const; PX_FORCE_INLINE bool isValid() const { if (!axleDescription.isValid()) return false; if (!frame.isValid()) return true; if (!scale.isValid()) return false; if (!suspensionStateCalculationParams.isValid()) return false; if (!brakeResponseParams[0].isValid(axleDescription)) return false; if (!brakeResponseParams[1].isValid(axleDescription)) return false; if (!steerResponseParams.isValid(axleDescription)) return false; if (!ackermannParams[0].isValid(axleDescription)) return false; for (PxU32 i = 0; i < axleDescription.nbWheels; i++) { const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i]; if (!suspensionParams[wheelId].isValid()) return false; if (!suspensionComplianceParams[wheelId].isValid()) return false; if (!suspensionForceParams[wheelId].isValid()) return false; if (!tireForceParams[wheelId].isValid()) return false; if (!wheelParams[wheelId].isValid()) return false; } if (!rigidBodyParams.isValid()) return false; return true; } }; struct BaseVehicleState { //Command responses PxReal brakeCommandResponseStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxReal steerCommandResponseStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleWheelActuationState actuationStates[PxVehicleLimits::eMAX_NB_WHEELS]; //Road geometry PxVehicleRoadGeometryState roadGeomStates[PxVehicleLimits::eMAX_NB_WHEELS]; //Suspensions PxVehicleSuspensionState suspensionStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleSuspensionComplianceState suspensionComplianceStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleSuspensionForce suspensionForces[PxVehicleLimits::eMAX_NB_WHEELS]; //Tires PxVehicleTireGripState tireGripStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireDirectionState tireDirectionStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireSpeedState tireSpeedStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireSlipState tireSlipStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireCamberAngleState tireCamberAngleStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireStickyState tireStickyStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleTireForce tireForces[PxVehicleLimits::eMAX_NB_WHEELS]; //Wheels PxVehicleWheelRigidBody1dState wheelRigidBody1dStates[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehicleWheelLocalPose wheelLocalPoses[PxVehicleLimits::eMAX_NB_WHEELS]; //Rigid body PxVehicleRigidBodyState rigidBodyState; PX_FORCE_INLINE void setToDefault() { for (unsigned int i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++) { brakeCommandResponseStates[i] = 0.0; steerCommandResponseStates[i] = 0.0f; actuationStates[i].setToDefault(); roadGeomStates[i].setToDefault(); suspensionStates[i].setToDefault(); suspensionComplianceStates[i].setToDefault(); suspensionForces[i].setToDefault(); tireGripStates[i].setToDefault(); tireDirectionStates[i].setToDefault(); tireSpeedStates[i].setToDefault(); tireSlipStates[i].setToDefault(); tireCamberAngleStates[i].setToDefault(); tireStickyStates[i].setToDefault(); tireForces[i].setToDefault(); wheelRigidBody1dStates[i].setToDefault(); wheelLocalPoses[i].setToDefault(); } rigidBodyState.setToDefault(); } }; // //The PhysX Vehicle SDK was designed to offer flexibility on how to combine data and logic //to implement a vehicle. For the purpose of the snippets, different vehicle types are //represented using a class hierarchy to share base functionality and data. The vehicle //classes implement the component interfaces directly such that no separate component //objects are needed. If the goal was to focus more on modularity, each component //could be defined as its own class but those classes would need to reference all the //data necessary to run the component logic. //This specific class deals with the mechanical base of a vehicle (suspension, tire, //wheel, vehicle body etc.). // class BaseVehicle : public PxVehicleRigidBodyComponent , public PxVehicleSuspensionComponent , public PxVehicleTireComponent , public PxVehicleWheelComponent { public: bool initialize(); virtual void destroy() {} //To be implemented by specific vehicle types that are built on top of this class. //The specific vehicle type defines what components to run and in what order. virtual void initComponentSequence(bool addPhysXBeginEndComponents) = 0; //Run a simulation step void step(const PxReal dt, const PxVehicleSimulationContext& context); virtual void getDataForRigidBodyComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyParams*& rigidBodyParams, PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces, PxVehicleArrayData<const PxVehicleTireForce>& tireForces, const PxVehicleAntiRollTorque*& antiRollTorque, PxVehicleRigidBodyState*& rigidBodyState) { axleDescription = &mBaseParams.axleDescription; rigidBodyParams = &mBaseParams.rigidBodyParams; suspensionForces.setData(mBaseState.suspensionForces); tireForces.setData(mBaseState.tireForces); antiRollTorque = NULL; rigidBodyState = &mBaseState.rigidBodyState; } virtual void getDataForSuspensionComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyParams*& rigidBodyParams, const PxVehicleSuspensionStateCalculationParams*& suspensionStateCalculationParams, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspensionComplianceParams, PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspensionForceParams, PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams, PxVehicleArrayData<const PxVehicleRoadGeometryState>& wheelRoadGeomStates, PxVehicleArrayData<PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<PxVehicleSuspensionForce>& suspensionForces, PxVehicleAntiRollTorque*& antiRollTorque) { axleDescription = &mBaseParams.axleDescription; rigidBodyParams = &mBaseParams.rigidBodyParams; suspensionStateCalculationParams = &mBaseParams.suspensionStateCalculationParams; steerResponseStates.setData(mBaseState.steerCommandResponseStates); rigidBodyState = &mBaseState.rigidBodyState; wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); suspensionComplianceParams.setData(mBaseParams.suspensionComplianceParams); suspensionForceParams.setData(mBaseParams.suspensionForceParams); antiRollForceParams.setEmpty(); wheelRoadGeomStates.setData(mBaseState.roadGeomStates); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); suspensionForces.setData(mBaseState.suspensionForces); antiRollTorque = NULL; } virtual void getDataForTireComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams, PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeomStates, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1DStates, PxVehicleArrayData<PxVehicleTireGripState>& tireGripStates, PxVehicleArrayData<PxVehicleTireDirectionState>& tireDirectionStates, PxVehicleArrayData<PxVehicleTireSpeedState>& tireSpeedStates, PxVehicleArrayData<PxVehicleTireSlipState>& tireSlipStates, PxVehicleArrayData<PxVehicleTireCamberAngleState>& tireCamberAngleStates, PxVehicleArrayData<PxVehicleTireStickyState>& tireStickyStates, PxVehicleArrayData<PxVehicleTireForce>& tireForces) { axleDescription = &mBaseParams.axleDescription; steerResponseStates.setData(mBaseState.steerCommandResponseStates); rigidBodyState = &mBaseState.rigidBodyState; actuationStates.setData(mBaseState.actuationStates); wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); tireForceParams.setData(mBaseParams.tireForceParams); roadGeomStates.setData(mBaseState.roadGeomStates); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); suspensionForces.setData(mBaseState.suspensionForces); wheelRigidBody1DStates.setData(mBaseState.wheelRigidBody1dStates); tireGripStates.setData(mBaseState.tireGripStates); tireDirectionStates.setData(mBaseState.tireDirectionStates); tireSpeedStates.setData(mBaseState.tireSpeedStates); tireSlipStates.setData(mBaseState.tireSlipStates); tireCamberAngleStates.setData(mBaseState.tireCamberAngleStates); tireStickyStates.setData(mBaseState.tireStickyStates); tireForces.setData(mBaseState.tireForces); } virtual void getDataForWheelComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& steerResponseStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleArrayData<PxVehicleWheelLocalPose>& wheelLocalPoses) { axleDescription = &mBaseParams.axleDescription; steerResponseStates.setData(mBaseState.steerCommandResponseStates); wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); actuationStates.setData(mBaseState.actuationStates); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); tireSpeedStates.setData(mBaseState.tireSpeedStates); wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); wheelLocalPoses.setData(mBaseState.wheelLocalPoses); } //Parameters and statess of the vehicle's mechanical base. BaseVehicleParams mBaseParams; BaseVehicleState mBaseState; //The sequence of components that will simulate the vehicle. //To be assembled by specific vehicle types that are built //on top of this class PxVehicleComponentSequence mComponentSequence; //A sub-group of components can be simulated with multiple substeps //to improve simulation fidelity without running the full sequence //at a lower timestep. PxU8 mComponentSequenceSubstepGroupHandle; }; }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/enginedrivetrain/EngineDrivetrain.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../physxintegration/PhysXIntegration.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct EngineDrivetrainParams { PxVehicleAutoboxParams autoboxParams; PxVehicleClutchCommandResponseParams clutchCommandResponseParams; PxVehicleEngineParams engineParams; PxVehicleGearboxParams gearBoxParams; PxVehicleMultiWheelDriveDifferentialParams multiWheelDifferentialParams; PxVehicleFourWheelDriveDifferentialParams fourWheelDifferentialParams; PxVehicleTankDriveDifferentialParams tankDifferentialParams; PxVehicleClutchParams clutchParams; EngineDrivetrainParams transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const; PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const { if (!autoboxParams.isValid(gearBoxParams)) return false; if (!clutchCommandResponseParams.isValid()) return false; if (!engineParams.isValid()) return false; if (!gearBoxParams.isValid()) return false; if (!multiWheelDifferentialParams.isValid(axleDesc)) return false; if (!fourWheelDifferentialParams.isValid(axleDesc)) return false; if (!tankDifferentialParams.isValid(axleDesc)) return false; if (!clutchParams.isValid()) return false; return true; } }; struct EngineDrivetrainState { PxVehicleEngineDriveThrottleCommandResponseState throttleCommandResponseState; PxVehicleAutoboxState autoboxState; PxVehicleClutchCommandResponseState clutchCommandResponseState; PxVehicleDifferentialState differentialState; PxVehicleWheelConstraintGroupState wheelConstraintGroupState; PxVehicleEngineState engineState; PxVehicleGearboxState gearboxState; PxVehicleClutchSlipState clutchState; PX_FORCE_INLINE void setToDefault() { throttleCommandResponseState.setToDefault(); autoboxState.setToDefault(); clutchCommandResponseState.setToDefault(); differentialState.setToDefault(); wheelConstraintGroupState.setToDefault(); engineState.setToDefault(); gearboxState.setToDefault(); clutchState.setToDefault(); } }; // //This class holds the parameters, state and logic needed to implement a vehicle that //is using an engine drivetrain with gears, clutch etc. // //See BaseVehicle for more details on the snippet code design. // class EngineDriveVehicle : public PhysXActorVehicle , public PxVehicleEngineDriveCommandResponseComponent , public PxVehicleFourWheelDriveDifferentialStateComponent , public PxVehicleMultiWheelDriveDifferentialStateComponent , public PxVehicleTankDriveDifferentialStateComponent , public PxVehicleEngineDriveActuationStateComponent , public PxVehicleEngineDrivetrainComponent { public: enum Enum { eDIFFTYPE_FOURWHEELDRIVE, eDIFFTYPE_MULTIWHEELDRIVE, eDIFFTYPE_TANKDRIVE }; bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, Enum differentialType, bool addPhysXBeginEndComponents=true); virtual void destroy(); virtual void initComponentSequence(bool addPhysXBeginEndComponents); virtual void getDataForPhysXActorBeginComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleCommandState*& commands, const PxVehicleEngineDriveTransmissionCommandState*& transmissionCommands, const PxVehicleGearboxParams*& gearParams, const PxVehicleGearboxState*& gearState, const PxVehicleEngineParams*& engineParams, PxVehiclePhysXActor*& physxActor, PxVehiclePhysXSteerState*& physxSteerState, PxVehiclePhysXConstraints*& physxConstraints, PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleEngineState*& engineState) { axleDescription = &mBaseParams.axleDescription; commands = &mCommandState; physxActor = &mPhysXState.physxActor; physxSteerState = &mPhysXState.physxSteerState; physxConstraints = &mPhysXState.physxConstraints; rigidBodyState = &mBaseState.rigidBodyState; wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); transmissionCommands = &mTransmissionCommandState; gearParams = &mEngineDriveParams.gearBoxParams; gearState = &mEngineDriveState.gearboxState; engineParams = &mEngineDriveParams.engineParams; engineState = &mEngineDriveState.engineState; } virtual void getDataForPhysXActorEndComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxTransform>& wheelShapeLocalPoses, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses, const PxVehicleGearboxState*& gearState, const PxReal*& throttle, PxVehiclePhysXActor*& physxActor) { axleDescription = &mBaseParams.axleDescription; rigidBodyState = &mBaseState.rigidBodyState; wheelParams.setData(mBaseParams.wheelParams); wheelShapeLocalPoses.setData(mPhysXParams.physxWheelShapeLocalPoses); wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); wheelLocalPoses.setData(mBaseState.wheelLocalPoses); physxActor = &mPhysXState.physxActor; gearState = &mEngineDriveState.gearboxState; throttle = &mCommandState.throttle; } virtual void getDataForEngineDriveCommandResponseComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams, const PxVehicleSteerCommandResponseParams*& steerResponseParams, PxVehicleSizedArrayData<const PxVehicleAckermannParams>& ackermannParams, const PxVehicleGearboxParams*& gearboxParams, const PxVehicleClutchCommandResponseParams*& clutchResponseParams, const PxVehicleEngineParams*& engineParams, const PxVehicleRigidBodyState*& rigidBodyState, const PxVehicleEngineState*& engineState, const PxVehicleAutoboxParams*& autoboxParams, const PxVehicleCommandState*& commands, const PxVehicleEngineDriveTransmissionCommandState*& transmissionCommands, PxVehicleArrayData<PxReal>& brakeResponseStates, PxVehicleEngineDriveThrottleCommandResponseState*& throttleResponseState, PxVehicleArrayData<PxReal>& steerResponseStates, PxVehicleGearboxState*& gearboxResponseState, PxVehicleClutchCommandResponseState*& clutchResponseState, PxVehicleAutoboxState*& autoboxState) { axleDescription = &mBaseParams.axleDescription; brakeResponseParams.setDataAndCount(mBaseParams.brakeResponseParams, sizeof(mBaseParams.brakeResponseParams) / sizeof(PxVehicleBrakeCommandResponseParams)); steerResponseParams = &mBaseParams.steerResponseParams; ackermannParams.setDataAndCount(mBaseParams.ackermannParams, sizeof(mBaseParams.ackermannParams)/sizeof(PxVehicleAckermannParams)); gearboxParams = &mEngineDriveParams.gearBoxParams; clutchResponseParams = &mEngineDriveParams.clutchCommandResponseParams; engineParams = &mEngineDriveParams.engineParams; rigidBodyState = &mBaseState.rigidBodyState; engineState = &mEngineDriveState.engineState; autoboxParams = &mEngineDriveParams.autoboxParams; commands = &mCommandState; transmissionCommands = (Enum::eDIFFTYPE_TANKDRIVE == mDifferentialType) ? &mTankDriveTransmissionCommandState : &mTransmissionCommandState; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseState = &mEngineDriveState.throttleCommandResponseState; steerResponseStates.setData(mBaseState.steerCommandResponseStates); gearboxResponseState = &mEngineDriveState.gearboxState; clutchResponseState = &mEngineDriveState.clutchCommandResponseState; autoboxState = &mEngineDriveState.autoboxState; } virtual void getDataForFourWheelDriveDifferentialStateComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleFourWheelDriveDifferentialParams*& differentialParams, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidbody1dStates, PxVehicleDifferentialState*& differentialState, PxVehicleWheelConstraintGroupState*& wheelConstraintGroups) { axleDescription = &mBaseParams.axleDescription; differentialParams = &mEngineDriveParams.fourWheelDifferentialParams; wheelRigidbody1dStates.setData(mBaseState.wheelRigidBody1dStates); differentialState = &mEngineDriveState.differentialState; wheelConstraintGroups = &mEngineDriveState.wheelConstraintGroupState; } virtual void getDataForMultiWheelDriveDifferentialStateComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleMultiWheelDriveDifferentialParams*& differentialParams, PxVehicleDifferentialState*& differentialState) { axleDescription = &mBaseParams.axleDescription; differentialParams = &mEngineDriveParams.multiWheelDifferentialParams; differentialState = &mEngineDriveState.differentialState; } virtual void getDataForTankDriveDifferentialStateComponent( const PxVehicleAxleDescription *&axleDescription, const PxVehicleTankDriveTransmissionCommandState*& tankDriveTransmissionCommands, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, const PxVehicleTankDriveDifferentialParams *& differentialParams, PxVehicleDifferentialState *& differentialState, PxVehicleWheelConstraintGroupState*& wheelConstraintGroups) { axleDescription = &mBaseParams.axleDescription; tankDriveTransmissionCommands = &mTankDriveTransmissionCommandState; wheelParams.setData(mBaseParams.wheelParams); differentialParams = &mEngineDriveParams.tankDifferentialParams; differentialState = &mEngineDriveState.differentialState; wheelConstraintGroups = &mEngineDriveState.wheelConstraintGroupState; } virtual void getDataForEngineDriveActuationStateComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleGearboxParams*& gearboxParams, PxVehicleArrayData<const PxReal>& brakeResponseStates, const PxVehicleEngineDriveThrottleCommandResponseState*& throttleResponseState, const PxVehicleGearboxState*& gearboxState, const PxVehicleDifferentialState*& differentialState, const PxVehicleClutchCommandResponseState*& clutchResponseState, PxVehicleArrayData<PxVehicleWheelActuationState>& actuationStates) { axleDescription = &mBaseParams.axleDescription; gearboxParams = &mEngineDriveParams.gearBoxParams; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseState = &mEngineDriveState.throttleCommandResponseState; gearboxState = &mEngineDriveState.gearboxState; differentialState = &mEngineDriveState.differentialState; clutchResponseState = &mEngineDriveState.clutchCommandResponseState; actuationStates.setData(mBaseState.actuationStates); } virtual void getDataForEngineDrivetrainComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, const PxVehicleEngineParams*& engineParams, const PxVehicleClutchParams*& clutchParams, const PxVehicleGearboxParams*& gearboxParams, PxVehicleArrayData<const PxReal>& brakeResponseStates, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleTireForce>& tireForces, const PxVehicleEngineDriveThrottleCommandResponseState*& throttleResponseState, const PxVehicleClutchCommandResponseState*& clutchResponseState, const PxVehicleDifferentialState*& differentialState, const PxVehicleWheelConstraintGroupState*& constraintGroupState, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleEngineState*& engineState, PxVehicleGearboxState*& gearboxState, PxVehicleClutchSlipState*& clutchState) { axleDescription = &mBaseParams.axleDescription; wheelParams.setData(mBaseParams.wheelParams); engineParams = &mEngineDriveParams.engineParams; clutchParams = &mEngineDriveParams.clutchParams; gearboxParams = &mEngineDriveParams.gearBoxParams; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); actuationStates.setData(mBaseState.actuationStates); tireForces.setData(mBaseState.tireForces); throttleResponseState = &mEngineDriveState.throttleCommandResponseState; clutchResponseState = &mEngineDriveState.clutchCommandResponseState; differentialState = &mEngineDriveState.differentialState; constraintGroupState = Enum::eDIFFTYPE_TANKDRIVE == mDifferentialType ? &mEngineDriveState.wheelConstraintGroupState : NULL; wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); engineState = &mEngineDriveState.engineState; gearboxState = &mEngineDriveState.gearboxState; clutchState = &mEngineDriveState.clutchState; } //Parameters and states of the vehicle's engine drivetrain. EngineDrivetrainParams mEngineDriveParams; EngineDrivetrainState mEngineDriveState; //The commands that will control the vehicle's transmission PxVehicleEngineDriveTransmissionCommandState mTransmissionCommandState; PxVehicleTankDriveTransmissionCommandState mTankDriveTransmissionCommandState; //The type of differential that will be used. //If eDIFFTYPE_TANKDRIVE is chosen then the vehicle's transmission //commands are stored in mTankDriveTransmissionCommandState. //If eDIFFTYPE_FOURWHEELDRIVE or eDIFFTYPE_MULTIWHEELDRIVE is chosen //then the vehicle's transmission commands are stored in //mTransmissionCommandState Enum mDifferentialType; }; }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/enginedrivetrain/EngineDrivetrain.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "EngineDrivetrain.h" #include "../base/Base.h" namespace snippetvehicle2 { EngineDrivetrainParams EngineDrivetrainParams::transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const { EngineDrivetrainParams r = *this; r.autoboxParams = autoboxParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.clutchCommandResponseParams = clutchCommandResponseParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.engineParams = engineParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.gearBoxParams = gearBoxParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.fourWheelDifferentialParams = fourWheelDifferentialParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.multiWheelDifferentialParams = multiWheelDifferentialParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.tankDifferentialParams = tankDifferentialParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); r.clutchParams = clutchParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); return r; } bool EngineDriveVehicle::initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, Enum differentialTye, bool addPhysXBeginEndComponents) { mDifferentialType = differentialTye; mTransmissionCommandState.setToDefault(); mTankDriveTransmissionCommandState.setToDefault(); if (!PhysXActorVehicle::initialize(physics, params, defaultMaterial)) return false; if (!mEngineDriveParams.isValid(mBaseParams.axleDescription)) return false; //Set the drivetrain state to default. mEngineDriveState.setToDefault(); //Add all the components in sequence that will simulate a vehicle with an engine drive drivetrain. initComponentSequence(addPhysXBeginEndComponents); return true; } void EngineDriveVehicle::destroy() { PhysXActorVehicle::destroy(); } void EngineDriveVehicle::initComponentSequence(bool addPhysXBeginEndComponents) { //Wake up the associated PxRigidBody if it is asleep and the vehicle commands signal an //intent to change state. //Read from the physx actor and write the state (position, velocity etc) to the vehicle. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorBeginComponent*>(this)); //Read the input commands (throttle, brake, steer, clutch etc) and forward them to the drivetrain and steering mechanism. //When using automatic transmission, the autobox determines if it wants to begin a gear change. If it does, it will overwrite //the target gear command and set throttle to 0 internally. mComponentSequence.add(static_cast<PxVehicleEngineDriveCommandResponseComponent*>(this)); //The differential determines the fraction of available drive torque that will be delivered to each wheel. switch (mDifferentialType) { case eDIFFTYPE_FOURWHEELDRIVE: mComponentSequence.add(static_cast<PxVehicleFourWheelDriveDifferentialStateComponent*>(this)); break; case eDIFFTYPE_MULTIWHEELDRIVE: mComponentSequence.add(static_cast<PxVehicleMultiWheelDriveDifferentialStateComponent*>(this)); break; case eDIFFTYPE_TANKDRIVE: mComponentSequence.add(static_cast<PxVehicleTankDriveDifferentialStateComponent*>(this)); break; default: PX_ASSERT(false); break; } //Work out which wheels have a non-zero drive torque and non-zero brake torque. //This is used to determine if any tire is to enter the "sticky" regime that will bring the //vehicle to rest. mComponentSequence.add(static_cast<PxVehicleEngineDriveActuationStateComponent*>(this)); //Perform a scene query against the physx scene to determine the plane and friction under each wheel. mComponentSequence.add(static_cast<PxVehiclePhysXRoadGeometrySceneQueryComponent*>(this)); //Start a substep group that can be ticked multiple times per update. //Record the handle returned by PxVehicleComponentSequence::beginSubstepGroup() because this //is used later to set the number of substeps for this substep group. //In this example, we allow the update of the suspensions, tires and wheels multiple times without recalculating //the plane underneath the wheel. This is useful for stability at low forward speeds and is much cheaper //than setting a smaller timestep for the whole vehicle. mComponentSequenceSubstepGroupHandle = mComponentSequence.beginSubstepGroup(3); //Update the suspension compression given the plane under each wheel. //Update the kinematic compliance from the compression state of each suspension. //Convert suspension state to suspension force and torque. mComponentSequence.add(static_cast<PxVehicleSuspensionComponent*>(this)); //Compute the load on the tire, the friction experienced by the tire //and the lateral/longitudinal slip angles. //Convert load/friction/slip to tire force and torque. //If the vehicle is to come rest then compute the "sticky" velocity constraints to apply to the //vehicle. mComponentSequence.add(static_cast<PxVehicleTireComponent*>(this)); //Apply any "sticky" velocity constraints to a data buffer that will be consumed by the physx scene //during the next physx scene update. mComponentSequence.add(static_cast<PxVehiclePhysXConstraintComponent*>(this)); //Update the rotational speed of the engine and wheels by applying the available drive torque //to the wheels through the clutch, differential and gears and accounting for the longitudinal //tire force that is applied to the wheel's angular momentum. mComponentSequence.add(static_cast<PxVehicleEngineDrivetrainComponent*>(this)); //Apply the suspension and tire forces to the vehicle's rigid body and forward //integrate the state of the rigid body. mComponentSequence.add(static_cast<PxVehicleRigidBodyComponent*>(this)); //Mark the end of the substep group. mComponentSequence.endSubstepGroup(); //Update the rotation angle of the wheel by forwarding integrating the rotational //speed of each wheel. //Compute the local pose of the wheel in the rigid body frame after accounting //suspension compression and compliance. mComponentSequence.add(static_cast<PxVehicleWheelComponent*>(this)); //Write the local poses of each wheel to the corresponding shapes on the physx actor. //Write the momentum change applied to the vehicle's rigid body to the physx actor. //The physx scene can now try to apply that change to the physx actor. //The physx scene will account for collisions and constraints to be applied to the vehicle //that occur by applying the change. if (addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorEndComponent*>(this)); } }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/physxintegration/PhysXIntegration.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "PxScene.h" #include "vehicle2/PxVehicleAPI.h" #include "../base/Base.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct PhysXIntegrationParams { PxVehiclePhysXRoadGeometryQueryParams physxRoadGeometryQueryParams; PxVehiclePhysXMaterialFrictionParams physxMaterialFrictionParams[PxVehicleLimits::eMAX_NB_WHEELS]; PxVehiclePhysXSuspensionLimitConstraintParams physxSuspensionLimitConstraintParams[PxVehicleLimits::eMAX_NB_WHEELS]; PxTransform physxActorCMassLocalPose; PxVec3 physxActorBoxShapeHalfExtents; PxTransform physxActorBoxShapeLocalPose; PxTransform physxWheelShapeLocalPoses[PxVehicleLimits::eMAX_NB_WHEELS]; void create (const PxVehicleAxleDescription& axleDescription, const PxQueryFilterData& queryFilterData, PxQueryFilterCallback* queryFilterCallback, PxVehiclePhysXMaterialFriction* materialFrictions, const PxU32 nbMaterialFrictions, const PxReal defaultFriction, const PxTransform& physXActorCMassLocalPose, const PxVec3& physXActorBoxShapeHalfExtents, const PxTransform& physxActorBoxShapeLocalPose); PhysXIntegrationParams transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const; PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const { if (!physxRoadGeometryQueryParams.isValid()) return false; for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; if (!physxMaterialFrictionParams[wheelId].isValid()) return false; if (!physxSuspensionLimitConstraintParams[wheelId].isValid()) return false; } return true; } }; struct PhysXIntegrationState { PxVehiclePhysXActor physxActor; //physx actor PxVehiclePhysXSteerState physxSteerState; PxVehiclePhysXConstraints physxConstraints; //susp limit and sticky tire constraints PX_FORCE_INLINE void setToDefault() { physxActor.setToDefault(); physxSteerState.setToDefault(); physxConstraints.setToDefault(); } void create (const BaseVehicleParams& baseParams, const PhysXIntegrationParams& physxParams, PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial); void destroy(); }; void setPhysXIntegrationParams(const PxVehicleAxleDescription&, PxVehiclePhysXMaterialFriction*, PxU32 nbPhysXMaterialFrictions, PxReal physXDefaultMaterialFriction, PhysXIntegrationParams&); // //This class holds the parameters, state and logic needed to implement a vehicle that //is using a PhysX actor to potentially interact with other objects in a PhysX scene. // //See BaseVehicle for more details on the snippet code design. // class PhysXActorVehicle : public BaseVehicle , public PxVehiclePhysXActorBeginComponent , public PxVehiclePhysXActorEndComponent , public PxVehiclePhysXConstraintComponent , public PxVehiclePhysXRoadGeometrySceneQueryComponent { public: bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial); virtual void destroy(); void setUpActor(PxScene& scene, const PxTransform& pose, const char* vehicleName); virtual void getDataForPhysXActorBeginComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleCommandState*& commands, const PxVehicleEngineDriveTransmissionCommandState*& transmissionCommands, const PxVehicleGearboxParams*& gearParams, const PxVehicleGearboxState*& gearState, const PxVehicleEngineParams*& engineParams, PxVehiclePhysXActor*& physxActor, PxVehiclePhysXSteerState*& physxSteerState, PxVehiclePhysXConstraints*& physxConstraints, PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleEngineState*& engineState) { axleDescription = &mBaseParams.axleDescription; commands = &mCommandState; physxActor = &mPhysXState.physxActor; physxSteerState = &mPhysXState.physxSteerState; physxConstraints = &mPhysXState.physxConstraints; rigidBodyState = &mBaseState.rigidBodyState; wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); transmissionCommands = NULL; gearParams = NULL; gearState = NULL; engineParams = NULL; engineState = NULL; } virtual void getDataForPhysXActorEndComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxTransform>& wheelShapeLocalPoses, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates, PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses, const PxVehicleGearboxState*& gearState, const PxReal*& throttle, PxVehiclePhysXActor*& physxActor) { axleDescription = &mBaseParams.axleDescription; rigidBodyState = &mBaseState.rigidBodyState; wheelParams.setData(mBaseParams.wheelParams); wheelShapeLocalPoses.setData(mPhysXParams.physxWheelShapeLocalPoses); wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); wheelLocalPoses.setData(mBaseState.wheelLocalPoses); physxActor = &mPhysXState.physxActor; gearState = NULL; throttle = &mCommandState.throttle; } virtual void getDataForPhysXConstraintComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& suspensionLimitParams, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleRoadGeometryState>& wheelRoadGeomStates, PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates, PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates, PxVehiclePhysXConstraints*& constraints) { axleDescription = &mBaseParams.axleDescription; rigidBodyState = &mBaseState.rigidBodyState; suspensionParams.setData(mBaseParams.suspensionParams); suspensionLimitParams.setData(mPhysXParams.physxSuspensionLimitConstraintParams); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); wheelRoadGeomStates.setData(mBaseState.roadGeomStates); tireDirectionStates.setData(mBaseState.tireDirectionStates); tireStickyStates.setData(mBaseState.tireStickyStates); constraints = &mPhysXState.physxConstraints; } virtual void getDataForPhysXRoadGeometrySceneQueryComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehiclePhysXRoadGeometryQueryParams*& roadGeomParams, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& materialFrictionParams, PxVehicleArrayData<PxVehicleRoadGeometryState>& roadGeometryStates, PxVehicleArrayData<PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeometryStates) { axleDescription = &mBaseParams.axleDescription; roadGeomParams = &mPhysXParams.physxRoadGeometryQueryParams; steerResponseStates.setData(mBaseState.steerCommandResponseStates); rigidBodyState = &mBaseState.rigidBodyState; wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); materialFrictionParams.setData(mPhysXParams.physxMaterialFrictionParams); roadGeometryStates.setData(mBaseState.roadGeomStates); physxRoadGeometryStates.setEmpty(); } //Parameters and states of the vehicle's physx integration. PhysXIntegrationParams mPhysXParams; PhysXIntegrationState mPhysXState; //The commands that will control the vehicle // // Note that this is not related to a PhysX actor based vehicle as such but // put in here to be shared by all vehicle types that will be based on this // class. It keeps the code simpler for the purpose of the snippets. // PxVehicleCommandState mCommandState; }; }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/physxintegration/PhysXIntegration.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PhysXIntegration.h" namespace snippetvehicle2 { void PhysXIntegrationParams::create (const PxVehicleAxleDescription& axleDescription, const PxQueryFilterData& queryFilterData, PxQueryFilterCallback* queryFilterCallback, PxVehiclePhysXMaterialFriction* materialFrictions, const PxU32 nbMaterialFrictions, const PxReal defaultFriction, const PxTransform& actorCMassLocalPose, const PxVec3& actorBoxShapeHalfExtents, const PxTransform& actorBoxShapeLocalPose) { physxRoadGeometryQueryParams.roadGeometryQueryType = PxVehiclePhysXRoadGeometryQueryType::eRAYCAST; physxRoadGeometryQueryParams.defaultFilterData = queryFilterData; physxRoadGeometryQueryParams.filterCallback = queryFilterCallback; physxRoadGeometryQueryParams.filterDataEntries = NULL; for(PxU32 i = 0; i < axleDescription.nbWheels; i++) { const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i]; physxMaterialFrictionParams[wheelId].defaultFriction = defaultFriction; physxMaterialFrictionParams[wheelId].materialFrictions = materialFrictions; physxMaterialFrictionParams[wheelId].nbMaterialFrictions = nbMaterialFrictions; physxSuspensionLimitConstraintParams[wheelId].restitution = 0.0f; physxSuspensionLimitConstraintParams[wheelId].directionForSuspensionLimitConstraint = PxVehiclePhysXSuspensionLimitConstraintParams::eROAD_GEOMETRY_NORMAL; physxWheelShapeLocalPoses[wheelId] = PxTransform(PxIdentity); } physxActorCMassLocalPose = actorCMassLocalPose; physxActorBoxShapeHalfExtents = actorBoxShapeHalfExtents; physxActorBoxShapeLocalPose = actorBoxShapeLocalPose; } PhysXIntegrationParams PhysXIntegrationParams::transformAndScale (const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const { PhysXIntegrationParams r = *this; r.physxRoadGeometryQueryParams = physxRoadGeometryQueryParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); for (PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++) { r.physxSuspensionLimitConstraintParams[i] = physxSuspensionLimitConstraintParams[i].transformAndScale(srcFrame, trgFrame, srcScale, trgScale); } r.physxActorCMassLocalPose = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, srcScale, trgScale, physxActorCMassLocalPose); r.physxActorBoxShapeHalfExtents = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, srcScale, trgScale, physxActorBoxShapeHalfExtents); r.physxActorBoxShapeLocalPose = PxVehicleTransformFrameToFrame(srcFrame, trgFrame, srcScale, trgScale, physxActorBoxShapeLocalPose); return r; } void PhysXIntegrationState::create (const BaseVehicleParams& baseParams, const PhysXIntegrationParams& physxParams, PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial) { setToDefault(); //physxActor needs to be populated with an actor and its shapes. { const PxVehiclePhysXRigidActorParams physxActorParams(baseParams.rigidBodyParams, NULL); const PxBoxGeometry boxGeom(physxParams.physxActorBoxShapeHalfExtents); const PxVehiclePhysXRigidActorShapeParams physxActorShapeParams(boxGeom, physxParams.physxActorBoxShapeLocalPose, defaultMaterial, PxShapeFlags(0), PxFilterData(), PxFilterData()); const PxVehiclePhysXWheelParams physxWheelParams(baseParams.axleDescription, baseParams.wheelParams); const PxVehiclePhysXWheelShapeParams physxWheelShapeParams(defaultMaterial, PxShapeFlags(0), PxFilterData(), PxFilterData()); PxVehiclePhysXActorCreate( baseParams.frame, physxActorParams, physxParams.physxActorCMassLocalPose, physxActorShapeParams, physxWheelParams, physxWheelShapeParams, physics, params, physxActor); } //physxConstraints needs to be populated with constraints. PxVehicleConstraintsCreate(baseParams.axleDescription, physics, *physxActor.rigidBody, physxConstraints); } void PhysXIntegrationState::destroy() { PxVehicleConstraintsDestroy(physxConstraints); PxVehiclePhysXActorDestroy(physxActor); } void setPhysXIntegrationParams(const PxVehicleAxleDescription& axleDescription, PxVehiclePhysXMaterialFriction* physXMaterialFrictions, PxU32 nbPhysXMaterialFrictions, PxReal physXDefaultMaterialFriction, PhysXIntegrationParams& physXParams) { //The physx integration params are hardcoded rather than loaded from file. const PxQueryFilterData queryFilterData(PxFilterData(0, 0, 0, 0), PxQueryFlag::eSTATIC); PxQueryFilterCallback* queryFilterCallback = NULL; const PxTransform physxActorCMassLocalPose(PxVec3(0.0f, 0.55f, 1.594f), PxQuat(PxIdentity)); const PxVec3 physxActorBoxShapeHalfExtents(0.84097f, 0.65458f, 2.46971f); const PxTransform physxActorBoxShapeLocalPose(PxVec3(0.0f, 0.830066f, 1.37003f), PxQuat(PxIdentity)); physXParams.create( axleDescription, queryFilterData, queryFilterCallback, physXMaterialFrictions, nbPhysXMaterialFrictions, physXDefaultMaterialFriction, physxActorCMassLocalPose, physxActorBoxShapeHalfExtents, physxActorBoxShapeLocalPose); } bool PhysXActorVehicle::initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial) { mCommandState.setToDefault(); if (!BaseVehicle::initialize()) return false; if (!mPhysXParams.isValid(mBaseParams.axleDescription)) return false; mPhysXState.create(mBaseParams, mPhysXParams, physics, params, defaultMaterial); return true; } void PhysXActorVehicle::destroy() { mPhysXState.destroy(); BaseVehicle::destroy(); } void PhysXActorVehicle::setUpActor(PxScene& scene, const PxTransform& pose, const char* vehicleName) { //Give the vehicle a start pose by appylying a pose to the PxRigidDynamic associated with the vehicle. //This vehicle has components that are configured to read the pose from the PxRigidDynamic //at the start of the vehicle simulation update and to write back an updated pose at the end of the //vehicle simulation update. This allows PhysX to manage any collisions that might happen in-between //each vehicle update. This is not essential but it is anticipated that this will be a typical component //configuration. mPhysXState.physxActor.rigidBody->setGlobalPose(pose); //Add the physx actor to the physx scene. //As described above, a vehicle may be coupled to a physx scene or it can be simulated without any reference to //to a PxRigidDynamic or PxScene. This snippet vehicle employs a configuration that includes coupling to a PxScene and a //PxRigidDynamic. This being the case, the PxRigidDynamic associated with the vehicle needs to be added to the //PxScene instance. scene.addActor(*mPhysXState.physxActor.rigidBody); //Give the physx actor a name to help identification in PVD mPhysXState.physxActor.rigidBody->setName(vehicleName); } }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/directdrivetrain/DirectDrivetrain.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "DirectDrivetrain.h" #include "../base/Base.h" namespace snippetvehicle2 { DirectDrivetrainParams DirectDrivetrainParams::transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const { DirectDrivetrainParams r = *this; r.directDriveThrottleResponseParams = directDriveThrottleResponseParams.transformAndScale(srcFrame, trgFrame, srcScale, trgScale); return r; } bool DirectDriveVehicle::initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents) { mTransmissionCommandState.setToDefault(); if (!PhysXActorVehicle::initialize(physics, params, defaultMaterial)) return false; if (!mDirectDriveParams.isValid(mBaseParams.axleDescription)) return false; //Set the drivetrain state to default. mDirectDriveState.setToDefault(); //Add all the components in sequence that will simulate a vehicle with a direct drive drivetrain. initComponentSequence(addPhysXBeginEndComponents); return true; } void DirectDriveVehicle::destroy() { PhysXActorVehicle::destroy(); } void DirectDriveVehicle::initComponentSequence(bool addPhysXBeginEndComponents) { //Wake up the associated PxRigidBody if it is asleep and the vehicle commands signal an //intent to change state. //Read from the physx actor and write the state (position, velocity etc) to the vehicle. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorBeginComponent*>(this)); //Read the input commands (throttle, brake etc) and forward them as torques and angles to the wheels on each axle. mComponentSequence.add(static_cast<PxVehicleDirectDriveCommandResponseComponent*>(this)); //Work out which wheels have a non-zero drive torque and non-zero brake torque. //This is used to determine if any tire is to enter the "sticky" regime that will bring the //vehicle to rest. mComponentSequence.add(static_cast<PxVehicleDirectDriveActuationStateComponent*>(this)); //Perform a scene query against the physx scene to determine the plane and friction under each wheel. mComponentSequence.add(static_cast<PxVehiclePhysXRoadGeometrySceneQueryComponent*>(this)); //Start a substep group that can be ticked multiple times per update. //In this example, we update the suspensions, tires and wheels 3 times without recalculating //the plane underneath the wheel. This is useful for stability at low forward speeds and is //computationally cheaper than simulating the whole pipeline at a smaller timestep. mComponentSequenceSubstepGroupHandle = mComponentSequence.beginSubstepGroup(3); //Update the suspension compression given the plane under each wheel. //Update the kinematic compliance from the compression state of each suspension. //Convert suspension state to suspension force and torque. mComponentSequence.add(static_cast<PxVehicleSuspensionComponent*>(this)); //Compute the load on the tire, the friction experienced by the tire //and the lateral/longitudinal slip angles. //Convert load/friction/slip to tire force and torque. //If the vehicle is to come rest then compute the "sticky" velocity constraints to apply to the //vehicle. mComponentSequence.add(static_cast<PxVehicleTireComponent*>(this)); //Apply any velocity constraints to a data buffer that will be consumed by the physx scene //during the next physx scene update. mComponentSequence.add(static_cast<PxVehiclePhysXConstraintComponent*>(this)); //Apply the tire force, brake force and drive force to each wheel and //forward integrate the rotation speed of each wheel. mComponentSequence.add(static_cast<PxVehicleDirectDrivetrainComponent*>(this)); //Apply the suspension and tire forces to the vehicle's rigid body and forward //integrate the state of the rigid body. mComponentSequence.add(static_cast<PxVehicleRigidBodyComponent*>(this)); //Mark the end of the substep group. mComponentSequence.endSubstepGroup(); //Update the rotation angle of the wheel by forwarding integrating the rotational //speed of each wheel. //Compute the local pose of the wheel in the rigid body frame after accounting //suspension compression and compliance. mComponentSequence.add(static_cast<PxVehicleWheelComponent*>(this)); //Write the local poses of each wheel to the corresponding shapes on the physx actor. //Write the momentum change applied to the vehicle's rigid body to the physx actor. //The physx scene can now try to apply that change to the physx actor. //The physx scene will account for collisions and constraints to be applied to the vehicle //that occur by applying the change. if (addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorEndComponent*>(this)); } }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/directdrivetrain/DirectDrivetrain.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../physxintegration/PhysXIntegration.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct DirectDrivetrainParams { PxVehicleDirectDriveThrottleCommandResponseParams directDriveThrottleResponseParams; DirectDrivetrainParams transformAndScale( const PxVehicleFrame& srcFrame, const PxVehicleFrame& trgFrame, const PxVehicleScale& srcScale, const PxVehicleScale& trgScale) const; PX_FORCE_INLINE bool isValid(const PxVehicleAxleDescription& axleDesc) const { if (!directDriveThrottleResponseParams.isValid(axleDesc)) return false; return true; } }; struct DirectDrivetrainState { PxReal directDriveThrottleResponseStates[PxVehicleLimits::eMAX_NB_WHEELS]; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(DirectDrivetrainState)); } }; // //This class holds the parameters, state and logic needed to implement a vehicle that //is using a direct drivetrain. // //See BaseVehicle for more details on the snippet code design. // class DirectDriveVehicle : public PhysXActorVehicle , public PxVehicleDirectDriveCommandResponseComponent , public PxVehicleDirectDriveActuationStateComponent , public PxVehicleDirectDrivetrainComponent { public: bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents = true); virtual void destroy(); virtual void initComponentSequence(bool addPhysXBeginEndComponents); void getDataForDirectDriveCommandResponseComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams, const PxVehicleDirectDriveThrottleCommandResponseParams*& throttleResponseParams, const PxVehicleSteerCommandResponseParams*& steerResponseParams, PxVehicleSizedArrayData<const PxVehicleAckermannParams>& ackermannParams, const PxVehicleCommandState*& commands, const PxVehicleDirectDriveTransmissionCommandState*& transmissionCommands, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<PxReal>& brakeResponseStates, PxVehicleArrayData<PxReal>& throttleResponseStates, PxVehicleArrayData<PxReal>& steerResponseStates) { axleDescription = &mBaseParams.axleDescription; brakeResponseParams.setDataAndCount(mBaseParams.brakeResponseParams, sizeof(mBaseParams.brakeResponseParams) / sizeof(PxVehicleBrakeCommandResponseParams)); throttleResponseParams = &mDirectDriveParams.directDriveThrottleResponseParams; steerResponseParams = &mBaseParams.steerResponseParams; ackermannParams.setDataAndCount(mBaseParams.ackermannParams, sizeof(mBaseParams.ackermannParams)/sizeof(PxVehicleAckermannParams)); commands = &mCommandState; transmissionCommands = &mTransmissionCommandState; rigidBodyState = &mBaseState.rigidBodyState; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseStates.setData(mDirectDriveState.directDriveThrottleResponseStates); steerResponseStates.setData(mBaseState.steerCommandResponseStates); } virtual void getDataForDirectDriveActuationStateComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& brakeResponseStates, PxVehicleArrayData<const PxReal>& throttleResponseStates, PxVehicleArrayData<PxVehicleWheelActuationState>& actuationStates) { axleDescription = &mBaseParams.axleDescription; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseStates.setData(mDirectDriveState.directDriveThrottleResponseStates); actuationStates.setData(mBaseState.actuationStates); } virtual void getDataForDirectDrivetrainComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& brakeResponseStates, PxVehicleArrayData<const PxReal>& throttleResponseStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleTireForce>& tireForces, PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates) { axleDescription = &mBaseParams.axleDescription; brakeResponseStates.setData(mBaseState.brakeCommandResponseStates); throttleResponseStates.setData(mDirectDriveState.directDriveThrottleResponseStates); wheelParams.setData(mBaseParams.wheelParams); actuationStates.setData(mBaseState.actuationStates); tireForces.setData(mBaseState.tireForces); wheelRigidBody1dStates.setData(mBaseState.wheelRigidBody1dStates); } //Parameters and states of the vehicle's direct drivetrain. DirectDrivetrainParams mDirectDriveParams; DirectDrivetrainState mDirectDriveState; //The commands that will control the vehicle's transmission PxVehicleDirectDriveTransmissionCommandState mTransmissionCommandState; }; }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/DirectDrivetrainSerialization.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../directdrivetrain/DirectDrivetrain.h" #if PX_SWITCH #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #elif PX_OSX #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #elif PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #if (PX_LINUX && PX_CLANG) || PX_SWITCH #pragma clang diagnostic pop #endif namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; bool readThrottleResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams); bool writeThrottleResponseParams (const PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readDirectDrivetrainParamsFromJsonFile(const char* directory, const char* filename, const PxVehicleAxleDescription& axleDescription, DirectDrivetrainParams&); bool writeDirectDrivetrainParamsToJsonFile(const char* directory, const char* filename, const PxVehicleAxleDescription& axleDescription, const DirectDrivetrainParams&); }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/SerializationCommon.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "SerializationCommon.h" #include <fstream> #include <sstream> namespace snippetvehicle2 { bool openDocument(const char* directory, const char* filename, rapidjson::Document& document) { // Check the json file exists. std::string fileWithPath(directory); fileWithPath.push_back('/'); fileWithPath.append(filename); std::ifstream inputFile(fileWithPath); if (!inputFile.is_open()) { printf("Opening file \"%s\" failed.\n", fileWithPath.c_str()); return false; } // Check the json file can be loaded by rapidjson. // Failures might be missing commas or braces. std::string inputData{ std::istreambuf_iterator<char>(inputFile), std::istreambuf_iterator<char>() }; document.Parse(inputData.c_str()); inputFile.close(); if (!document.IsObject()) { printf("Parsing file \"%s\" failed.\n", fileWithPath.c_str()); return false; } return true; } bool readCommandResponseParams (const rapidjson::Value& value, const PxVehicleAxleDescription& axleDesc, PxVehicleCommandResponseParams& responseParams) { if (!value.HasMember("MaxResponse")) return false; responseParams.maxResponse = static_cast<PxReal>(value["MaxResponse"].GetDouble()); if (!value.HasMember("WheelResponseMultipliers")) return false; const rapidjson::Value& responseMultipliers = value["WheelResponseMultipliers"]; if (responseMultipliers.Size() < axleDesc.nbWheels) return false; if (responseMultipliers.Size() > PxVehicleLimits::eMAX_NB_WHEELS) return false; for (PxU32 i = 0; i < responseMultipliers.Size(); i++) { responseParams.wheelResponseMultipliers[i] = static_cast<PxReal>(responseMultipliers[i].GetDouble()); } //Nonlinear response is not mandatory. responseParams.nonlinearResponse.clear(); if(!value.HasMember("NonLinearResponse")) return true; const rapidjson::Value& nonlinearResponse = value["NonLinearResponse"]; const int nbCommandValues = nonlinearResponse.Size(); for (int i = 0; i < nbCommandValues; i++) { PxVehicleCommandValueResponseTable commandValueResponse; //Read the throttle value and set it. const rapidjson::Value& commandAndResponse = nonlinearResponse[i]; if (!commandAndResponse.HasMember("Throttle")) return false; const PxReal commandValue = static_cast<PxReal>(commandAndResponse["Throttle"].GetDouble()); commandValueResponse.commandValue = commandValue; //Read the array of (speed, torque) entries. if (!commandAndResponse.HasMember("ResponseCurve")) return false; const rapidjson::Value& torqueCurve = commandAndResponse["ResponseCurve"]; const PxU32 nbItems = torqueCurve.Size(); for (PxU32 j = 0; j < nbItems; j++) { const rapidjson::Value& torqueCurveItem = torqueCurve[j]; if (torqueCurveItem.Size() != 2) return false; const PxReal speed = static_cast<PxReal>(torqueCurveItem[0].GetDouble()); const PxReal normalisedResponse = static_cast<PxReal>(torqueCurveItem[1].GetDouble()); commandValueResponse.speedResponses.addPair(speed, normalisedResponse); } responseParams.nonlinearResponse.addResponse(commandValueResponse); } return true; } bool writeCommandResponseParams (const PxVehicleCommandResponseParams& responseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("MaxResponse"); writer.Double(static_cast<double>(responseParams.maxResponse)); writer.Key("WheelResponseMultipliers"); writer.StartArray(); for(PxU32 i = 0; i < axleDesc.nbWheels; i++) { const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Double(static_cast<double>(responseParams.wheelResponseMultipliers[wheelId])); } writer.EndArray(); writer.Key("ResponseCurve"); writer.StartArray(); for (PxU32 i = 0; i < responseParams.nonlinearResponse.nbCommandValues; i++) { writer.Key("Throttle"); writer.Double(static_cast<double>(responseParams.nonlinearResponse.commandValues[i])); writer.Key("ResponseCurve"); writer.StartArray(); const PxReal* speeds = responseParams.nonlinearResponse.speedResponses + responseParams.nonlinearResponse.speedResponsesPerCommandValue[i]; const PxReal* responses = speeds + responseParams.nonlinearResponse.nbSpeedResponsesPerCommandValue[i]; for (PxU32 j = 0; j < responseParams.nonlinearResponse.nbSpeedResponsesPerCommandValue[i]; j++) { writer.StartArray(); writer.Double(static_cast<double>(speeds[j])); writer.Double(static_cast<double>(responses[j])); writer.EndArray(); } writer.EndArray(); } writer.EndArray(); return true; } void writeCommandResponseParams (const PxVehicleAxleDescription& axleDesc, const PxVehicleCommandResponseParams& throttleResponseParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartObject(); writer.Key("MaxResponse"); writer.Double(static_cast<double>(throttleResponseParams.maxResponse)); writer.Key("WheelResponseMultipliers"); writer.StartArray(); for(PxU32 i = 0; i < axleDesc.nbWheels; i++) { const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Double(static_cast<double>(throttleResponseParams.wheelResponseMultipliers[wheelId])); } writer.EndArray(); writer.EndObject(); } bool readVec3(const rapidjson::Value& values, PxVec3& r) { if (values.Size() != 3) return false; r.x = static_cast<PxReal>(values[0].GetDouble()); r.y = static_cast<PxReal>(values[1].GetDouble()); r.z = static_cast<PxReal>(values[2].GetDouble()); return true; } bool writeVec3(const PxVec3& r, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartArray(); writer.Double(static_cast<double>(r.x)); writer.Double(static_cast<double>(r.y)); writer.Double(static_cast<double>(r.z)); writer.EndArray(); return true; } bool readQuat(const rapidjson::Value& values, PxQuat& r) { if (values.Size() != 4) return false; r.x = static_cast<PxReal>(values[0].GetDouble()); r.y = static_cast<PxReal>(values[1].GetDouble()); r.z = static_cast<PxReal>(values[2].GetDouble()); r.w = static_cast<PxReal>(values[3].GetDouble()); return true; } bool writeQuat(const PxQuat& r, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartArray(); writer.Double(static_cast<double>(r.x)); writer.Double(static_cast<double>(r.y)); writer.Double(static_cast<double>(r.z)); writer.Double(static_cast<double>(r.w)); writer.EndArray(); return true; } bool readTransform(const rapidjson::Value& values, PxTransform& r) { if (!values.HasMember("Pos")) return false; if (!values.HasMember("Quat")) return false; if (!readVec3(values["Pos"], r.p)) return false; if (!readQuat(values["Quat"], r.q)) return false; return true; } bool writeTransform(const PxTransform& r, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartObject(); writer.Key("Pos"); writeVec3(r.p, writer); writer.Key("Quat"); writeQuat(r.q, writer); writer.EndObject(); return true; } template<const PxU32 N> bool readFloatLookupTableN(const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxReal, N>& lookupTable) { lookupTable.clear(); if (values.Size() > N) return false; for (PxU32 i = 0; i < values.Size(); i++) { const rapidjson::Value& element = values[i]; if (element.Size() != 2) return false; const PxReal x = static_cast<PxReal>(values[i][0].GetDouble()); const PxReal y = static_cast<PxReal>(values[i][1].GetDouble()); lookupTable.addPair(x, y); } return true; } bool readFloatLookupTable (const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxReal, 3>& lookupTable) { return readFloatLookupTableN<3>(values, lookupTable); } bool readFloatLookupTable (const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxReal, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>& lookupTable) { return readFloatLookupTableN<PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>(values, lookupTable); } template<const PxU32 N> bool writeFloatLookupTable(const PxVehicleFixedSizeLookupTable<PxReal, N>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartArray(); for (PxU32 i = 0; i < lookupTable.nbDataPairs; i++) { writer.StartArray(); writer.Double(static_cast<double>(lookupTable.xVals[i])); writer.Double(static_cast<double>(lookupTable.yVals[i])); writer.EndArray(); } writer.EndArray(); return true; } bool writeFloatLookupTable(const PxVehicleFixedSizeLookupTable<PxReal, 3>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { return writeFloatLookupTable<3>(lookupTable, writer); } bool writeFloatLookupTable(const PxVehicleFixedSizeLookupTable<PxReal, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { return writeFloatLookupTable<PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>(lookupTable, writer); } bool readVec3LookupTable(const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxVec3, 3>& lookupTable) { lookupTable.clear(); if (values.Size() > 3) return false; for (PxU32 i = 0; i < values.Size(); i++) { const rapidjson::Value& element = values[i]; if (element.Size() != 4) return false; const PxReal x = static_cast<PxReal>(values[i][0].GetDouble()); const PxVec3 y(static_cast<PxReal>( values[i][1].GetDouble()), static_cast<PxReal>(values[i][2].GetDouble()), static_cast<PxReal>(values[i][3].GetDouble())); lookupTable.addPair(x, y); } return true; } bool writeVec3LookupTable(const PxVehicleFixedSizeLookupTable<PxVec3, 3>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.StartArray(); for (PxU32 i = 0; i < lookupTable.nbDataPairs; i++) { writer.StartArray(); writer.Double(static_cast<double>(lookupTable.xVals[i])); writer.Double(static_cast<double>(lookupTable.yVals[i].x)); writer.Double(static_cast<double>(lookupTable.yVals[i].y)); writer.Double(static_cast<double>(lookupTable.yVals[i].z)); writer.EndArray(); } writer.EndArray(); return true; } }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/DirectDrivetrainSerialization.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "DirectDrivetrainSerialization.h" #include "SerializationCommon.h" #include <fstream> #include <sstream> namespace snippetvehicle2 { bool readThrottleResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams) { if (!config.HasMember("ThrottleCommandResponseParams")) return false; if (!readCommandResponseParams(config["ThrottleCommandResponseParams"], axleDesc, throttleResponseParams)) return false; return true; } bool writeThrottleResponseParams (const PxVehicleDirectDriveThrottleCommandResponseParams& throttleResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("ThrottleCommandResponseParams"); writer.StartObject(); writeCommandResponseParams(throttleResponseParams, axleDesc, writer); writer.EndObject(); return true; } bool readDirectDrivetrainParamsFromJsonFile(const char* directory, const char* filename, const PxVehicleAxleDescription& axleDescription, DirectDrivetrainParams& directDrivetrainParams) { rapidjson::Document config; if (!openDocument(directory, filename, config)) return false; if(!readThrottleResponseParams(config, axleDescription, directDrivetrainParams.directDriveThrottleResponseParams)) return false; return true; } bool writeDirectDrivetrainParamsToJsonFile(const char* directory, const char* filename, const PxVehicleAxleDescription& axleDescription, const DirectDrivetrainParams& directDrivetrainParams) { rapidjson::StringBuffer strbuf; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf); writer.StartObject(); writeThrottleResponseParams(directDrivetrainParams.directDriveThrottleResponseParams, axleDescription, writer); writer.EndObject(); std::ofstream myfile; myfile.open(std::string(directory) + "/" + filename); myfile << strbuf.GetString() << std::endl; myfile.close(); return true; } }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/SerializationCommon.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #if PX_SWITCH #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #elif PX_OSX #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #elif PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #if (PX_LINUX && PX_CLANG) || PX_SWITCH || PX_OSX #pragma clang diagnostic pop #endif namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; bool openDocument(const char* directory, const char* filename, rapidjson::Document&); bool readCommandResponseParams (const rapidjson::Value& value, const PxVehicleAxleDescription& axleDesc, PxVehicleCommandResponseParams& responseParams); bool writeCommandResponseParams (const PxVehicleCommandResponseParams& responseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readVec3(const rapidjson::Value& values, PxVec3& r); bool writeVec3(const PxVec3& r, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readQuat(const rapidjson::Value& values, PxQuat& r); bool writeQuat(const PxQuat& r, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readTransform(const rapidjson::Value& values, PxTransform& r); bool writeTransform(const PxTransform& r, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readFloatLookupTable(const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxReal, 3>& lookupTable); bool readFloatLookupTable(const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxReal, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>& lookupTable); bool readVec3LookupTable(const rapidjson::Value& values, PxVehicleFixedSizeLookupTable<PxVec3, 3>& lookupTable); bool writeVec3LookupTable(const PxVehicleFixedSizeLookupTable<PxVec3, 3>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool writeFloatLookupTable(const PxVehicleFixedSizeLookupTable<PxReal, 3>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool writeFloatLookupTable(const PxVehicleFixedSizeLookupTable<PxReal, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES>& lookupTable, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/BaseSerialization.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../base/Base.h" #if PX_SWITCH #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #elif PX_OSX #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #elif PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #if (PX_LINUX && PX_CLANG) || PX_SWITCH #pragma clang diagnostic pop #endif namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; bool readAxleDescription(const rapidjson::Document& config, PxVehicleAxleDescription& axleDesc); bool writeAxleDescription(const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readFrame(const rapidjson::Document& config, PxVehicleFrame& frame); bool writeFrame(const PxVehicleFrame& frame, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readScale(const rapidjson::Document& config, PxVehicleScale& scale); bool writeScale(const PxVehicleScale& scale, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readBrakeResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleBrakeCommandResponseParams& brakeResponseParams); bool writeBrakeResponseParams (const PxVehicleBrakeCommandResponseParams& brakeResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readHandbrakeResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleBrakeCommandResponseParams& handbrakeResponseParams); bool writeHandbrakeResponseParams (const PxVehicleBrakeCommandResponseParams& handrakeResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSteerResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSteerCommandResponseParams& steerResponseParams); bool writeSteerResponseParams (const PxVehicleSteerCommandResponseParams& steerResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readAckermannParams (const rapidjson::Document& config, PxVehicleAckermannParams& ackermannParams); bool writeAckermannParams (const PxVehicleAckermannParams& ackermannParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readRigidBodyParams (const rapidjson::Document& config, PxVehicleRigidBodyParams& rigidBodyParams); bool writeRigidBodyParams (const PxVehicleRigidBodyParams& rigidBodyParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionParams* suspParams); bool writeSuspensionParams (const PxVehicleSuspensionParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionStateCalculationParams (const rapidjson::Document& config, PxVehicleSuspensionStateCalculationParams& suspParams); bool writeSuspensionStateCalculationParams (const PxVehicleSuspensionStateCalculationParams& suspParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionComplianceParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionComplianceParams* suspParams); bool writeSuspensionComplianceParams (const PxVehicleSuspensionComplianceParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionForceParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionForceParams* suspParams); bool writeSuspensionForceParams (const PxVehicleSuspensionForceParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readSuspensionForceLegacyParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionForceLegacyParams* suspParams); bool writeSuspensionForceLegacyParams (const PxVehicleSuspensionForceLegacyParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readTireSlipParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleTireSlipParams* tireParams); bool writeTireSlipParams (const PxVehicleTireSlipParams* tireParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readTireStickyParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleTireStickyParams* tireParams); bool writeTireStickyParams (const PxVehicleTireStickyParams* tireParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readTireForceParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleTireForceParams* tireParams); bool writeTireForceParams (const PxVehicleTireForceParams* tireParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readWheelParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleWheelParams* wheelParams); bool writeWheelParams (const PxVehicleWheelParams* wheelParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readBaseParamsFromJsonFile(const char* directory, const char* filename, BaseVehicleParams&); bool writeBaseParamsToJsonFile(const char* directory, const char* filename, const BaseVehicleParams&); }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/EngineDrivetrainSerialization.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "EngineDrivetrainSerialization.h" #include "SerializationCommon.h" #include <fstream> #include <sstream> namespace snippetvehicle2 { bool readAutoboxParams(const rapidjson::Document& config, PxVehicleAutoboxParams& autoboxParams) { if(!config.HasMember("AutoboxParams")) return false; if(!config["AutoboxParams"].HasMember("UpRatios")) return false; if (!config["AutoboxParams"].HasMember("DownRatios")) return false; if (!config["AutoboxParams"].HasMember("Latency")) return false; const rapidjson::Value& upRatios = config["AutoboxParams"]["UpRatios"]; for(PxU32 i = 0; i < upRatios.Size(); i++) { autoboxParams.upRatios[i] = static_cast<PxReal>(upRatios[i].GetDouble()); } const rapidjson::Value& downRatios = config["AutoboxParams"]["DownRatios"]; for (PxU32 i = 0; i < downRatios.Size(); i++) { autoboxParams.downRatios[i] = static_cast<PxReal>(downRatios[i].GetDouble()); } autoboxParams.latency = static_cast<PxReal>(config["AutoboxParams"]["Latency"].GetDouble()); return true; } bool writeAutoboxParams(const PxVehicleAutoboxParams& autoboxParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("AutoboxParams"); writer.StartObject(); writer.Key("UpRatios"); writer.StartArray(); for(PxU32 i = 0; i < PxVehicleGearboxParams::eMAX_NB_GEARS; i++) { writer.Double(static_cast<double>(autoboxParams.upRatios[i])); } writer.EndArray(); writer.Key("DownRatios"); writer.StartArray(); for (PxU32 i = 0; i < PxVehicleGearboxParams::eMAX_NB_GEARS; i++) { writer.Double(static_cast<double>(autoboxParams.downRatios[i])); } writer.EndArray(); writer.Key("Latency"); writer.Double(static_cast<double>(autoboxParams.latency)); writer.EndObject(); return true; } bool readClutchCommandResponseParams(const rapidjson::Document& config, PxVehicleClutchCommandResponseParams& clutchCommandResponseParams) { if(!config.HasMember("ClutchCommandResponseParams")) return false; if(!config["ClutchCommandResponseParams"].HasMember("MaxResponse")) return false; clutchCommandResponseParams.maxResponse = static_cast<PxReal>(config["ClutchCommandResponseParams"]["MaxResponse"].GetDouble()); return true; } bool writeClutchCommandResponseParams(const PxVehicleClutchCommandResponseParams& clutchCommandResponseParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("ClutchCommandResponseParams"); writer.StartObject(); writer.Key("MaxResponse"); writer.Double(static_cast<double>(clutchCommandResponseParams.maxResponse)); writer.EndObject(); return true; } bool readEngineParams(const rapidjson::Document& config, PxVehicleEngineParams& engineParams) { if(!config.HasMember("EngineParams")) return false; if(!config["EngineParams"].HasMember("TorqueCurve")) return false; if (!config["EngineParams"].HasMember("MOI")) return false; if (!config["EngineParams"].HasMember("PeakTorque")) return false; if (!config["EngineParams"].HasMember("IdleOmega")) return false; if (!config["EngineParams"].HasMember("MaxOmega")) return false; if (!config["EngineParams"].HasMember("DampingRateFullThrottle")) return false; if (!config["EngineParams"].HasMember("DampingRateZeroThrottleClutchEngaged")) return false; if (!config["EngineParams"].HasMember("DampingRateZeroThrottleClutchDisengaged")) return false; if(!readFloatLookupTable(config["EngineParams"]["TorqueCurve"], engineParams.torqueCurve)) return false; engineParams.moi = static_cast<PxReal>(config["EngineParams"]["MOI"].GetDouble()); engineParams.peakTorque = static_cast<PxReal>(config["EngineParams"]["PeakTorque"].GetDouble()); engineParams.idleOmega = static_cast<PxReal>(config["EngineParams"]["IdleOmega"].GetDouble()); engineParams.maxOmega = static_cast<PxReal>(config["EngineParams"]["MaxOmega"].GetDouble()); engineParams.dampingRateFullThrottle = static_cast<PxReal>(config["EngineParams"]["DampingRateFullThrottle"].GetDouble()); engineParams.dampingRateZeroThrottleClutchEngaged = static_cast<PxReal>(config["EngineParams"]["DampingRateZeroThrottleClutchEngaged"].GetDouble()); engineParams.dampingRateZeroThrottleClutchDisengaged = static_cast<PxReal>(config["EngineParams"]["DampingRateZeroThrottleClutchDisengaged"].GetDouble()); return true; } bool writeEngineParams(const PxVehicleEngineParams& engineParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("EngineParams"); writer.StartObject(); writer.Key("TorqueCurve"); writeFloatLookupTable(engineParams.torqueCurve, writer); writer.Key("MOI"); writer.Double(static_cast<double>(engineParams.moi)); writer.Key("PeakTorque"); writer.Double(static_cast<double>(engineParams.peakTorque)); writer.Key("IdleOmega"); writer.Double(static_cast<double>(engineParams.idleOmega)); writer.Key("MaxOmega"); writer.Double(static_cast<double>(engineParams.maxOmega)); writer.Key("DampingRateFullThrottle"); writer.Double(static_cast<double>(engineParams.dampingRateFullThrottle)); writer.Key("DampingRateZeroThrottleClutchEngaged"); writer.Double(double(engineParams.dampingRateZeroThrottleClutchEngaged)); writer.Key("DampingRateZeroThrottleClutchDisengaged"); writer.Double(double(engineParams.dampingRateZeroThrottleClutchDisengaged)); writer.EndObject(); return true; } bool readGearboxParams(const rapidjson::Document& config, PxVehicleGearboxParams& gearboxParams) { if (!config.HasMember("GearboxParams")) return false; if (!config["GearboxParams"].HasMember("NeutralGear")) return false; if (!config["GearboxParams"].HasMember("Ratios")) return false; if (!config["GearboxParams"].HasMember("FinalRatio")) return false; if (!config["GearboxParams"].HasMember("SwitchTime")) return false; gearboxParams.neutralGear = config["GearboxParams"]["NeutralGear"].GetInt(); gearboxParams.finalRatio = static_cast<PxReal>(config["GearboxParams"]["FinalRatio"].GetDouble()); gearboxParams.switchTime = static_cast<PxReal>(config["GearboxParams"]["SwitchTime"].GetDouble()); const rapidjson::Value& ratios = config["GearboxParams"]["Ratios"]; for(PxU32 i = 0; i < ratios.Size(); i++) { gearboxParams.ratios[i] = static_cast<PxReal>(ratios[i].GetDouble()); } gearboxParams.nbRatios = ratios.Size(); return true; } bool writeGearboxParams(const PxVehicleGearboxParams& gearboxParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("GearboxParams"); writer.StartObject(); writer.Key("NeutralGear"); writer.Int(gearboxParams.neutralGear); writer.Key("FinalRatio"); writer.Double(static_cast<double>(gearboxParams.finalRatio)); writer.Key("SwitchTime"); writer.Double(static_cast<double>(gearboxParams.switchTime)); writer.Key("Ratios"); writer.StartArray(); for(PxU32 i = 0; i < gearboxParams.nbRatios; i++) { writer.Double(static_cast<double>(gearboxParams.ratios[i])); } writer.EndArray(); writer.EndObject(); return true; } bool readMultiWheelDiffParams(const rapidjson::Value& config, PxVehicleMultiWheelDriveDifferentialParams& multiWheelDiffParams) { if (!config.HasMember("TorqueRatios")) return false; if (!config.HasMember("AveWheelSpeedRatios")) return false; const rapidjson::Value& aveWheelSpeedRatios = config["AveWheelSpeedRatios"]; const rapidjson::Value& torqueRatios = config["TorqueRatios"]; if (aveWheelSpeedRatios.Size() != torqueRatios.Size()) return false; for (PxU32 i = 0; i < aveWheelSpeedRatios.Size(); i++) { multiWheelDiffParams.aveWheelSpeedRatios[i] = static_cast<PxReal>(aveWheelSpeedRatios[i].GetDouble()); multiWheelDiffParams.torqueRatios[i] = static_cast<PxReal>(torqueRatios[i].GetDouble()); } return true; } void writeMultiWheelDiffParams (const PxVehicleMultiWheelDriveDifferentialParams& multiWheelDiffParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("TorqueRatios"); writer.StartArray(); for (PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++) { writer.Double(static_cast<double>(multiWheelDiffParams.torqueRatios[i])); } writer.EndArray(); writer.Key("AveWheelSpeedRatios"); writer.StartArray(); for (PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++) { writer.Double(static_cast<double>(multiWheelDiffParams.aveWheelSpeedRatios[i])); } writer.EndArray(); } bool readMultiWheelDifferentialParams(const rapidjson::Document& config, PxVehicleMultiWheelDriveDifferentialParams& multiWheelDifferentialParams) { multiWheelDifferentialParams.setToDefault(); if (!config.HasMember("MultiWheelDifferentialParams")) return false; if (!readMultiWheelDiffParams(config["MultiWheelDifferentialParams"], multiWheelDifferentialParams)) return false; return true; } bool writeMultiWheelDifferentialParams (const PxVehicleMultiWheelDriveDifferentialParams& multiWheelDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("MultiWheelDifferentialParams"); writer.StartObject(); writeMultiWheelDiffParams(multiWheelDifferentialParams, writer); writer.EndObject(); return true; } bool readFourWheelDifferentialParams(const rapidjson::Document& config, PxVehicleFourWheelDriveDifferentialParams& fourWheelDifferentialParams) { fourWheelDifferentialParams.setToDefault(); if (!config.HasMember("FourWheelDifferentialParams")) return false; if (!readMultiWheelDiffParams(config["FourWheelDifferentialParams"], static_cast<PxVehicleMultiWheelDriveDifferentialParams&>(fourWheelDifferentialParams))) return false; if (!config["FourWheelDifferentialParams"].HasMember("FrontWheelIds")) return false; if (!config["FourWheelDifferentialParams"].HasMember("RearWheelIds")) return false; if (!config["FourWheelDifferentialParams"].HasMember("CenterBias")) return false; if (!config["FourWheelDifferentialParams"].HasMember("CenterTarget")) return false; if (!config["FourWheelDifferentialParams"].HasMember("FrontBias")) return false; if (!config["FourWheelDifferentialParams"].HasMember("FrontTarget")) return false; if (!config["FourWheelDifferentialParams"].HasMember("RearBias")) return false; if (!config["FourWheelDifferentialParams"].HasMember("RearTarget")) return false; if (!config["FourWheelDifferentialParams"].HasMember("Rate")) return false; const rapidjson::Value& frontWheelIds = config["FourWheelDifferentialParams"]["FrontWheelIds"]; if(frontWheelIds.Size() != 2) return false; fourWheelDifferentialParams.frontWheelIds[0] = frontWheelIds[0].GetInt(); fourWheelDifferentialParams.frontWheelIds[1] = frontWheelIds[1].GetInt(); const rapidjson::Value& rearWheelIds = config["FourWheelDifferentialParams"]["RearWheelIds"]; if (rearWheelIds.Size() != 2) return false; fourWheelDifferentialParams.rearWheelIds[0] = rearWheelIds[0].GetInt(); fourWheelDifferentialParams.rearWheelIds[1] = rearWheelIds[1].GetInt(); fourWheelDifferentialParams.centerBias = static_cast<PxReal>(config["FourWheelDifferentialParams"]["CenterBias"].GetDouble()); fourWheelDifferentialParams.centerTarget = static_cast<PxReal>(config["FourWheelDifferentialParams"]["CenterTarget"].GetDouble()); fourWheelDifferentialParams.frontBias = static_cast<PxReal>(config["FourWheelDifferentialParams"]["FrontBias"].GetDouble()); fourWheelDifferentialParams.frontTarget = static_cast<PxReal>(config["FourWheelDifferentialParams"]["FrontTarget"].GetDouble()); fourWheelDifferentialParams.rearBias = static_cast<PxReal>(config["FourWheelDifferentialParams"]["RearBias"].GetDouble()); fourWheelDifferentialParams.rearTarget = static_cast<PxReal>(config["FourWheelDifferentialParams"]["RearTarget"].GetDouble()); fourWheelDifferentialParams.rate = static_cast<PxReal>(config["FourWheelDifferentialParams"]["Rate"].GetDouble()); return true; } bool writeFourWheelDifferentialParams(const PxVehicleFourWheelDriveDifferentialParams& fourWheelDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("FourWheelDifferentialParams"); writer.StartObject(); writeMultiWheelDiffParams(static_cast<const PxVehicleMultiWheelDriveDifferentialParams&>(fourWheelDifferentialParams), writer); writer.Key("FrontWheelIds"); writer.StartArray(); writer.Int(fourWheelDifferentialParams.frontWheelIds[0]); writer.Int(fourWheelDifferentialParams.frontWheelIds[1]); writer.EndArray(); writer.Key("RearWheelIds"); writer.StartArray(); writer.Int(fourWheelDifferentialParams.rearWheelIds[0]); writer.Int(fourWheelDifferentialParams.rearWheelIds[1]); writer.EndArray(); writer.Key("CenterBias"); writer.Double(static_cast<double>(fourWheelDifferentialParams.centerBias)); writer.Key("CenterTarget"); writer.Double(static_cast<double>(fourWheelDifferentialParams.centerTarget)); writer.Key("FrontBias"); writer.Double(static_cast<double>(fourWheelDifferentialParams.frontBias)); writer.Key("FrontTarget"); writer.Double(static_cast<double>(fourWheelDifferentialParams.frontTarget)); writer.Key("RearBias"); writer.Double(static_cast<double>(fourWheelDifferentialParams.rearBias)); writer.Key("RearTarget"); writer.Double(static_cast<double>(fourWheelDifferentialParams.rearTarget)); writer.Key("Rate"); writer.Double(static_cast<double>(fourWheelDifferentialParams.rate)); writer.EndObject(); return true; } bool readTankDifferentialParams(const rapidjson::Document& config, PxVehicleTankDriveDifferentialParams& tankDifferentialParams) { tankDifferentialParams.setToDefault(); if (!config.HasMember("TankDifferentialParams")) return false; if(!readMultiWheelDiffParams(config["TankDifferentialParams"], static_cast<PxVehicleMultiWheelDriveDifferentialParams&>(tankDifferentialParams))) return false; if (!config["TankDifferentialParams"].HasMember("TankTracks")) return false; const rapidjson::Value& tankTracks = config["TankDifferentialParams"]["TankTracks"]; for (PxU32 i = 0; i < tankTracks.Size(); i++) { const rapidjson::Value& tankTrack = tankTracks[i]; PxU32 wheelIds[PxVehicleLimits::eMAX_NB_WHEELS]; PxU32 nbWheels = 0; for (PxU32 j = 0; j < tankTrack.Size(); j++) { wheelIds[nbWheels] = static_cast<PxU32>(tankTrack[j].GetInt()); nbWheels++; } tankDifferentialParams.addTankTrack(nbWheels, wheelIds, i); } return true; } bool writeTankDifferentialParams(const PxVehicleTankDriveDifferentialParams& tankDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("TankDifferentialParams"); writer.StartObject(); writeMultiWheelDiffParams(static_cast<const PxVehicleMultiWheelDriveDifferentialParams&>(tankDifferentialParams), writer); writer.Key("TankTracks"); writer.StartArray(); for (PxU32 i = 0; i < tankDifferentialParams.nbTracks; i++) { writer.StartArray(); for (PxU32 j = 0; j < tankDifferentialParams.getNbWheelsInTrack(i); j++) { writer.Int(static_cast<int>(tankDifferentialParams.getWheelInTrack(j, i))); } writer.EndArray(); } writer.EndArray(); writer.EndObject(); return true; } bool reaClutchParams(const rapidjson::Document& config, PxVehicleClutchParams& clutchParams) { if (!config.HasMember("ClutchParams")) return false; if (!config["ClutchParams"].HasMember("AccuracyMode")) return false; if (!config["ClutchParams"].HasMember("EstimateIterations")) return false; clutchParams.accuracyMode = static_cast<PxVehicleClutchAccuracyMode::Enum>(config["ClutchParams"]["AccuracyMode"].GetInt()); clutchParams.estimateIterations = config["ClutchParams"]["EstimateIterations"].GetInt(); return true; } bool writeClutchParams(const PxVehicleClutchParams& clutchParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("ClutchParams"); writer.StartObject(); writer.Key("AccuracyMode"); writer.Int(static_cast<PxU32>(clutchParams.accuracyMode)); writer.Key("EstimateIterations"); writer.Int(clutchParams.estimateIterations); writer.EndObject(); return true; } bool readEngineDrivetrainParamsFromJsonFile(const char* directory, const char* filename, EngineDrivetrainParams& engineDrivetrainParams) { rapidjson::Document config; if (!openDocument(directory, filename, config)) return false; if(!readAutoboxParams(config, engineDrivetrainParams.autoboxParams)) return false; if(!readClutchCommandResponseParams(config, engineDrivetrainParams.clutchCommandResponseParams)) return false; if (!readEngineParams(config, engineDrivetrainParams.engineParams)) return false; if (!readGearboxParams(config, engineDrivetrainParams.gearBoxParams)) return false; if (!readMultiWheelDifferentialParams(config, engineDrivetrainParams.multiWheelDifferentialParams)) return false; if (!readFourWheelDifferentialParams(config, engineDrivetrainParams.fourWheelDifferentialParams)) return false; if (!readTankDifferentialParams(config, engineDrivetrainParams.tankDifferentialParams)) return false; if (!reaClutchParams(config, engineDrivetrainParams.clutchParams)) return false; return true; } bool writeEngineDrivetrainParamsToJsonFile(const char* directory, const char* filename, const EngineDrivetrainParams& engineDrivetrainParams) { rapidjson::StringBuffer strbuf; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf); writer.StartObject(); writeAutoboxParams(engineDrivetrainParams.autoboxParams, writer); writeClutchCommandResponseParams(engineDrivetrainParams.clutchCommandResponseParams, writer); writeEngineParams(engineDrivetrainParams.engineParams, writer); writeGearboxParams(engineDrivetrainParams.gearBoxParams, writer); writeMultiWheelDifferentialParams(engineDrivetrainParams.multiWheelDifferentialParams, writer); writeFourWheelDifferentialParams(engineDrivetrainParams.fourWheelDifferentialParams, writer); writeTankDifferentialParams(engineDrivetrainParams.tankDifferentialParams, writer); writeClutchParams(engineDrivetrainParams.clutchParams, writer); writer.EndObject(); std::ofstream myfile; myfile.open(std::string(directory) + "/" + filename); myfile << strbuf.GetString() << std::endl; myfile.close(); return true; } }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/EngineDrivetrainSerialization.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "vehicle2/PxVehicleAPI.h" #include "../enginedrivetrain/EngineDrivetrain.h" #if PX_SWITCH #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #elif PX_OSX #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexpansion-to-defined" #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #elif PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #endif #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #if (PX_LINUX && PX_CLANG) || PX_SWITCH #pragma clang diagnostic pop #endif namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; bool readAutoboxParams(const rapidjson::Document& config, PxVehicleAutoboxParams& autoboxParams); bool writeAutoboxParams(const PxVehicleAutoboxParams& autoboxParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readClutchCommandResponseParams(const rapidjson::Document& config, PxVehicleClutchCommandResponseParams& clutchCommandResponseParams); bool writeClutchCommandResponseParams(const PxVehicleClutchCommandResponseParams& clutchCommandResponseParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readEngineParams(const rapidjson::Document& config, PxVehicleEngineParams& engineParams); bool writeEngineParams(const PxVehicleEngineParams& engineParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readGearboxParams(const rapidjson::Document& config, PxVehicleGearboxParams& gearboxParams); bool writeGearboxParams(const PxVehicleGearboxParams& gearboxParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readFourWheelDifferentialParams(const rapidjson::Document& config, PxVehicleFourWheelDriveDifferentialParams& fourWheelDifferentialParams); bool writeFourWheelDifferentialParams(const PxVehicleFourWheelDriveDifferentialParams& fourWheelDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readMultiWheelDifferentialParams(const rapidjson::Document& config, PxVehicleMultiWheelDriveDifferentialParams& multiWheelDifferentialParams); bool writeMultiWheelDifferentialParams(const PxVehicleMultiWheelDriveDifferentialParams& multiWheelDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readTankDifferentialParams(const rapidjson::Document& config, PxVehicleTankDriveDifferentialParams& tankDifferentialParams); bool writeTankDifferentialParams(const PxVehicleTankDriveDifferentialParams& tankDifferentialParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool reaClutchParams(const rapidjson::Document& config, PxVehicleClutchParams& clutchParams); bool writeClutchParams(const PxVehicleClutchParams& clutchParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer); bool readEngineDrivetrainParamsFromJsonFile(const char* directory, const char* filename, EngineDrivetrainParams&); bool writeEngineDrivetrainParamsToJsonFile(const char* directory, const char* filename, const EngineDrivetrainParams&); }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2common/serialization/BaseSerialization.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "BaseSerialization.h" #include "SerializationCommon.h" #include <fstream> #include <sstream> namespace snippetvehicle2 { bool readAxleDescription(const rapidjson::Document& config, PxVehicleAxleDescription& axleDesc) { if (!config.HasMember("AxleDescription")) return false; const PxU32 nbAxles = config["AxleDescription"].Size(); if (nbAxles > PxVehicleLimits::eMAX_NB_AXLES) return false; axleDesc.setToDefault(); //Read each axle in turn. for (PxU32 i = 0; i < nbAxles; i++) { const rapidjson::Value& axle = config["AxleDescription"][i]; if (!axle.HasMember("WheelIds")) return false; const rapidjson::Value& wheelIds = axle["WheelIds"]; const PxU32 nbWheelIds = wheelIds.Size(); if(nbWheelIds > PxVehicleLimits::eMAX_NB_WHEELS) return false; PxU32 axleWheelIds[PxVehicleLimits::eMAX_NB_WHEELS]; for (PxU32 j = 0; j < nbWheelIds; j++) { axleWheelIds[j]= wheelIds[j].GetInt(); } axleDesc.addAxle(nbWheelIds, axleWheelIds); } return true; } bool writeAxleDescription(const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("AxleDescription"); writer.StartArray(); for(PxU32 i = 0; i < axleDesc.getNbAxles(); i++) { writer.StartObject(); writer.Key("WheelIds"); writer.StartArray(); for(PxU32 j = 0; j < axleDesc.getNbWheelsOnAxle(i); j++) { writer.Int(axleDesc.getWheelOnAxle(j, i)); } writer.EndArray(); writer.EndObject(); } writer.EndArray(); return true; } bool readFrame(const rapidjson::Document& config, PxVehicleFrame& frame) { if (!config.HasMember("Frame")) return false; if (!config["Frame"].HasMember("LngAxis")) return false; if (!config["Frame"].HasMember("LatAxis")) return false; if (!config["Frame"].HasMember("VrtAxis")) return false; const PxU32 lngAxis = config["Frame"]["LngAxis"].GetInt(); const PxU32 latAxis = config["Frame"]["LatAxis"].GetInt(); const PxU32 vrtAxis = config["Frame"]["VrtAxis"].GetInt(); if ((lngAxis == latAxis) || (lngAxis == vrtAxis) || (latAxis == vrtAxis)) { return false; } frame.lngAxis = static_cast<PxVehicleAxes::Enum>(lngAxis); frame.latAxis = static_cast<PxVehicleAxes::Enum>(latAxis); frame.vrtAxis = static_cast<PxVehicleAxes::Enum>(vrtAxis); return true; } bool writeFrame(const PxVehicleFrame& frame, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("Frame"); writer.StartObject(); writer.Key("LngAxis"); writer.Int(static_cast<PxU32>(frame.lngAxis)); writer.Key("LatAxis"); writer.Int(static_cast<PxU32>(frame.latAxis)); writer.Key("VrtAxis"); writer.Int(static_cast<PxU32>(frame.vrtAxis)); writer.EndObject(); return true; } bool readScale(const rapidjson::Document& config, PxVehicleScale& scale) { if (!config.HasMember("Scale")) return false; if (!config["Scale"].HasMember("Scale")) return false; scale.scale = static_cast<PxReal>(config["Scale"]["Scale"].GetDouble()); return true; } bool writeScale(const PxVehicleScale& scale, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("Scale"); writer.StartObject(); writer.Key("Scale"); writer.Double(static_cast<double>(scale.scale)); writer.EndObject(); return true; } bool readBrakeResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleBrakeCommandResponseParams& brakeResponseParams) { if (!config.HasMember("BrakeCommandResponseParams")) return false; if (!readCommandResponseParams(config["BrakeCommandResponseParams"], axleDesc, brakeResponseParams)) return false; return true; } bool writeBrakeResponseParams (const PxVehicleBrakeCommandResponseParams& brakeResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("BrakeCommandResponseParams"); writer.StartObject(); writeCommandResponseParams(brakeResponseParams, axleDesc, writer); writer.EndObject(); return true; } bool readHandbrakeResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleBrakeCommandResponseParams& handbrakeResponseParams) { if (!config.HasMember("HandbrakeCommandResponseParams")) return false; if (!readCommandResponseParams(config["HandbrakeCommandResponseParams"], axleDesc, handbrakeResponseParams)) return false; return true; } bool writeHandbrakeResponseParams (const PxVehicleBrakeCommandResponseParams& handrakeResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("HandbrakeCommandResponseParams"); writer.StartObject(); writeCommandResponseParams(handrakeResponseParams, axleDesc, writer); writer.EndObject(); return true; } bool readSteerResponseParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSteerCommandResponseParams& steerResponseParams) { if (!config.HasMember("SteerCommandResponseParams")) return false; if (!readCommandResponseParams(config["SteerCommandResponseParams"], axleDesc, steerResponseParams)) return false; return true; } bool writeSteerResponseParams (const PxVehicleSteerCommandResponseParams& steerResponseParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SteerCommandResponseParams"); writer.StartObject(); writeCommandResponseParams(steerResponseParams, axleDesc, writer); writer.EndObject(); return true; } bool readAckermannParams(const rapidjson::Document& config, PxVehicleAckermannParams& ackermannParams) { if (!config.HasMember("AckermannParams")) return false; const rapidjson::Value& corrections = config["AckermannParams"]; if (!corrections.HasMember("WheelBase")) return false; if (!corrections.HasMember("TrackWidth")) return false; if (!corrections.HasMember("Strength")) return false; ackermannParams.wheelBase = static_cast<PxReal>(corrections["WheelBase"].GetDouble()); ackermannParams.trackWidth = static_cast<PxReal>(corrections["TrackWidth"].GetDouble()); ackermannParams.strength = static_cast<PxReal>(corrections["Strength"].GetDouble()); if (!corrections.HasMember("WheelIds")) return false; const rapidjson::Value& wheelIds = corrections["WheelIds"]; const PxU32 nbWheelIds = wheelIds.Size(); if (nbWheelIds != 2) return false; for (PxU32 j = 0; j < 2; j++) { ackermannParams.wheelIds[j] = wheelIds[j].GetInt(); } return true; } bool writeAckermannParams(const PxVehicleAckermannParams& ackermannParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("AckermannParams"); writer.StartObject(); writer.Key("WheelIds"); writer.StartArray(); writer.Int(ackermannParams.wheelIds[0]); writer.Int(ackermannParams.wheelIds[1]); writer.EndArray(); writer.Key("WheelBase"); writer.Double(static_cast<double>(ackermannParams.wheelBase)); writer.Key("TrackWidth"); writer.Double(static_cast<double>(ackermannParams.trackWidth)); writer.Key("Strength"); writer.Double(static_cast<double>(ackermannParams.strength)); writer.EndObject(); return true; } bool readRigidBodyParams (const rapidjson::Document& config, PxVehicleRigidBodyParams& rigidBodyParams) { if (!config.HasMember("RigidBodyParams")) return false; if (!config["RigidBodyParams"].HasMember("Mass")) return false; if (!config["RigidBodyParams"].HasMember("MOI")) return false; rigidBodyParams.mass = static_cast<PxReal>(config["RigidBodyParams"]["Mass"].GetDouble()); if (!readVec3(config["RigidBodyParams"]["MOI"], rigidBodyParams.moi)) return false; return true; } bool writeRigidBodyParams (const PxVehicleRigidBodyParams& rigidBodyParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("RigidBodyParams"); writer.StartObject(); writer.Key("Mass"); writer.Double(static_cast<double>(rigidBodyParams.mass)); writer.Key("MOI"); writeVec3(rigidBodyParams.moi, writer); writer.EndObject(); return true; } bool readSuspensionParams(const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionParams* suspParams) { if (!config.HasMember("SuspensionParams")) return false; const rapidjson::Value& suspensions = config["SuspensionParams"]; const PxU32 nbSuspensions = suspensions.Size(); if (nbSuspensions != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbSuspensions; i++) { if(!suspensions[i].HasMember("WheelId")) return false; if (!suspensions[i].HasMember("SuspensionAttachment")) return false; if (!suspensions[i].HasMember("SuspensionTravelDir")) return false; if (!suspensions[i].HasMember("SuspensionTravelDist")) return false; if (!suspensions[i].HasMember("WheelAttachment")) return false; const PxU32 wheelId = suspensions[i]["WheelId"].GetInt(); PxVehicleSuspensionParams& sp = suspParams[wheelId]; if (!readTransform(suspensions[i]["SuspensionAttachment"], sp.suspensionAttachment)) return false; if (!readVec3(suspensions[i]["SuspensionTravelDir"], sp.suspensionTravelDir)) return false; sp.suspensionTravelDist = static_cast<PxReal>(suspensions[i]["SuspensionTravelDist"].GetDouble()); if (!readTransform(suspensions[i]["WheelAttachment"], sp.wheelAttachment)) return false; } return true; } bool writeSuspensionParams(const PxVehicleSuspensionParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SuspensionParams"); writer.StartArray(); for(PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("SuspensionAttachment"); writeTransform(suspParams[wheelId].suspensionAttachment, writer); writer.Key("SuspensionTravelDir"); writeVec3(suspParams[wheelId].suspensionTravelDir, writer); writer.Key("SuspensionTravelDist"); writer.Double(static_cast<double>(suspParams[wheelId].suspensionTravelDist)); writer.Key("WheelAttachment"); writeTransform(suspParams[wheelId].wheelAttachment, writer); writer.EndObject(); } writer.EndArray(); return true; } static const char* kLimitSuspensionExpansionVelocity = "LimitSuspensionExpansionVelocity"; bool readSuspensionStateCalculationParams(const rapidjson::Document& config, PxVehicleSuspensionStateCalculationParams& suspParams) { if (!config.HasMember("SuspensionStateCalculationParams")) return false; const rapidjson::Value& suspCalcParams = config["SuspensionStateCalculationParams"]; if (!suspCalcParams.HasMember("JounceCalculationType")) return false; if (!suspCalcParams.HasMember(kLimitSuspensionExpansionVelocity)) return false; suspParams.suspensionJounceCalculationType = static_cast<PxVehicleSuspensionJounceCalculationType::Enum>(suspCalcParams["JounceCalculationType"].GetInt()); suspParams.limitSuspensionExpansionVelocity = suspCalcParams[kLimitSuspensionExpansionVelocity].GetBool(); return true; } bool writeSuspensionStateCalculationParams (const PxVehicleSuspensionStateCalculationParams& suspParams, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SuspensionStateCalculationParams"); writer.StartObject(); writer.Key("JounceCalculationType"); writer.Int(static_cast<PxU32>(suspParams.suspensionJounceCalculationType)); writer.Key(kLimitSuspensionExpansionVelocity); writer.Bool(suspParams.limitSuspensionExpansionVelocity); writer.EndObject(); return true; } bool readSuspensionComplianceParams(const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionComplianceParams* suspCompParams) { if (!config.HasMember("SuspensionComplianceParams")) return false; const rapidjson::Value& suspensions = config["SuspensionComplianceParams"]; const PxU32 nbSuspensions = suspensions.Size(); if (nbSuspensions != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbSuspensions; i++) { if (!suspensions[i].HasMember("WheelId")) return false; if (!suspensions[i].HasMember("WheelToeAngle")) return false; if (!suspensions[i].HasMember("WheelCamberAngle")) return false; if (!suspensions[i].HasMember("SuspForceAppPoint")) return false; if (!suspensions[i].HasMember("SuspForceAppPoint")) return false; const PxU32 wheelId = suspensions[i]["WheelId"].GetInt(); if (!readFloatLookupTable(suspensions[i]["WheelToeAngle"], suspCompParams[wheelId].wheelToeAngle)) return false; if (!readFloatLookupTable(suspensions[i]["WheelCamberAngle"], suspCompParams[wheelId].wheelCamberAngle)) return false; if (!readVec3LookupTable(suspensions[i]["SuspForceAppPoint"], suspCompParams[wheelId].suspForceAppPoint)) return false; if (!readVec3LookupTable(suspensions[i]["TireForceAppPoint"], suspCompParams[wheelId].tireForceAppPoint)) return false; } return true; } bool writeSuspensionComplianceParams (const PxVehicleSuspensionComplianceParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SuspensionComplianceParams"); writer.StartArray(); for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("WheelToeAngle"); writeFloatLookupTable(suspParams[wheelId].wheelToeAngle, writer); writer.Key("WheelCamberAngle"); writeFloatLookupTable(suspParams[wheelId].wheelCamberAngle, writer); writer.Key("SuspForceAppPoint"); writeVec3LookupTable(suspParams[wheelId].suspForceAppPoint, writer); writer.Key("TireForceAppPoint"); writeVec3LookupTable(suspParams[wheelId].tireForceAppPoint, writer); writer.EndObject(); } writer.EndArray(); return true; } bool readSuspensionForceParams(const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleSuspensionForceParams* suspParams) { if (!config.HasMember("SuspensionForceParams")) return false; const rapidjson::Value& suspensions = config["SuspensionForceParams"]; const PxU32 nbSuspensions = suspensions.Size(); if (nbSuspensions != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbSuspensions; i++) { if (!suspensions[i].HasMember("WheelId")) return false; if (!suspensions[i].HasMember("Damping")) return false; if (!suspensions[i].HasMember("Stiffness")) return false; if (!suspensions[i].HasMember("SprungMass")) return false; const PxU32 wheelId = suspensions[i]["WheelId"].GetInt(); suspParams[wheelId].damping = static_cast<PxReal>(suspensions[i]["Damping"].GetDouble()); suspParams[wheelId].stiffness = static_cast<PxReal>(suspensions[i]["Stiffness"].GetDouble()); suspParams[wheelId].sprungMass = static_cast<PxReal>(suspensions[i]["SprungMass"].GetDouble()); } return true; } bool writeSuspensionForceParams (const PxVehicleSuspensionForceParams* suspParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("SuspensionForceParams"); writer.StartArray(); for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("Damping"); writer.Double(double(suspParams[wheelId].damping)); writer.Key("Stiffness"); writer.Double(double(suspParams[wheelId].stiffness)); writer.Key("SprungMass"); writer.Double(double(suspParams[wheelId].sprungMass)); writer.EndObject(); } writer.EndArray(); return true; } bool readTireForceParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleTireForceParams* tireParams) { if (!config.HasMember("TireForceParams")) return false; const rapidjson::Value& tires = config["TireForceParams"]; const PxU32 nbTires = tires.Size(); if (nbTires != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbTires; i++) { if (!tires[i].HasMember("WheelId")) return false; if (!tires[i].HasMember("LongitudinalStiffness")) return false; if (!tires[i].HasMember("LateralStiffnessX")) return false; if (!tires[i].HasMember("LateralStiffnessY")) return false; if (!tires[i].HasMember("CamberStiffness")) return false; if (!tires[i].HasMember("RestLoad")) return false; if (!tires[i].HasMember("FrictionVsSlip")) return false; if (!tires[i].HasMember("TireLoadFilter")) return false; const PxU32 wheelId = tires[i]["WheelId"].GetInt(); tireParams[wheelId].longStiff = static_cast<PxReal>(tires[i]["LongitudinalStiffness"].GetDouble()); tireParams[wheelId].latStiffX = static_cast<PxReal>(tires[i]["LateralStiffnessX"].GetDouble()); tireParams[wheelId].latStiffY = static_cast<PxReal>(tires[i]["LateralStiffnessY"].GetDouble()); tireParams[wheelId].camberStiff = static_cast<PxReal>(tires[i]["CamberStiffness"].GetDouble()); tireParams[wheelId].restLoad = static_cast<PxReal>(tires[i]["RestLoad"].GetDouble()); const rapidjson::Value& frictionVsSlip = tires[i]["FrictionVsSlip"]; if (frictionVsSlip.Size() != 3) return false; for (PxU32 j = 0; j < 3; j++) { const rapidjson::Value& element = tires[i]["FrictionVsSlip"][j]; if (element.Size() != 2) return false; tireParams[wheelId].frictionVsSlip[j][0] = static_cast<PxReal>(element[0].GetDouble()); tireParams[wheelId].frictionVsSlip[j][1] = static_cast<PxReal>(element[1].GetDouble()); } const rapidjson::Value& tireLoadFilter = tires[i]["TireLoadFilter"]; if (tireLoadFilter.Size() != 2) return false; for (PxU32 j = 0; j < 2; j++) { const rapidjson::Value& element = tires[i]["TireLoadFilter"][j]; if (element.Size() != 2) return false; tireParams[wheelId].loadFilter[j][0] = static_cast<PxReal>(element[0].GetDouble()); tireParams[wheelId].loadFilter[j][1] = static_cast<PxReal>(element[1].GetDouble()); } } return true; } bool writeTireForceParams (const PxVehicleTireForceParams* tireParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("TireForceParams"); writer.StartArray(); for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("LongitudinalStiffness"); writer.Double(static_cast<double>(tireParams[wheelId].longStiff)); writer.Key("LateralStiffnessX"); writer.Double(static_cast<double>(tireParams[wheelId].latStiffX)); writer.Key("LateralStiffnessY"); writer.Double(static_cast<double>(tireParams[wheelId].latStiffY)); writer.Key("CamberStiffness"); writer.Double(static_cast<double>(tireParams[wheelId].camberStiff)); writer.Key("RestLoad"); writer.Double(static_cast<double>(tireParams[wheelId].restLoad)); writer.Key("FrictionVsSlip"); writer.StartArray(); for(PxU32 k = 0; k < 3; k++) { writer.StartArray(); writer.Double(static_cast<double>(tireParams[wheelId].frictionVsSlip[k][0])); writer.Double(static_cast<double>(tireParams[wheelId].frictionVsSlip[k][1])); writer.EndArray(); } writer.EndArray(); writer.Key("TireLoadFilter"); writer.StartArray(); for (PxU32 k = 0; k < 2; k++) { writer.StartArray(); writer.Double(static_cast<double>(tireParams[wheelId].loadFilter[k][0])); writer.Double(static_cast<double>(tireParams[wheelId].loadFilter[k][1])); writer.EndArray(); } writer.EndArray(); writer.EndObject(); } writer.EndArray(); return true; } bool readWheelParams (const rapidjson::Document& config, const PxVehicleAxleDescription& axleDesc, PxVehicleWheelParams* wheelParams) { if (!config.HasMember("WheelParams")) return false; const rapidjson::Value& wheels = config["WheelParams"]; const PxU32 nbWheels = wheels.Size(); if (nbWheels != axleDesc.getNbWheels()) return false; for (PxU32 i = 0; i < nbWheels; i++) { if (!wheels[i].HasMember("WheelId")) return false; if (!wheels[i].HasMember("HalfWidth")) return false; if (!wheels[i].HasMember("Radius")) return false; if (!wheels[i].HasMember("Mass")) return false; if (!wheels[i].HasMember("MOI")) return false; if (!wheels[i].HasMember("DampingRate")) return false; const PxU32 wheelId = wheels[i]["WheelId"].GetInt(); wheelParams[wheelId].halfWidth = static_cast<PxReal>(wheels[i]["HalfWidth"].GetDouble()); wheelParams[wheelId].radius = static_cast<PxReal>(wheels[i]["Radius"].GetDouble()); wheelParams[wheelId].mass = static_cast<PxReal>(wheels[i]["Mass"].GetDouble()); wheelParams[wheelId].moi = static_cast<PxReal>(wheels[i]["MOI"].GetDouble()); wheelParams[wheelId].dampingRate = static_cast<PxReal>(wheels[i]["DampingRate"].GetDouble()); } return true; } bool writeWheelParams (const PxVehicleWheelParams* wheelParams, const PxVehicleAxleDescription& axleDesc, rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) { writer.Key("WheelParams"); writer.StartArray(); for (PxU32 i = 0; i < axleDesc.nbWheels; i++) { writer.StartObject(); writer.Key("WheelId"); const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i]; writer.Int(wheelId); writer.Key("HalfWidth"); writer.Double(static_cast<double>(wheelParams[wheelId].halfWidth)); writer.Key("Radius"); writer.Double(static_cast<double>(wheelParams[wheelId].radius)); writer.Key("Mass"); writer.Double(static_cast<double>(wheelParams[wheelId].mass)); writer.Key("MOI"); writer.Double(static_cast<double>(wheelParams[wheelId].moi)); writer.Key("DampingRate"); writer.Double(static_cast<double>(wheelParams[wheelId].dampingRate)); writer.EndObject(); } writer.EndArray(); return true; } bool readBaseParamsFromJsonFile(const char* directory, const char* filename, BaseVehicleParams& baseParams) { rapidjson::Document config; if (!openDocument(directory, filename, config)) return false; ////////////////////////////// //Read the high level params ////////////////////////////// PxMemSet(&baseParams.axleDescription, 0xff, sizeof(baseParams.axleDescription)); if (!readAxleDescription(config, baseParams.axleDescription)) return false; PxMemSet(&baseParams.frame, 0xff, sizeof(baseParams.frame)); if (!readFrame(config, baseParams.frame)) return false; PxMemSet(&baseParams.scale, 0xff, sizeof(baseParams.scale)); if (!readScale(config, baseParams.scale)) return false; ////////////////////////////// //Read the rigid body params ///////////////////////////// PxMemSet(&baseParams.rigidBodyParams, 0xff, sizeof(baseParams.rigidBodyParams)); if (!readRigidBodyParams(config, baseParams.rigidBodyParams)) return false; ////////////////////////////// //Read the suspension state calculation params. ////////////////////////////// PxMemSet(&baseParams.suspensionStateCalculationParams, 0xff, sizeof(baseParams.suspensionStateCalculationParams)); if (!readSuspensionStateCalculationParams(config, baseParams.suspensionStateCalculationParams)) return false; /////////////////////////////// //Read the command responses /////////////////////////////// PxMemSet(&baseParams.brakeResponseParams[0], 0xff, sizeof(baseParams.brakeResponseParams[0])); if (!readBrakeResponseParams(config, baseParams.axleDescription, baseParams.brakeResponseParams[0])) return false; PxMemSet(&baseParams.brakeResponseParams[1], 0xff, sizeof(baseParams.brakeResponseParams[1])); if (!readHandbrakeResponseParams(config, baseParams.axleDescription, baseParams.brakeResponseParams[1])) return false; PxMemSet(&baseParams.steerResponseParams, 0xff, sizeof(baseParams.steerResponseParams)); if (!readSteerResponseParams(config, baseParams.axleDescription, baseParams.steerResponseParams)) return false; PxMemSet(&baseParams.ackermannParams, 0xff, sizeof(baseParams.ackermannParams)); if (!readAckermannParams(config, baseParams.ackermannParams[0])) return false; /////////////////////////////////// //Read the suspension params /////////////////////////////////// PxMemSet(baseParams.suspensionParams, 0xff, sizeof(baseParams.suspensionParams)); if (!readSuspensionParams(config, baseParams.axleDescription, baseParams.suspensionParams)) return false; PxMemSet(baseParams.suspensionComplianceParams, 0x00, sizeof(baseParams.suspensionComplianceParams)); if (!readSuspensionComplianceParams(config, baseParams.axleDescription, baseParams.suspensionComplianceParams)) return false; PxMemSet(baseParams.suspensionForceParams, 0xff, sizeof(baseParams.suspensionForceParams)); if (!readSuspensionForceParams(config, baseParams.axleDescription, baseParams.suspensionForceParams)) return false; /////////////////////////////////// //Read the tire params /////////////////////////////////// PxMemSet(baseParams.tireForceParams, 0xff, sizeof(baseParams.tireForceParams)); if (!readTireForceParams(config, baseParams.axleDescription, baseParams.tireForceParams)) return false; ////////////////////////// //Read the wheel params ////////////////////////// PxMemSet(baseParams.wheelParams, 0xff, sizeof(baseParams.wheelParams)); if (!readWheelParams(config, baseParams.axleDescription, baseParams.wheelParams)) return false; return true; } bool writeBaseParamsToJsonFile(const char* directory, const char* filename, const BaseVehicleParams& baseParams) { rapidjson::StringBuffer strbuf; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf); writer.StartObject(); ////////////////////////////// //Write the high level params ////////////////////////////// writeAxleDescription(baseParams.axleDescription, writer); writeFrame(baseParams.frame, writer); writeScale(baseParams.scale, writer); ////////////////////////////// //Write the rigid body params ///////////////////////////// writeRigidBodyParams(baseParams.rigidBodyParams, writer); ////////////////////////////// //Write the suspension state calculation params ////////////////////////////// writeSuspensionStateCalculationParams(baseParams.suspensionStateCalculationParams, writer); /////////////////////////////// //Write the command responses /////////////////////////////// writeBrakeResponseParams(baseParams.brakeResponseParams[0], baseParams.axleDescription, writer); writeHandbrakeResponseParams(baseParams.brakeResponseParams[1], baseParams.axleDescription, writer); writeSteerResponseParams(baseParams.steerResponseParams, baseParams.axleDescription, writer); writeAckermannParams(baseParams.ackermannParams[0], writer); /////////////////////////////////// //Write the suspension params /////////////////////////////////// writeSuspensionParams(baseParams.suspensionParams, baseParams.axleDescription, writer); writeSuspensionComplianceParams(baseParams.suspensionComplianceParams, baseParams.axleDescription, writer); writeSuspensionForceParams(baseParams.suspensionForceParams, baseParams.axleDescription, writer); /////////////////////////////////// //Write the tire params /////////////////////////////////// writeTireForceParams(baseParams.tireForceParams, baseParams.axleDescription, writer); ////////////////////////// //Write the wheel params ////////////////////////// writeWheelParams(baseParams.wheelParams, baseParams.axleDescription, writer); writer.EndObject(); std::ofstream myfile; myfile.open(std::string(directory) + "/" + filename); myfile << strbuf.GetString() << std::endl; myfile.close(); return true; } }//namespace snippetvehicle2
NVIDIA-Omniverse/PhysX/physx/snippets/snippethellogrb/SnippetHelloGRBRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, (PxActor**)&actors[0], nbActors); Snippets::renderActors(&actors[0], (PxU32)actors.size(), true); } Snippets::finishRender(); } void cleanup() { delete sCamera; cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet HelloWorld", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); cleanup(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippethellogrb/SnippetHelloGRB.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates GPU-accelerated rigid body simulation. // // It creates a number of box stacks on a plane, and allows the // user to create new stacks and fire a ball from the camera position // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxCudaContextManager* gCudaContextManager = NULL; static PxReal stackZ = 10.0f; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::ePROFILE); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); //Create the CUDA context manager, required for GRB to dispatch CUDA kernels. if( gCudaContextManager ) { if( !gCudaContextManager->contextIsValid() ) PX_RELEASE(gCudaContextManager); } PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(4); //Create a CPU dispatcher using 4 worther threads sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.cudaContextManager = gCudaContextManager; //Set the CUDA context manager, used by GRB. sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; //Enable GPU dynamics - without this enabled, simulation (contact gen and solver) will run on the CPU. sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; //Enable PCM. PCM NP is supported on GPU. Legacy contact gen will fall back to CPU sceneDesc.flags |= PxSceneFlag::eENABLE_STABILIZATION; //Improve solver stability by enabling post-stabilization. sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; //Enable GPU broad phase. Without this set, broad phase will run on the CPU. sceneDesc.gpuMaxNumPartitions = 8; //Defines the maximum number of partitions used by the solver. Only power-of-2 values are valid. //A value of 8 generally gives best balance between performance and stability. gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, false); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, false); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, false); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); for(PxU32 i=0;i<40;i++) createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 20, 1.0f); //if(!interactive) { PxRigidDynamic* ball = createDynamic(PxTransform(PxVec3(0,20,100)), PxSphereGeometry(5), PxVec3(0,-25,-100)); PxRigidBodyExt::updateMassAndInertia(*ball, 1000.f); } } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gCudaContextManager); PX_RELEASE(gFoundation); printf("SnippetHelloWorld done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case 'B': createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 10, 2.0f); break; case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0,0,-1))*200); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
NVIDIA-Omniverse/PhysX/physx/snippets/snippetarticulationrc/SnippetArticulationRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); const PxVec3 dynColor(1.0f, 0.5f, 0.25f); const PxVec3 rcaColor(0.6f*0.75f, 0.8f*0.75f, 1.0f*0.75f); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } PxU32 nbArticulations = scene->getNbArticulations(); for(PxU32 i=0;i<nbArticulations;i++) { PxArticulationReducedCoordinate* articulation; scene->getArticulations(&articulation, 1, i); const PxU32 nbLinks = articulation->getNbLinks(); std::vector<PxArticulationLink*> links(nbLinks); articulation->getLinks(&links[0], nbLinks); Snippets::renderActors(reinterpret_cast<PxRigidActor**>(&links[0]), static_cast<PxU32>(links.size()), true, rcaColor); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } //const PxVec3 gCamEyeLift(8.605188f, 4.050591f, 0.145860f); //const PxVec3 gCamDirLift(-0.999581f, -0.026449f, 0.011790f); const PxVec3 gCamEyeLift(-5.858525f, 6.079476f, 1.546743f); const PxVec3 gCamDirLift(0.927923f, -0.356565f, -0.108720f); void renderLoop() { sCamera = new Snippets::Camera(gCamEyeLift, gCamDirLift); Snippets::setupDefault("PhysX Snippet RC Articulation", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
NVIDIA-Omniverse/PhysX/physx/snippets/snippetarticulationrc/SnippetArticulation.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet demonstrates the use of Reduced Coordinates articulations. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxArticulationReducedCoordinate* gArticulation = NULL; static PxArticulationJointReducedCoordinate* gDriveJoint = NULL; static PxFilterFlags scissorFilter( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(attributes1); PX_UNUSED(constantBlock); PX_UNUSED(constantBlockSize); if (filterData0.word2 != 0 && filterData0.word2 == filterData1.word2) return PxFilterFlag::eKILL; pairFlags |= PxPairFlag::eCONTACT_DEFAULT; return PxFilterFlag::eDEFAULT; } static void createScissorLift() { const PxReal runnerLength = 2.f; const PxReal placementDistance = 1.8f; const PxReal cosAng = (placementDistance) / (runnerLength); const PxReal angle = PxAcos(cosAng); const PxReal sinAng = PxSin(angle); const PxQuat leftRot(-angle, PxVec3(1.f, 0.f, 0.f)); const PxQuat rightRot(angle, PxVec3(1.f, 0.f, 0.f)); //(1) Create base... PxArticulationLink* base = gArticulation->createLink(NULL, PxTransform(PxVec3(0.f, 0.25f, 0.f))); PxRigidActorExt::createExclusiveShape(*base, PxBoxGeometry(0.5f, 0.25f, 1.5f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*base, 3.f); //Now create the slider and fixed joints... gArticulation->setSolverIterationCounts(32); PxArticulationLink* leftRoot = gArticulation->createLink(base, PxTransform(PxVec3(0.f, 0.55f, -0.9f))); PxRigidActorExt::createExclusiveShape(*leftRoot, PxBoxGeometry(0.5f, 0.05f, 0.05f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftRoot, 1.f); PxArticulationLink* rightRoot = gArticulation->createLink(base, PxTransform(PxVec3(0.f, 0.55f, 0.9f))); PxRigidActorExt::createExclusiveShape(*rightRoot, PxBoxGeometry(0.5f, 0.05f, 0.05f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightRoot, 1.f); PxArticulationJointReducedCoordinate* joint = static_cast<PxArticulationJointReducedCoordinate*>(leftRoot->getInboundJoint()); joint->setJointType(PxArticulationJointType::eFIX); joint->setParentPose(PxTransform(PxVec3(0.f, 0.25f, -0.9f))); joint->setChildPose(PxTransform(PxVec3(0.f, -0.05f, 0.f))); //Set up the drive joint... gDriveJoint = static_cast<PxArticulationJointReducedCoordinate*>(rightRoot->getInboundJoint()); gDriveJoint->setJointType(PxArticulationJointType::ePRISMATIC); gDriveJoint->setMotion(PxArticulationAxis::eZ, PxArticulationMotion::eLIMITED); gDriveJoint->setLimitParams(PxArticulationAxis::eZ, PxArticulationLimit(-1.4f, 0.2f)); gDriveJoint->setDriveParams(PxArticulationAxis::eZ, PxArticulationDrive(100000.f, 0.f, PX_MAX_F32)); gDriveJoint->setParentPose(PxTransform(PxVec3(0.f, 0.25f, 0.9f))); gDriveJoint->setChildPose(PxTransform(PxVec3(0.f, -0.05f, 0.f))); const PxU32 linkHeight = 3; PxArticulationLink* currLeft = leftRoot, *currRight = rightRoot; PxQuat rightParentRot(PxIdentity); PxQuat leftParentRot(PxIdentity); for (PxU32 i = 0; i < linkHeight; ++i) { const PxVec3 pos(0.5f, 0.55f + 0.1f*(1 + i), 0.f); PxArticulationLink* leftLink = gArticulation->createLink(currLeft, PxTransform(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), leftRot)); PxRigidActorExt::createExclusiveShape(*leftLink, PxBoxGeometry(0.05f, 0.05f, 1.f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftLink, 1.f); const PxVec3 leftAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), -0.9f); joint = static_cast<PxArticulationJointReducedCoordinate*>(leftLink->getInboundJoint()); joint->setParentPose(PxTransform(currLeft->getGlobalPose().transformInv(leftAnchorLocation), leftParentRot)); joint->setChildPose(PxTransform(PxVec3(0.f, 0.f, -1.f), rightRot)); joint->setJointType(PxArticulationJointType::eREVOLUTE); leftParentRot = leftRot; joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eLIMITED); joint->setLimitParams(PxArticulationAxis::eTWIST, PxArticulationLimit(-PxPi, angle)); PxArticulationLink* rightLink = gArticulation->createLink(currRight, PxTransform(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), rightRot)); PxRigidActorExt::createExclusiveShape(*rightLink, PxBoxGeometry(0.05f, 0.05f, 1.f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightLink, 1.f); const PxVec3 rightAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), 0.9f); joint = static_cast<PxArticulationJointReducedCoordinate*>(rightLink->getInboundJoint()); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setParentPose(PxTransform(currRight->getGlobalPose().transformInv(rightAnchorLocation), rightParentRot)); joint->setChildPose(PxTransform(PxVec3(0.f, 0.f, 1.f), leftRot)); joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eLIMITED); joint->setLimitParams(PxArticulationAxis::eTWIST, PxArticulationLimit(-angle, PxPi)); rightParentRot = rightRot; PxD6Joint* d6joint = PxD6JointCreate(*gPhysics, leftLink, PxTransform(PxIdentity), rightLink, PxTransform(PxIdentity)); d6joint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); currLeft = rightLink; currRight = leftLink; } PxArticulationLink* leftTop = gArticulation->createLink(currLeft, currLeft->getGlobalPose().transform(PxTransform(PxVec3(-0.5f, 0.f, -1.0f), leftParentRot))); PxRigidActorExt::createExclusiveShape(*leftTop, PxBoxGeometry(0.5f, 0.05f, 0.05f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftTop, 1.f); PxArticulationLink* rightTop = gArticulation->createLink(currRight, currRight->getGlobalPose().transform(PxTransform(PxVec3(-0.5f, 0.f, 1.0f), rightParentRot))); PxRigidActorExt::createExclusiveShape(*rightTop, PxCapsuleGeometry(0.05f, 0.8f), *gMaterial); //PxRigidActorExt::createExclusiveShape(*rightTop, PxBoxGeometry(0.5f, 0.05f, 0.05f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightTop, 1.f); joint = static_cast<PxArticulationJointReducedCoordinate*>(leftTop->getInboundJoint()); joint->setParentPose(PxTransform(PxVec3(0.f, 0.f, -1.f), currLeft->getGlobalPose().q.getConjugate())); joint->setChildPose(PxTransform(PxVec3(0.5f, 0.f, 0.f), leftTop->getGlobalPose().q.getConjugate())); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eFREE); joint = static_cast<PxArticulationJointReducedCoordinate*>(rightTop->getInboundJoint()); joint->setParentPose(PxTransform(PxVec3(0.f, 0.f, 1.f), currRight->getGlobalPose().q.getConjugate())); joint->setChildPose(PxTransform(PxVec3(0.5f, 0.f, 0.f), rightTop->getGlobalPose().q.getConjugate())); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eFREE); currLeft = leftRoot; currRight = rightRoot; rightParentRot = PxQuat(PxIdentity); leftParentRot = PxQuat(PxIdentity); for (PxU32 i = 0; i < linkHeight; ++i) { const PxVec3 pos(-0.5f, 0.55f + 0.1f*(1 + i), 0.f); PxArticulationLink* leftLink = gArticulation->createLink(currLeft, PxTransform(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), leftRot)); PxRigidActorExt::createExclusiveShape(*leftLink, PxBoxGeometry(0.05f, 0.05f, 1.f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftLink, 1.f); const PxVec3 leftAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), -0.9f); joint = static_cast<PxArticulationJointReducedCoordinate*>(leftLink->getInboundJoint()); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setParentPose(PxTransform(currLeft->getGlobalPose().transformInv(leftAnchorLocation), leftParentRot)); joint->setChildPose(PxTransform(PxVec3(0.f, 0.f, -1.f), rightRot)); leftParentRot = leftRot; joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eLIMITED); joint->setLimitParams(PxArticulationAxis::eTWIST, PxArticulationLimit(-PxPi, angle)); PxArticulationLink* rightLink = gArticulation->createLink(currRight, PxTransform(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), rightRot)); PxRigidActorExt::createExclusiveShape(*rightLink, PxBoxGeometry(0.05f, 0.05f, 1.f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightLink, 1.f); const PxVec3 rightAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), 0.9f); /*joint = PxD6JointCreate(getPhysics(), currRight, PxTransform(currRight->getGlobalPose().transformInv(rightAnchorLocation)), rightLink, PxTransform(PxVec3(0.f, 0.f, 1.f)));*/ joint = static_cast<PxArticulationJointReducedCoordinate*>(rightLink->getInboundJoint()); joint->setParentPose(PxTransform(currRight->getGlobalPose().transformInv(rightAnchorLocation), rightParentRot)); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setChildPose(PxTransform(PxVec3(0.f, 0.f, 1.f), leftRot)); joint->setMotion(PxArticulationAxis::eTWIST, PxArticulationMotion::eLIMITED); joint->setLimitParams(PxArticulationAxis::eTWIST, PxArticulationLimit(-angle, PxPi)); rightParentRot = rightRot; PxD6Joint* d6joint = PxD6JointCreate(*gPhysics, leftLink, PxTransform(PxIdentity), rightLink, PxTransform(PxIdentity)); d6joint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); currLeft = rightLink; currRight = leftLink; } PxD6Joint* d6joint = PxD6JointCreate(*gPhysics, currLeft, PxTransform(PxVec3(0.f, 0.f, -1.f)), leftTop, PxTransform(PxVec3(-0.5f, 0.f, 0.f))); d6joint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); d6joint = PxD6JointCreate(*gPhysics, currRight, PxTransform(PxVec3(0.f, 0.f, 1.f)), rightTop, PxTransform(PxVec3(-0.5f, 0.f, 0.f))); d6joint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); d6joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); const PxTransform topPose(PxVec3(0.f, leftTop->getGlobalPose().p.y + 0.15f, 0.f)); PxArticulationLink* top = gArticulation->createLink(leftTop, topPose); PxRigidActorExt::createExclusiveShape(*top, PxBoxGeometry(0.5f, 0.1f, 1.5f), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*top, 1.f); joint = static_cast<PxArticulationJointReducedCoordinate*>(top->getInboundJoint()); joint->setJointType(PxArticulationJointType::eFIX); joint->setParentPose(PxTransform(PxVec3(0.f, 0.0f, 0.f))); joint->setChildPose(PxTransform(PxVec3(0.f, -0.15f, -0.9f))); gScene->addArticulation(*gArticulation); for (PxU32 i = 0; i < gArticulation->getNbLinks(); ++i) { PxArticulationLink* link; gArticulation->getLinks(&link, 1, i); link->setLinearDamping(0.2f); link->setAngularDamping(0.2f); link->setMaxAngularVelocity(20.f); link->setMaxLinearVelocity(100.f); if (link != top) { for (PxU32 b = 0; b < link->getNbShapes(); ++b) { PxShape* shape; link->getShapes(&shape, 1, b); shape->setSimulationFilterData(PxFilterData(0, 0, 1, 0)); } } } const PxVec3 halfExt(0.25f); const PxReal density(0.5f); PxRigidDynamic* box0 = gPhysics->createRigidDynamic(PxTransform(PxVec3(-0.25f, 5.f, 0.5f))); PxShape* shape0 = PxRigidActorExt::createExclusiveShape(*box0, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box0, density); gScene->addActor(*box0); PxRigidDynamic* box1 = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.25f, 5.f, 0.5f))); PxShape* shape1 = PxRigidActorExt::createExclusiveShape(*box1, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box1, density); gScene->addActor(*box1); PxRigidDynamic* box2 = gPhysics->createRigidDynamic(PxTransform(PxVec3(-0.25f, 4.5f, 0.5f))); PxShape* shape2 = PxRigidActorExt::createExclusiveShape(*box2, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box2, density); gScene->addActor(*box2); PxRigidDynamic* box3 = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.25f, 4.5f, 0.5f))); PxShape* shape3 = PxRigidActorExt::createExclusiveShape(*box3, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box3, density); gScene->addActor(*box3); PxRigidDynamic* box4 = gPhysics->createRigidDynamic(PxTransform(PxVec3(-0.25f, 5.f, 0.f))); PxShape* shape4 = PxRigidActorExt::createExclusiveShape(*box4, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box4, density); gScene->addActor(*box4); PxRigidDynamic* box5 = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.25f, 5.f, 0.f))); PxShape* shape5 = PxRigidActorExt::createExclusiveShape(*box5, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box5, density); gScene->addActor(*box5); PxRigidDynamic* box6 = gPhysics->createRigidDynamic(PxTransform(PxVec3(-0.25f, 4.5f, 0.f))); PxShape* shape6 = PxRigidActorExt::createExclusiveShape(*box6, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box6, density); gScene->addActor(*box6); PxRigidDynamic* box7 = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.25f, 4.5f, 0.f))); PxShape* shape7 = PxRigidActorExt::createExclusiveShape(*box7, PxBoxGeometry(halfExt), *gMaterial); PxRigidBodyExt::updateMassAndInertia(*box7, density); gScene->addActor(*box7); const float contactOffset = 0.2f; shape0->setContactOffset(contactOffset); shape1->setContactOffset(contactOffset); shape2->setContactOffset(contactOffset); shape3->setContactOffset(contactOffset); shape4->setContactOffset(contactOffset); shape5->setContactOffset(contactOffset); shape6->setContactOffset(contactOffset); shape7->setContactOffset(contactOffset); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.solverType = PxSolverType::eTGS; sceneDesc.filterShader = scissorFilter; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); gArticulation = gPhysics->createArticulationReducedCoordinate(); createScissorLift(); } static bool gClosing = true; void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; PxReal driveValue = gDriveJoint->getDriveTarget(PxArticulationAxis::eZ); if (gClosing && driveValue < -1.2f) gClosing = false; else if (!gClosing && driveValue > 0.f) gClosing = true; if (gClosing) driveValue -= dt*0.25f; else driveValue += dt*0.25f; gDriveJoint->setDriveTarget(PxArticulationAxis::eZ, driveValue); gScene->simulate(dt); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { gArticulation->release(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); PX_RELEASE(gPvd); PX_RELEASE(transport); PxCloseExtensions(); PX_RELEASE(gFoundation); printf("SnippetArticulation done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }