Interactive 3D slides

4. Buttons in the slide

This example is a grid of 120 x 120 vertices whose positions are updated at each frame: either a ripple from the center, or parallel waves. The surface is driven by buttons written in the text of the slide, outside the frame of the demo. The current state is therefore visible in the slide, and the slide can also display a value of the program.

Get this example

Download: c3-cgp-waving-surface.zip. The zip contains the C++ program, its slide in reveal.js (slides.html) and in lhtml-site (lhtml-site/), the web build of the demo (ready to show), the bridge and the build script. The CGP project is needed only to recompile.

Try it: unzip it, and in the unzipped folder run python3 -m http.server 8080; then open http://localhost:8080/examples/c3-cgp-waving-surface/slides.html, the slide with its demo. To change the program: build and run.

Graphics: a mesh updated at each frameInterface: buttons in the slide, a panel, ImGui
Amplitude:
Live: these buttons are outside the frame, as in a slide.

What is new

  • Buttons in the slide, in HTML only, with slide-controls.js: data-demo-set gives the settings to apply, data-demo-value shows a value live, and a button gets the class on while its settings are the current values of the demo.
  • A CGP scene of its own: three files replace those of the template. main.cpp changes by one line (slide::parse(argc, argv)); the parameters are declared in scene.cpp.
  • The ImGui window of the template is hidden in a slide (the page has its panel), unless ?gui=1.
A trap of the web: the wireframe

draw_wireframe() of CGP uses glPolygonMode, which WebGL does not have: on the web it draws nothing, without an error. The wireframe here is a curve_drawable of segments (GL_LINES), drawn the same way on the desktop and on the web. The browser test of the example caught it: the image did not change when the wireframe was turned on.

Build and run

As example 3, with c3-cgp-waving-surface. Its browser test, demo.json, clicks the buttons of the slide and checks the images and the values (see Testing a demo).

The files

examples/c3-cgp-waving-surface/
  src/main.cpp       the main() of the template, plus slide::parse
  src/scene.hpp      the parameters of the wave
  src/scene.cpp      the scene: the grid, the wave, the wireframe, the declared parameters
  slides.html        the slide, with its buttons (reveal.js)
  lhtml-site/        the same slide, made with lhtml-site
  demo.json          the browser test of the example

src/scene.cpp

scene.cpp

Show the full file: scene.cpp (145 lines)
#include "scene.hpp"
#include "slide_bridge.hpp"

#include <cmath>

using namespace cgp;


void scene_structure::initialize()
{
	camera_control.initialize(inputs, window);
	camera_control.set_rotation_axis_z();
	camera_control.look_at({2.1f, -2.1f, 1.5f}, {0, 0, -0.15f}, {0, 0, 1});

	// A grid of 120 x 120 vertices, moved at each frame (CGP How-to: update a mesh every frame)
	int const N = 120;
	surface_mesh = mesh_primitive_grid({-1, -1, 0}, {1, -1, 0}, {1, 1, 0}, {-1, 1, 0}, N, N);
	surface.initialize_data_on_gpu(surface_mesh);
	surface.material.color = {0.35f, 0.58f, 0.85f};
	surface.material.phong.specular = 0.25f;

	// The wireframe: one grid line out of 6 in each direction (all the edges of 120 x 120 vertices
	// would cover the surface), each line following the surface vertex by vertex.
	// mesh_primitive_grid stores the vertex (ku, kv) at the index ku * N + kv.
	int const step = 6;
	auto index = [N](int ku, int kv) { return static_cast<unsigned int>(ku * N + kv); };
	for (int ku = 0; ku < N; ++ku)
		for (int kv = 0; kv < N; ++kv) {
			bool const line_u = (ku % step == 0) || ku == N - 1;   // ku fixed, along kv
			bool const line_v = (kv % step == 0) || kv == N - 1;   // kv fixed, along ku
			if (line_u && kv + 1 < N) wire_edges.push_back(uint2{index(ku, kv), index(ku, kv + 1)});
			if (line_v && ku + 1 < N) wire_edges.push_back(uint2{index(ku, kv), index(ku + 1, kv)});
		}
	wire_position.resize(2 * wire_edges.size());
	update_wire();
	wire.display_type = curve_drawable_display_type::Segments;
	wire.initialize_data_on_gpu(wire_position);
	wire.color = {0.1f, 0.15f, 0.3f};

	// The parameters of the demo, declared once: the panel of the page, the buttons of the
	// slide and postMessage go through them. Their values given at start (?ampl=0.2) are applied here.
	slide::param("ampl", wave.amplitude, 0.0f, 0.3f, 0.01f).with_label("amplitude", "<i>A</i>");
	slide::param("k", wave.wave_number, 2.0f, 20.0f, 0.5f).with_label("wave number", "<i>k</i>");
	slide::param("speed", wave.speed, 0.0f, 10.0f, 0.1f).with_label("speed", "<i>&omega;</i>");
	slide::param("damping", wave.damping, 0.0f, 4.0f, 0.1f).with_label("damping", "<i>d</i>");
	slide::param("shape", wave.shape, {{"ripple", "Ripple"}, {"waves", "Waves"}})
		.on_change([this] { t = 0; });
	slide::param("wireframe", wave.wireframe).with_label("Wireframe");
	slide::param("play", wave.play).with_label("Play");
	slide::param("gui", wave.gui).with_label("ImGui");
	slide::action("drop", [this] { t = 0; wave.shape = "ripple"; }).with_label("Drop");
}


// Height of the surface at (x, y), time t
static float height(wave_parameters const& w, float x, float y, float t)
{
	if (w.shape == "waves")
		return w.amplitude * std::sin(w.wave_number * x - w.speed * t);

	// a ripple from the center: its front moves at the speed omega / k
	float const r = std::sqrt(x * x + y * y);
	float const front = (w.wave_number > 0 ? w.speed / w.wave_number : 0) * t;
	float const reached = std::fmin(std::fmax((front - r) * 8.0f, 0.0f), 1.0f);   // smooth front
	return reached * w.amplitude * std::exp(-w.damping * r) * std::sin(w.wave_number * r - w.speed * t);
}


void scene_structure::display_frame()
{
	environment.camera_view = camera_control.camera().matrix_view();
	environment.light = camera_control.camera_model.position();

	if (wave.play)
		t += inputs.time_interval;

	// CPU: move the vertices, then their normals
	for (vec3& p : surface_mesh.position)
		p.z = height(wave, p.x, p.y, t);
	surface_mesh.normal_update();

	// GPU: overwrite the buffers (same size, no reallocation)
	surface.vbo_position.update(surface_mesh.position);
	surface.vbo_normal.update(surface_mesh.normal);

	draw(surface, environment);
	if (wave.wireframe) {
		update_wire();
		wire.vbo_position.update(wire_position);
		draw(wire, environment);
	}
}


// The two ends of each edge, slightly above the surface (no polygon offset for lines in WebGL)
void scene_structure::update_wire()
{
	for (size_t k = 0; k < wire_edges.size(); ++k) {
		wire_position[2 * k] = surface_mesh.position[wire_edges[k].x] + vec3{0, 0, 0.002f};
		wire_position[2 * k + 1] = surface_mesh.position[wire_edges[k].y] + vec3{0, 0, 0.002f};
	}
}


void scene_structure::display_gui()
{
	// The template always draws its ImGui window: in a slide, the page has its own panel,
	// so the window is hidden unless gui=1. ImGui keeps a corner of a window on screen:
	// it is also collapsed and made transparent.
	ImGui::GetStyle().Alpha = wave.gui ? 1.0f : 0.0f;
	if (!wave.gui) {
		ImGui::SetWindowCollapsed(true);
		ImGui::SetWindowPos(ImVec2(-10000, -10000));
		return;
	}
	ImGui::SetWindowCollapsed(false);
	ImGui::SetWindowPos(ImVec2(10, 10));
	// the same variables as the panel of the page (which shows the new values at its next change)
	ImGui::SliderFloat("amplitude", &wave.amplitude, 0.0f, 0.3f);
	ImGui::SliderFloat("wave number", &wave.wave_number, 2.0f, 20.0f);
	ImGui::SliderFloat("speed", &wave.speed, 0.0f, 10.0f);
	ImGui::SliderFloat("damping", &wave.damping, 0.0f, 4.0f);
	ImGui::Checkbox("wireframe", &wave.wireframe);
	if (ImGui::Button("drop"))
		slide::set("drop", "");
}


void scene_structure::mouse_move_event()
{
	if (!inputs.keyboard.shift)
		camera_control.action_mouse_move();
}
void scene_structure::mouse_click_event()
{
	camera_control.action_mouse_click();
}
void scene_structure::keyboard_event()
{
	camera_control.action_keyboard();
}
void scene_structure::idle_frame()
{
	camera_control.idle_frame();
}

src/scene.hpp

scene.hpp

Show the full file: scene.hpp (55 lines)
#pragma once

#include "cgp/cgp.hpp"
#include "environment.hpp"

#include <string>

using cgp::mesh;
using cgp::mesh_drawable;


// The parameters of the wave: declared to the bridge in initialize(), so that the page,
// the slide and the ImGui window change the same variables
struct wave_parameters {
	float amplitude = 0.12f;
	float wave_number = 9.0f;     // spatial frequency (radians per unit of length)
	float speed = 4.0f;           // temporal frequency (radians per second)
	float damping = 1.0f;         // decay with the distance to the center
	std::string shape = "ripple"; // ripple (from the center) or waves (parallel)
	bool wireframe = false;
	bool play = true;
	bool gui = false;             // the ImGui window of the template (hidden in a slide)
};


struct scene_structure : cgp::scene_inputs_generic {

	void initialize();
	void display_frame();
	void display_gui();

	environment_structure environment;
	window_structure window;
	input_devices inputs;

	camera_controller_orbit_euler camera_control;
	camera_projection_perspective camera_projection;

	mesh surface_mesh;            // CPU copy, moved at each frame
	mesh_drawable surface;        // GPU buffers

	// The wireframe as segments: glPolygonMode (used by draw_wireframe) does not exist in WebGL
	cgp::curve_drawable wire;
	cgp::numarray<cgp::uint2> wire_edges;   // pairs of vertices of the grid lines
	cgp::numarray<cgp::vec3> wire_position; // their two ends, updated at each frame
	wave_parameters wave;
	float t = 0;                  // time since the last drop

	void update_wire();

	void mouse_move_event();
	void mouse_click_event();
	void keyboard_event();
	void idle_frame();
};

src/main.cpp

main.cpp

// CGP library
#include "cgp/cgp.hpp"

// Running application
#include "application.hpp"

// Custom scene of this code
#include "scene.hpp"

// interactive-3d-slides: the parameters of the demo, set from the slide
#include "slide_bridge.hpp"


int main(int argc, char* argv[])
{
	// The only change to the main() of the template: keep the arguments
	// (--ampl 0.2 ..., given by the address of the iframe)
	slide::parse(argc, argv);

	scene_structure scene;
	application_structure app;
	app.initialize(argv[0], &scene);

	app.start_loop();

	return 0;
}

slides.html

The buttons below the frame, and slide-controls.js. slides.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>A waving surface</title>
<!--
  A slide of reveal.js with the demo of this example. Open it through a web server, from the root of
  the repository: python3 -m http.server 8080, then http://localhost:8080/examples/c3-cgp-waving-surface/slides.html
  reveal.js comes from a CDN: for a talk without network, download it next to this file.
-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/theme/white.css">
<style>
  .reveal iframe.demo { width: 100%; height: 540px; border: 0; }
  .reveal .row { font-size: 0.6em; margin-top: 12px; }
  .reveal .row button { font: inherit; padding: 4px 14px; margin: 0 4px; border-radius: 8px;
                        border: 2px solid #999; background: white; cursor: pointer; }
  .reveal .row button.on { background: #333; color: white; border-color: #333; }
</style>
</head>
<body>
<div class="reveal"><div class="slides">
<section>
  <h3>A waving surface</h3>
  <iframe class="demo" id="demo" data-src="web/index.html?controls=ampl,k,speed&panel=bl"></iframe>
  <div class="row">
    <button data-demo-set="shape=ripple">Ripple</button>
    <button data-demo-set="shape=waves">Waves</button>
    <button data-demo-set="drop">Drop</button>
    <button data-demo-set="ampl=0.25&amp;k=14">Strong</button>
    Amplitude: <span data-demo-value="ampl" data-digits="2"></span>
  </div>
</section>
</div></div>
<script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.js"></script>
<script src="../../bridge/slide-controls.js"></script>
<script>Reveal.initialize({hash: true});</script>
</body>
</html>

In reveal.js all the slides are in one page: with several demos, give each frame an id and name it on its buttons, data-demo="#surface".

lhtml-site/

The same slide in lhtml-site (open it), organized as in example 1; only the slide changes, src/01_waving-surface/index.html.j2:

{% set layout = 'side' %}

= A waving surface

The buttons below are in the text of the slide, outside the frame.

<div class="controls">
<p>
<button data-demo-set="shape=ripple">Ripple</button>
<button data-demo-set="shape=waves">Waves</button>
<button data-demo-set="drop">Drop</button>
<button data-demo-set="ampl=0.25&amp;k=14">Strong</button>
</p>
<p>Amplitude: <span class="value" data-demo-value="ampl" data-digits="2"></span></p>
</div>

media::
demo::../_demo/index.html?controls=ampl,k,speed&panel=bl(.live)
img::../_demo/poster.png(.still)
::

Next: 5. GUI with ImGui.