1. Cube en rotation
Ce premier exemple est un programme minimal : un cube qui tourne tout seul, écrit en OpenGL 3.3 brut avec GLFW (environ 200 lignes). La slide règle sa vitesse et son inclinaison par l'adresse du cadre, et il n'y a aucun contrôle à l'écran. Le même fichier source est compilé pour le bureau et pour le web.
Télécharger : a1-opengl-cube.zip. Le zip contient le programme C++, sa slide en reveal.js (slides.html) et en lhtml-site (lhtml-site/), la compilation web de la démo (prête à montrer), le pont, le module CMake et glad.
L'essayer : décompressez-le, et dans le dossier décompressé lancez python3 -m http.server 8080 ; puis ouvrez http://localhost:8080/examples/a1-opengl-cube/slides.html, la slide avec sa démo. Pour modifier le programme : compiler et lancer.
?speed=0.2&tilt=25.Compiler et lancer
Sous Windows : voir les commandes d'Avant de commencer.
Sur le bureau, depuis examples/a1-opengl-cube/ :
cmake -S . -B build cmake --build build ./build/project --speed 0.3 --tilt 40
Pour le web, avec le SDK Emscripten activé :
emcmake cmake -S . -B build_web cmake --build build_web
build_web/ contient alors index.html, project.js et project.wasm, et la compilation les copie dans
web/ et lhtml-site/src/_demo/ : les slides montrent la nouvelle version du programme (pour garder web/
tel quel, ajoutez -DSLIDE_DEMO_PUBLISH=OFF à la première commande). Montrez la slide à travers un serveur
web, depuis la racine du dépôt (ou du dossier décompressé) :
python3 -m http.server 8080
et ouvrez http://localhost:8080/examples/a1-opengl-cube/slides.html. Après un clic dans le cube, la flèche
droite passe toujours à la slide suivante.
Les fichiers
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
Une seule source pour le bureau (OpenGL 3.3 core, GLFW, glad) et pour le web (WebGL 2, c'est-à-dire OpenGL
ES 3.0). Les quatre différences sont marquées par #ifdef __EMSCRIPTEN__ :
- Les en-têtes :
<GLES3/gl3.h>sur le web, glad sur le bureau. - La première ligne des shaders :
#version 300 eset uneprecisionsur le web,#version 330 coresur le bureau. Le corps des shaders est le même ; le programme ajoute devant la bonne ligne (shader_header). - La taille du dessin : celle du canvas de la page. La fenêtre est créée à sa taille, sinon
glfwCreateWindowredimensionne le canvas, et la taille est lue à chaque image (surface_size). - La boucle principale : sur le web, le navigateur appelle
frame()à chaque rafraîchissement (emscripten_set_main_loop).
Les réglages viennent de la ligne de commande, que la page de la démo construit à partir de son adresse
(?speed=0.2 donne --speed 0.2) : quatre lignes avec le pont, au début de main().
Afficher le fichier complet : main.cpp (212 lignes)
// 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, et le module qu'il inclut, raw_opengl_demo.cmake : sur le bureau il lie GLFW et glad ; sur le web il ajoute les options d'Emscripten et copie la page de la démo à côté de la compilation.
cmake_minimum_required(VERSION 3.16) project(a1-opengl-cube CXX) include(../cmake/raw_opengl_demo.cmake) raw_opengl_demo(project main.cpp)
Afficher le fichier complet : raw_opengl_demo.cmake (53 lignes)
# 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
La slide utilise reveal.js, et contient un cadre dont l'adresse donne les réglages. L'attribut data-src
charge la démo quand sa slide approche. 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>
La page de la démo, web/index.html, est slide-frame.html du pont,
copiée par la compilation ; son code et celui des deux fichiers C++ du pont sont dans la
référence.
lhtml-site/
La même slide, faite avec lhtml-site : une présentation d'une seule slide, qui se construit telle quelle depuis
le zip (l'ouvrir). Dans ce dossier, lhtml-site la construit dans
.site/html/, et lhtml-site --serve la montre sur http://127.0.0.1:8000/. Dans la slide, (.live) et (.still) donnent une
classe au cadre et à l'image : le cadre est montré à l'écran, l'image dans un PDF (voir 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
Ensuite : 2. Uniforms pilotés en direct : le même cube, changé pendant qu'il tourne.