Skip to content

Rayrai Example: Rolling And Spinning Friction ​

Overview ​

This example visualizes native rolling and spinning friction on a grid of spheres and cylinders, all spawned with initial linear and angular velocity. As the bodies dissipate energy through these friction modes they slow down, come to rest, and are recolored to indicate sleeping. The demo restarts on a fixed cadence so the motion and its decay are easy to compare.

The GIF below uses a smaller 6 × 6 grid. A headless image generator rebuilds it during the documentation build:

Target ​

CMake target: rayrai_rolling_spinning_friction.

Run ​

Run the build-tree executable:

bash
./build-examples/examples/rayrai_rolling_spinning_friction

On Windows, run rayrai_rolling_spinning_friction.exe instead. This example renders in process with rayrai and does not need rayrai_tcp_viewer.

Command-line options:

bash
./build-examples/examples/rayrai_rolling_spinning_friction \
  --grid=12             \
  --steps=2500          \
  --steps-per-frame=16  \
  --hold-frames=120
  • --grid — N × N body grid (default 10). Larger values exercise the solver harder; the GIF on this page uses a 6 × 6 grid for clarity.
  • --steps — physics steps per cycle (default 2500). One cycle is one full reset → run-until-rest sequence.
  • --steps-per-frame — physics steps per render frame (default 16). Higher values speed up the visible motion at the cost of frame-to-frame smoothness.
  • --hold-frames — frames to wait after each cycle before resetting (default 120).

How it works ​

The rolling/spinning friction comes from the material-pair property set up in main():

cpp
world->setMaterialPairProp("ground", "body",
                           1.0,    // dynamic friction
                           0.0,    // restitution
                           0.0,    // restitution threshold
                           1.0,    // static friction
                           1e-3,   // static-friction threshold velocity
                           0.12,   // rolling friction (mu_r)
                           0.08);  // spinning friction (mu_spin)

The last two arguments are the rollingFriction and spinningFriction coefficients introduced in v2.3.0. Both are zero in every other setMaterialPairProp overload, so existing scenes behave exactly as before; setting them switches the solver onto the extended path for that pair. See Material System for the full contact-impulse derivation.

The scene is built once at startup:

  • A checkerboard-textured ground plane with the ground material.
  • An N × N grid of unit-mass primitives alternating sphere/cylinder by checker pattern, all in the body material. Cylinders are oriented so that the initial angular velocity rolls them along the floor instead of spinning in place; spheres receive linear + angular velocity in two axes.
  • Sleeping is enabled with mild thresholds (setSleepingParameters(0.012, 0.03, 25)), so bodies that come to rest stop integrating and switch to a blue appearance.

Each rendered frame integrates --steps-per-frame physics steps, updates the sleep appearance, and shows aggregate statistics in an ImGui overlay. Abridged from the source:

cpp
while (!app.quit) {
  app.processEvents();
  if (app.quit) break;

  if (stepInCycle < cycleSteps) {
    for (int i = 0; i < stepsPerFrame; ++i) {
      world->integrate();
      lastContacts = world->getContactProblem()->size();
      contactTotal += lastContacts;
      ++stepInCycle;
    }
  } else if (++heldFrames >= holdFrames) {
    resetDemo(*world, bodies, grid);   // re-fire the cycle
    stepInCycle = 0;
    heldFrames = 0;
  }

  updateSleepingAppearance(*world, bodies);
  computeMeanSpeeds(bodies, meanLinearSpeed, meanAngularSpeed);

  app.beginFrame();
  app.renderViewer(*viewer);
  // ... ImGui overlay with step / contacts / speeds ...
  app.endFrame();
}

What to look for ​

  • Rolling bodies come to rest. Sliding friction first turns the initial skid into rolling; rolling friction then removes energy from the rolling motion, so linear and angular speed decay together. Without rolling friction, a body rolling without slipping would keep rolling.
  • Spheres stop spinning about the vertical axis. Each sphere also starts with spin about the contact normal. Spinning friction applies a torque about the normal that removes this spin; without it, a sphere would keep spinning in place after it stops rolling.
  • Sleeping bodies turn blue. RaiSim's sleep detector fires when the averaged velocity drops below the configured thresholds; sleeping bodies skip integration and stay on the cheaper path until the next cycle reset.
  • Average contact count and mean speeds are shown in the ImGui overlay so you can watch energy dissipate over the cycle.

Full source ​

This is the complete source used by the build-tree target:

cpp
#include <algorithm>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>

#include <glm/glm.hpp>

#include "raisim/World.hpp"
#include "rayrai/PhysicsSnapshot.hpp"
#include "rayrai/example_common.hpp"
#include "rayrai_example_compat.hpp"

namespace {

struct DemoBody {
  raisim::SingleBodyObject* object = nullptr;
  std::string activeAppearance;
  bool sleeping = false;
  bool sphereShape = false;
  int x = 0;
  int y = 0;
};

int readIntArg(int argc, char** argv, const char* name, int fallback) {
  const std::string prefix = std::string(name) + "=";
  for (int i = 1; i < argc; ++i) {
    const std::string arg(argv[i]);
    if (arg == name && i + 1 < argc) return std::max(1, std::atoi(argv[++i]));
    if (arg.rfind(prefix, 0) == 0) return std::max(1, std::atoi(arg.c_str() + prefix.size()));
  }
  return fallback;
}

void resetBody(raisim::World& world, DemoBody& body, int grid) {
  const double spacing = 1.1;
  const double origin = -0.5 * spacing * double(grid - 1);
  const int x = body.x;
  const int y = body.y;

  if (body.sphereShape) {
    body.object->setPosition(origin + spacing * x, origin + spacing * y, 0.25);
    body.object->setOrientation(1.0, 0.0, 0.0, 0.0);
    body.object->setVelocity(1.7 + 0.08 * x, 0.4 + 0.05 * y, 0.0, 0.0, -11.0, 18.0);
  } else if ((x & 1) == 0) {
    // Cylinder axis lies along world X, so angular velocity about X visibly rolls it along Y.
    body.object->setOrientation(0.7071067812, 0.0, 0.7071067812, 0.0);
    body.object->setPosition(origin + spacing * x, origin + spacing * y, 0.22);
    body.object->setVelocity(0.15 + 0.04 * x, 1.9 + 0.07 * y, 0.0, 14.0, 0.0, 0.0);
  } else {
    // Cylinder axis lies along world Y, so angular velocity about Y visibly rolls it along X.
    body.object->setOrientation(0.7071067812, -0.7071067812, 0.0, 0.0);
    body.object->setPosition(origin + spacing * x, origin + spacing * y, 0.22);
    body.object->setVelocity(1.9 + 0.07 * x, 0.15 + 0.04 * y, 0.0, 0.0, -14.0, 0.0);
  }

  body.sleeping = false;
  body.object->setAppearance(body.activeAppearance);
  world.wakeObject(body.object);
}

std::vector<DemoBody> createBodies(raisim::World& world, int grid) {
  std::vector<DemoBody> bodies;
  bodies.reserve(static_cast<size_t>(grid * grid));

  for (int y = 0; y < grid; ++y) {
    for (int x = 0; x < grid; ++x) {
      const bool sphereShape = ((x + y) & 1) == 0;
      DemoBody body;
      body.sphereShape = sphereShape;
      body.x = x;
      body.y = y;
      body.activeAppearance = sphereShape ? "0.95, 0.42, 0.12, 1.0" : "0.15, 0.70, 0.28, 1.0";
      if (sphereShape) {
        body.object = world.addSphere(0.25, 1.0, "body");
      } else {
        body.object = world.addCylinder(0.22, 0.55, 1.0, "body");
      }
      body.object->setAppearance(body.activeAppearance);
      bodies.push_back(body);
      resetBody(world, bodies.back(), grid);
    }
  }

  return bodies;
}

void resetDemo(raisim::World& world, std::vector<DemoBody>& bodies, int grid) {
  world.setWorldTime(0.0);
  for (auto& body : bodies) resetBody(world, body, grid);
  world.wakeAll();
}

void updateSleepingAppearance(raisim::World& world, std::vector<DemoBody>& bodies) {
  for (auto& body : bodies) {
    const bool sleeping = world.isObjectSleeping(body.object);
    if (sleeping != body.sleeping) {
      body.object->setAppearance(sleeping ? "0.20, 0.55, 1.00, 1.0" : body.activeAppearance);
      body.sleeping = sleeping;
    }
  }
}

void computeMeanSpeeds(const std::vector<DemoBody>& bodies, double& linearSpeed, double& angularSpeed) {
  linearSpeed = 0.0;
  angularSpeed = 0.0;
  if (bodies.empty()) return;

  for (const auto& body : bodies) {
    linearSpeed += body.object->getLinearVelocity().norm();
    angularSpeed += body.object->getAngularVelocity().norm();
  }

  linearSpeed /= double(bodies.size());
  angularSpeed /= double(bodies.size());
}

}  // namespace

int main(int argc, char* argv[]) {
  const int grid = readIntArg(argc, argv, "--grid", 10);
  const int cycleSteps = readIntArg(argc, argv, "--steps", 2500);
  const int stepsPerFrame = readIntArg(argc, argv, "--steps-per-frame", 16);
  const int holdFrames = readIntArg(argc, argv, "--hold-frames", 120);

  ExampleApp app;
  if (!app.init("rayrai_rolling_spinning_friction", 1280, 720)) return -1;

  auto world = std::make_shared<raisim::World>();
  world->setTimeStep(0.001);
  world->setERP(0.0, 0.0);
  world->setContactSolverParam(1.0, 1.0, 1.0, 120, 1e-10);
  world->setGravity({0.0, 0.0, -9.81});
  world->setSleepingEnabled(true);
  world->setSleepingParameters(0.012, 0.03, 25);
  auto* ground = world->addGround(0.0, "ground");
  ground->setAppearance("checkerboard");
  world->setMaterialPairProp("ground", "body", 1.0, 0.0, 0.0, 1.0, 1e-3, 0.12, 0.08);

  std::vector<DemoBody> bodies = createBodies(*world, grid);

  // The renderer owns an empty world; physics reaches it only through copied snapshots.
  raisin::PhysicsSnapshotCapture snapshotCapture;
  auto viewer = std::make_shared<raisin::RayraiWindow>(std::make_shared<raisim::World>(), 1280, 720);
  viewer->setRenderQualitySettings(raisin::RayraiWindow::defaultRenderQualitySettings(raisin::RayraiWindow::RenderQualityPreset::Balanced));
  raisim_examples::setRayraiBackgroundColorRgb255(*viewer, {24, 26, 30, 255});
  raisim_examples::addRayraiBasicSceneLights(*viewer);

  auto& camera = viewer->getCamera();
  camera.position = glm::vec3(6.0f, -8.5f, 5.0f);
  camera.target = glm::vec3(0.0f, 0.0f, 0.25f);
  camera.yaw = 125.0f;
  camera.pitch = -31.0f;
  camera.zoom = 42.0f;
  camera.zNear = 0.03f;
  camera.zFar = 35.0f;
  camera.setCameraFixedTarget(true);
  camera.setCameraFixedDistance(true);
  camera.update(false);

  int stepInCycle = 0;
  int heldFrames = 0;
  std::size_t contactTotal = 0;
  std::size_t lastContacts = 0;
  double meanLinearSpeed = 0.0;
  double meanAngularSpeed = 0.0;

  while (!app.quit) {
    app.processEvents();
    if (app.quit) break;

    if (stepInCycle < cycleSteps) {
      const int frameSteps = std::min(stepsPerFrame, cycleSteps - stepInCycle);
      for (int i = 0; i < frameSteps; ++i) {
        world->integrate();
        lastContacts = world->getContactProblem()->size();
        contactTotal += lastContacts;
        ++stepInCycle;
      }
      heldFrames = 0;
    } else if (++heldFrames >= holdFrames) {
      resetDemo(*world, bodies, grid);
      stepInCycle = 0;
      heldFrames = 0;
      contactTotal = 0;
      lastContacts = 0;
    }

    updateSleepingAppearance(*world, bodies);
    computeMeanSpeeds(bodies, meanLinearSpeed, meanAngularSpeed);

    const auto snapshot = snapshotCapture.capture(*world);
    viewer->applyPhysicsSnapshot(snapshot);

    app.beginFrame();
    app.renderViewer(*viewer);

    ImGui::SetNextWindowPos(ImVec2(12, 12), ImGuiCond_Always);
    ImGui::SetNextWindowBgAlpha(0.72f);
    ImGui::Begin("Rolling friction", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse);
    ImGui::Text("step %d / %d", stepInCycle, cycleSteps);
    ImGui::Text("bodies: %zu", bodies.size());
    ImGui::Text("contacts: %zu", lastContacts);
    ImGui::Text("average contacts: %.2f", stepInCycle > 0 ? double(contactTotal) / double(stepInCycle) : 0.0);
    ImGui::Text("mean linear speed: %.3f m/s", meanLinearSpeed);
    ImGui::Text("mean angular speed: %.3f rad/s", meanAngularSpeed);
    ImGui::End();

    app.endFrame();
  }

  viewer.reset();
  app.shutdown();
  return 0;
}

RaiSim — physics for robotics and AI.