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:
./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:
./build-examples/examples/rayrai_rolling_spinning_friction \
--grid=12 \
--steps=2500 \
--steps-per-frame=16 \
--hold-frames=120
--grid— N × N body grid (default10). Larger values exercise the solver harder; the GIF on this page uses a 6 × 6 grid for clarity.--steps— physics steps per cycle (default2500). One cycle is one full reset → run-until-rest sequence.--steps-per-frame— physics steps per render frame (default16). 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 (default120).
How it works
The rolling/spinning friction comes from the material-pair property set
up in main():
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 thegroundmaterial.An
N × Ngrid of unit-mass primitives alternating sphere/cylinder by checker pattern, all in thebodymaterial. 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:
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:
1#include <algorithm>
2#include <cstdlib>
3#include <memory>
4#include <string>
5#include <vector>
6
7#include <glm/glm.hpp>
8
9#include "raisim/World.hpp"
10#include "rayrai/example_common.hpp"
11#include "rayrai_example_compat.hpp"
12
13namespace {
14
15struct DemoBody {
16 raisim::SingleBodyObject* object = nullptr;
17 std::string activeAppearance;
18 bool sleeping = false;
19 bool sphereShape = false;
20 int x = 0;
21 int y = 0;
22};
23
24int readIntArg(int argc, char** argv, const char* name, int fallback) {
25 const std::string prefix = std::string(name) + "=";
26 for (int i = 1; i < argc; ++i) {
27 const std::string arg(argv[i]);
28 if (arg == name && i + 1 < argc) return std::max(1, std::atoi(argv[++i]));
29 if (arg.rfind(prefix, 0) == 0) return std::max(1, std::atoi(arg.c_str() + prefix.size()));
30 }
31 return fallback;
32}
33
34void resetBody(raisim::World& world, DemoBody& body, int grid) {
35 const double spacing = 1.1;
36 const double origin = -0.5 * spacing * double(grid - 1);
37 const int x = body.x;
38 const int y = body.y;
39
40 if (body.sphereShape) {
41 body.object->setPosition(origin + spacing * x, origin + spacing * y, 0.25);
42 body.object->setOrientation(1.0, 0.0, 0.0, 0.0);
43 body.object->setVelocity(1.7 + 0.08 * x, 0.4 + 0.05 * y, 0.0, 0.0, -11.0, 18.0);
44 } else if ((x & 1) == 0) {
45 // Cylinder axis lies along world X, so angular velocity about X visibly rolls it along Y.
46 body.object->setOrientation(0.7071067812, 0.0, 0.7071067812, 0.0);
47 body.object->setPosition(origin + spacing * x, origin + spacing * y, 0.22);
48 body.object->setVelocity(0.15 + 0.04 * x, 1.9 + 0.07 * y, 0.0, 14.0, 0.0, 0.0);
49 } else {
50 // Cylinder axis lies along world Y, so angular velocity about Y visibly rolls it along X.
51 body.object->setOrientation(0.7071067812, -0.7071067812, 0.0, 0.0);
52 body.object->setPosition(origin + spacing * x, origin + spacing * y, 0.22);
53 body.object->setVelocity(1.9 + 0.07 * x, 0.15 + 0.04 * y, 0.0, 0.0, -14.0, 0.0);
54 }
55
56 body.sleeping = false;
57 body.object->setAppearance(body.activeAppearance);
58 world.wakeObject(body.object);
59}
60
61std::vector<DemoBody> createBodies(raisim::World& world, int grid) {
62 std::vector<DemoBody> bodies;
63 bodies.reserve(static_cast<size_t>(grid * grid));
64
65 for (int y = 0; y < grid; ++y) {
66 for (int x = 0; x < grid; ++x) {
67 const bool sphereShape = ((x + y) & 1) == 0;
68 DemoBody body;
69 body.sphereShape = sphereShape;
70 body.x = x;
71 body.y = y;
72 body.activeAppearance = sphereShape ? "0.95, 0.42, 0.12, 1.0" : "0.15, 0.70, 0.28, 1.0";
73 if (sphereShape) {
74 body.object = world.addSphere(0.25, 1.0, "body");
75 } else {
76 body.object = world.addCylinder(0.22, 0.55, 1.0, "body");
77 }
78 body.object->setAppearance(body.activeAppearance);
79 bodies.push_back(body);
80 resetBody(world, bodies.back(), grid);
81 }
82 }
83
84 return bodies;
85}
86
87void resetDemo(raisim::World& world, std::vector<DemoBody>& bodies, int grid) {
88 world.setWorldTime(0.0);
89 for (auto& body : bodies) resetBody(world, body, grid);
90 world.wakeAll();
91}
92
93void updateSleepingAppearance(raisim::World& world, std::vector<DemoBody>& bodies) {
94 for (auto& body : bodies) {
95 const bool sleeping = world.isObjectSleeping(body.object);
96 if (sleeping != body.sleeping) {
97 body.object->setAppearance(sleeping ? "0.20, 0.55, 1.00, 1.0" : body.activeAppearance);
98 body.sleeping = sleeping;
99 }
100 }
101}
102
103void computeMeanSpeeds(const std::vector<DemoBody>& bodies, double& linearSpeed, double& angularSpeed) {
104 linearSpeed = 0.0;
105 angularSpeed = 0.0;
106 if (bodies.empty()) return;
107
108 for (const auto& body : bodies) {
109 linearSpeed += body.object->getLinearVelocity().norm();
110 angularSpeed += body.object->getAngularVelocity().norm();
111 }
112
113 linearSpeed /= double(bodies.size());
114 angularSpeed /= double(bodies.size());
115}
116
117} // namespace
118
119int main(int argc, char* argv[]) {
120 const int grid = readIntArg(argc, argv, "--grid", 10);
121 const int cycleSteps = readIntArg(argc, argv, "--steps", 2500);
122 const int stepsPerFrame = readIntArg(argc, argv, "--steps-per-frame", 16);
123 const int holdFrames = readIntArg(argc, argv, "--hold-frames", 120);
124
125 ExampleApp app;
126 if (!app.init("rayrai_rolling_spinning_friction", 1280, 720)) return -1;
127
128 auto world = std::make_shared<raisim::World>();
129 world->setTimeStep(0.001);
130 world->setERP(0.0, 0.0);
131 world->setContactSolverParam(1.0, 1.0, 1.0, 120, 1e-10);
132 world->setGravity({0.0, 0.0, -9.81});
133 world->setSleepingEnabled(true);
134 world->setSleepingParameters(0.012, 0.03, 25);
135 auto* ground = world->addGround(0.0, "ground");
136 ground->setAppearance("checkerboard");
137 world->setMaterialPairProp("ground", "body", 1.0, 0.0, 0.0, 1.0, 1e-3, 0.12, 0.08);
138
139 std::vector<DemoBody> bodies = createBodies(*world, grid);
140
141 auto viewer = std::make_shared<raisin::RayraiWindow>(world, 1280, 720);
142 viewer->setRenderQualitySettings(raisin::RayraiWindow::defaultRenderQualitySettings(raisin::RayraiWindow::RenderQualityPreset::Balanced));
143 raisim_examples::setRayraiBackgroundColorRgb255(*viewer, {24, 26, 30, 255});
144 raisim_examples::addRayraiBasicSceneLights(*viewer);
145
146 auto& camera = viewer->getCamera();
147 camera.position = glm::vec3(6.0f, -8.5f, 5.0f);
148 camera.target = glm::vec3(0.0f, 0.0f, 0.25f);
149 camera.yaw = 125.0f;
150 camera.pitch = -31.0f;
151 camera.zoom = 42.0f;
152 camera.zNear = 0.03f;
153 camera.zFar = 35.0f;
154 camera.setCameraFixedTarget(true);
155 camera.setCameraFixedDistance(true);
156 camera.update(false);
157
158 int stepInCycle = 0;
159 int heldFrames = 0;
160 std::size_t contactTotal = 0;
161 std::size_t lastContacts = 0;
162 double meanLinearSpeed = 0.0;
163 double meanAngularSpeed = 0.0;
164
165 while (!app.quit) {
166 app.processEvents();
167 if (app.quit) break;
168
169 if (stepInCycle < cycleSteps) {
170 const int frameSteps = std::min(stepsPerFrame, cycleSteps - stepInCycle);
171 for (int i = 0; i < frameSteps; ++i) {
172 world->integrate();
173 lastContacts = world->getContactProblem()->size();
174 contactTotal += lastContacts;
175 ++stepInCycle;
176 }
177 heldFrames = 0;
178 } else if (++heldFrames >= holdFrames) {
179 resetDemo(*world, bodies, grid);
180 stepInCycle = 0;
181 heldFrames = 0;
182 contactTotal = 0;
183 lastContacts = 0;
184 }
185
186 updateSleepingAppearance(*world, bodies);
187 computeMeanSpeeds(bodies, meanLinearSpeed, meanAngularSpeed);
188
189 app.beginFrame();
190 app.renderViewer(*viewer);
191
192 ImGui::SetNextWindowPos(ImVec2(12, 12), ImGuiCond_Always);
193 ImGui::SetNextWindowBgAlpha(0.72f);
194 ImGui::Begin("Rolling friction", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse);
195 ImGui::Text("step %d / %d", stepInCycle, cycleSteps);
196 ImGui::Text("bodies: %zu", bodies.size());
197 ImGui::Text("contacts: %zu", lastContacts);
198 ImGui::Text("average contacts: %.2f", stepInCycle > 0 ? double(contactTotal) / double(stepInCycle) : 0.0);
199 ImGui::Text("mean linear speed: %.3f m/s", meanLinearSpeed);
200 ImGui::Text("mean angular speed: %.3f rad/s", meanAngularSpeed);
201 ImGui::End();
202
203 app.endFrame();
204 }
205
206 viewer.reset();
207 app.shutdown();
208 return 0;
209}