1. Rotating cube
This first example is a minimal program: a cube that rotates by itself, written in raw OpenGL 3.3 with GLFW (about 200 lines). The slide sets its speed and its tilt through the address of the frame, and there is no control on screen. The same source file is compiled for the desktop and for the web.
Download: a1-opengl-cube.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, the CMake module and glad.
Try it: unzip it, and in the unzipped folder run python3 -m http.server 8080; then open http://localhost:8080/examples/a1-opengl-cube/slides.html, the slide with its demo. To change the program: build and run.
?speed=0.2&tilt=25.Build and run
On Windows: see the commands of Before you start.
On the desktop, from examples/a1-opengl-cube/:
cmake -S . -B build cmake --build build ./build/project --speed 0.3 --tilt 40
For the web, with the Emscripten SDK activated:
emcmake cmake -S . -B build_web cmake --build build_web
build_web/ then holds index.html, project.js and project.wasm, and the build copies them into web/ and
lhtml-site/src/_demo/: the slides show the new version of the program (to keep web/ as it is, add
-DSLIDE_DEMO_PUBLISH=OFF to the first command). Show the slide through a web server, from the root of the
repository (or of the unzipped folder):
python3 -m http.server 8080
and open http://localhost:8080/examples/a1-opengl-cube/slides.html. After a click in the cube, the right
arrow still goes to the next slide.
The files
examples/a1-opengl-cube/ main.cpp the program CMakeLists.txt its build, desktop and web slides.html the slide that shows it (reveal.js) lhtml-site/ the same slide, made with lhtml-site web/ the web build: index.html (slide-frame.html), project.js, project.wasm examples/cmake/raw_opengl_demo.cmake the build of the raw OpenGL examples examples/third_party/glad/ the OpenGL loader, for the desktop bridge/ the bridge between the program and the slide
main.cpp
One source for the desktop (OpenGL 3.3 core, GLFW, glad) and for the web (WebGL 2, which is OpenGL ES 3.0).
The four differences are marked with #ifdef __EMSCRIPTEN__:
- The headers:
<GLES3/gl3.h>on the web, glad on the desktop. - The first line of the shaders:
#version 300 esand aprecisionon the web,#version 330 coreon the desktop. The body of the shaders is the same; the program prepends the right line (shader_header). - The size of the drawing: the canvas of the page. The window is created at its size, otherwise
glfwCreateWindowresizes the canvas, and the size is read at each frame (surface_size). - The main loop: on the web the browser calls
frame()at each refresh (emscripten_set_main_loop).
The settings come from the command line, which the page of the demo builds from its address
(?speed=0.2 gives --speed 0.2): four lines with the bridge, at the start of main().
Show the full file: main.cpp (212 lines)
// A1 - Raw OpenGL 3.3: a turning cube, set by the address of the slide. // // One source for the native program (OpenGL 3.3 core, GLFW, glad) and for the web // (WebGL 2 = OpenGL ES 3.0, compiled with Emscripten). The differences are marked // with #ifdef __EMSCRIPTEN__: the headers, the first line of the shaders, the size // of the drawing surface and the main loop. // // Settings (command line, or address of the iframe: index.html?speed=0.3&tilt=30&background=dark) // --speed <turns per second> --tilt <degrees> --background <light|dark> --size WxH (native) #ifdef __EMSCRIPTEN__ #include <emscripten/emscripten.h> #include <emscripten/html5.h> #include <GLES3/gl3.h> #else #include "glad.hpp" #endif #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include "slide_bridge.hpp" #include <cmath> #include <cstdio> #include <string> // The settings of the demo float speed = 0.15f; // turns per second float tilt = 25.0f; // degrees, rotation around the horizontal axis std::string background = "light"; GLFWwindow* window = nullptr; GLuint program = 0, vao = 0; GLint uniform_matrix = -1; // The first line of the shaders: OpenGL 3.3 core on the desktop, OpenGL ES 3.0 on the web #ifdef __EMSCRIPTEN__ char const* const shader_header = "#version 300 es\nprecision highp float;\n"; #else char const* const shader_header = "#version 330 core\n"; #endif char const* const vertex_shader = R"( layout (location = 0) in vec3 position; layout (location = 1) in vec3 color; uniform mat4 matrix; // projection * view * model out vec3 vertex_color; void main() { vertex_color = color; gl_Position = matrix * vec4(position, 1.0); } )"; char const* const fragment_shader = R"( in vec3 vertex_color; out vec4 frag_color; void main() { frag_color = vec4(vertex_color, 1.0); } )"; GLuint compile(GLenum type, char const* body) { GLuint shader = glCreateShader(type); char const* sources[] = {shader_header, body}; glShaderSource(shader, 2, sources, nullptr); glCompileShader(shader); GLint ok = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); if (!ok) { char log[1024]; glGetShaderInfoLog(shader, sizeof(log), nullptr, log); std::fprintf(stderr, "Shader error: %s\n", log); } return shader; } // 4x4 matrices, column-major as OpenGL reads them: m[column * 4 + row] struct mat4 { float m[16]; }; mat4 multiply(mat4 const& a, mat4 const& b) { mat4 r{}; for (int c = 0; c < 4; ++c) for (int l = 0; l < 4; ++l) for (int k = 0; k < 4; ++k) r.m[c * 4 + l] += a.m[k * 4 + l] * b.m[c * 4 + k]; return r; } mat4 rotation_x(float a) { float c = std::cos(a), s = std::sin(a); return {{1,0,0,0, 0,c,s,0, 0,-s,c,0, 0,0,0,1}}; } mat4 rotation_y(float a) { float c = std::cos(a), s = std::sin(a); return {{c,0,-s,0, 0,1,0,0, s,0,c,0, 0,0,0,1}}; } mat4 translation_z(float z) { return {{1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,z,1}}; } mat4 perspective(float fov_y, float aspect, float near, float far) { float const f = 1.0f / std::tan(fov_y / 2); return {{f / aspect,0,0,0, 0,f,0,0, 0,0,(far + near) / (near - far),-1, 0,0,2 * far * near / (near - far),0}}; } // A cube of side 1 centered at the origin: 6 faces of 2 triangles, one color per face void create_cube() { float const p[8][3] = {{-.5f,-.5f,-.5f}, {.5f,-.5f,-.5f}, {.5f,.5f,-.5f}, {-.5f,.5f,-.5f}, {-.5f,-.5f,.5f}, {.5f,-.5f,.5f}, {.5f,.5f,.5f}, {-.5f,.5f,.5f}}; int const faces[6][4] = {{4,5,6,7}, {1,0,3,2}, {5,1,2,6}, {0,4,7,3}, {7,6,2,3}, {0,1,5,4}}; float const colors[6][3] = {{.90f,.30f,.25f}, {.25f,.55f,.85f}, {.30f,.70f,.40f}, {.95f,.70f,.20f}, {.60f,.40f,.80f}, {.35f,.75f,.80f}}; float data[36 * 6]; int n = 0; for (int f = 0; f < 6; ++f) for (int corner : {0, 1, 2, 0, 2, 3}) { for (int k = 0; k < 3; ++k) data[n++] = p[faces[f][corner]][k]; for (int k = 0; k < 3; ++k) data[n++] = colors[f][k]; } GLuint vbo; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); } // Size of the drawing surface, in pixels void surface_size(int& width, int& height) { #ifdef __EMSCRIPTEN__ // the page sizes the canvas to the iframe (slide-frame.html) emscripten_get_canvas_element_size("#canvas", &width, &height); #else glfwGetFramebufferSize(window, &width, &height); // pixels, also on a Retina screen #endif } void frame() { int width = 1, height = 1; surface_size(width, height); glViewport(0, 0, width, height); float const shade = (background == "dark") ? 0.12f : 1.0f; glClearColor(shade, shade, shade, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); float const pi = 3.14159265f; float const angle = 2 * pi * speed * float(glfwGetTime()); mat4 const model = multiply(rotation_x(tilt * pi / 180), rotation_y(angle)); mat4 const view = translation_z(-3.0f); mat4 const projection = perspective(40 * pi / 180, float(width) / float(height > 0 ? height : 1), 0.1f, 10.0f); mat4 const matrix = multiply(projection, multiply(view, model)); glUseProgram(program); glUniformMatrix4fv(uniform_matrix, 1, GL_FALSE, matrix.m); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, 36); glfwSwapBuffers(window); glfwPollEvents(); } int main(int argc, char* argv[]) { // The settings: from the command line, or from the address of the iframe slide::parse(argc, argv); slide::param("speed", speed, 0.0f, 1.0f, 0.01f).with_label("speed (turns/s)"); slide::param("tilt", tilt, -90.0f, 90.0f, 1.0f).with_label("tilt (degrees)"); slide::param("background", background, {"light", "dark"}); int width = 800, height = 600; std::sscanf(slide::arg("size", "800x600").c_str(), "%dx%d", &width, &height); if (!glfwInit()) return 1; #ifdef __EMSCRIPTEN__ // The window is the canvas, sized by the page to the iframe: glfwCreateWindow would resize it emscripten_get_canvas_element_size("#canvas", &width, &height); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); #else glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // needed on macOS #endif window = glfwCreateWindow(width, height, "A1 - OpenGL cube", nullptr, nullptr); if (!window) { std::fprintf(stderr, "Cannot create an OpenGL 3.3 window\n"); return 1; } glfwMakeContextCurrent(window); #ifndef __EMSCRIPTEN__ if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::fprintf(stderr, "Cannot load OpenGL\n"); return 1; } glfwSwapInterval(1); #endif program = glCreateProgram(); glAttachShader(program, compile(GL_VERTEX_SHADER, vertex_shader)); glAttachShader(program, compile(GL_FRAGMENT_SHADER, fragment_shader)); glLinkProgram(program); uniform_matrix = glGetUniformLocation(program, "matrix"); create_cube(); glEnable(GL_DEPTH_TEST); #ifdef __EMSCRIPTEN__ // The browser calls frame() at each display refresh; main() returns to it emscripten_set_main_loop(frame, 0, 1); #else while (!glfwWindowShouldClose(window)) frame(); glfwTerminate(); #endif return 0; }
CMakeLists.txt
CMakeLists.txt, and the module it includes, raw_opengl_demo.cmake: on the desktop it links GLFW and glad; on the web it adds the options of Emscripten and copies the page of the demo next to the build.
cmake_minimum_required(VERSION 3.16) project(a1-opengl-cube CXX) include(../cmake/raw_opengl_demo.cmake) raw_opengl_demo(project main.cpp)
Show the full file: raw_opengl_demo.cmake (53 lines)
# raw_opengl_demo(<target> <sources...>): a demo in raw OpenGL 3.3, native and web. # # Native: OpenGL 3.3 core, GLFW (installed: brew install glfw, apt install libglfw3-dev), glad. # Web: emcmake cmake -S . -B build_web && cmake --build build_web # gives project.js and project.wasm, and index.html (bridge/slide-frame.html) next to them, # then copies these three files into web/ (the folder the slides load) and, if it exists, into # lhtml-site/src/_demo/: after a build, the slides show the new version of the program. # To keep web/ as it is: emcmake cmake -S . -B build_web -DSLIDE_DEMO_PUBLISH=OFF set(INTERACTIVE_3D_SLIDES_ROOT "${CMAKE_CURRENT_LIST_DIR}/../..") set(SLIDE_BRIDGE_DIR "${INTERACTIVE_3D_SLIDES_ROOT}/bridge") set(SLIDE_GLAD_DIR "${INTERACTIVE_3D_SLIDES_ROOT}/examples/third_party/glad") option(SLIDE_DEMO_PUBLISH "Copy the web build into web/ and lhtml-site/src/_demo/" ON) function(raw_opengl_demo target) add_executable(${target} ${ARGN} "${SLIDE_BRIDGE_DIR}/slide_bridge.cpp") target_compile_features(${target} PRIVATE cxx_std_17) target_include_directories(${target} PRIVATE "${SLIDE_BRIDGE_DIR}") if(EMSCRIPTEN) target_link_options(${target} PRIVATE -sUSE_GLFW=3 -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sEXPORTED_FUNCTIONS=_main,_slide_set,_slide_describe -sEXPORTED_RUNTIME_METHODS=ccall) # the page of the demo, for a slide add_custom_command(TARGET ${target} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy "${SLIDE_BRIDGE_DIR}/slide-frame.html" "$<TARGET_FILE_DIR:${target}>/index.html") if(SLIDE_DEMO_PUBLISH) set(built "$<TARGET_FILE_DIR:${target}>/index.html" "$<TARGET_FILE_DIR:${target}>/project.js" "$<TARGET_FILE_DIR:${target}>/project.wasm") set(web "${CMAKE_CURRENT_SOURCE_DIR}/web") add_custom_command(TARGET ${target} POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory "${web}" COMMAND ${CMAKE_COMMAND} -E copy ${built} "${web}/" COMMENT "web build copied into web/") if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/lhtml-site") # the lhtml-site slide also needs the poster (its image in a PDF) and slide-controls.js set(demo "${CMAKE_CURRENT_SOURCE_DIR}/lhtml-site/src/_demo") add_custom_command(TARGET ${target} POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory "${demo}" COMMAND ${CMAKE_COMMAND} -E copy ${built} "${SLIDE_BRIDGE_DIR}/slide-controls.js" "${CMAKE_CURRENT_SOURCE_DIR}/poster.png" "${demo}/" COMMENT "web build copied into lhtml-site/src/_demo/") endif() endif() else() find_package(glfw3 3.3 REQUIRED) find_package(OpenGL REQUIRED) target_sources(${target} PRIVATE "${SLIDE_GLAD_DIR}/glad.cpp") target_include_directories(${target} PRIVATE "${SLIDE_GLAD_DIR}") target_link_libraries(${target} PRIVATE glfw OpenGL::GL ${CMAKE_DL_LIBS}) endif() endfunction()
slides.html
The slide uses reveal.js, and contains a frame whose address gives the settings. The attribute data-src
loads the demo when its slide comes near. slides.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Rotating cube</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/a1-opengl-cube/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>Rotating cube</h3> <iframe class="demo" id="demo" data-src="web/index.html?speed=0.2&tilt=25"></iframe> </section> </div></div> <script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.js"></script> <script>Reveal.initialize({hash: true});</script> </body> </html>
The page of the demo, web/index.html, is slide-frame.html of the
bridge, copied by the build; its code and that of the two C++ files of the bridge are in the
reference.
lhtml-site/
The same slide, made with lhtml-site: a presentation of a single slide, which builds as it is from the zip
(open it). In this folder, lhtml-site builds it into .site/html/, and
lhtml-site --serve shows it on http://127.0.0.1:8000/. In the slide, (.live) and (.still) give a
class to the frame and to the image: the frame is shown on screen, the image in a PDF (see talk.css).
lhtml-site/ configure.yaml the build, and how to fill src/_demo/ from a clone of the repository src/01_rotating-cube/index.html.j2 the slide src/_style/talk.css the buttons of the slide, and the image of the demo in a PDF src/_demo/ the demo: the web build, its poster, slide-controls.js (in the zip)
{% set layout = 'side' %}
= Rotating cube
* A program in raw OpenGL 3.3, about 200 lines
* Compiled to WebAssembly with Emscripten
* Set by the address of the frame: `?speed=0.2&tilt=25`
media::
demo::../_demo/index.html?speed=0.2&tilt=25(.live)
img::../_demo/poster.png(.still)
::
# The slide of the example a1-opengl-cube, made with lhtml-site (the same as ../slides.html, made with reveal.js). # # The demo goes in src/_demo/: the web build of the example, its poster, and slide-controls.js. The zip of # the example on the site of the tutorial already holds it. From a clone of the repository, in this folder: # mkdir -p src/_demo && cp -R ../web/. ../poster.png ../../../bridge/slide-controls.js src/_demo/ # # lhtml-site build into .site/: html/ in the browser # lhtml-site --serve --watch preview on http://127.0.0.1:8000/ # # A folder whose name starts with an underscore is not a slide: it is copied as it is. source_directory: 'src/' site_directory: '.site/' targets: html: {theme: slides} keywords: cssAbs: [_style/talk.css] # the buttons of the slide, and the image of the demo in a PDF jsAbs: [_demo/slide-controls.js] # the buttons of the slide drive the demo
Next: 2. Uniforms driven live: the same cube, changed while it runs.