3. Programme CGP
Un programme écrit avec une bibliothèque marche de la même façon, si la bibliothèque se compile pour le web. Cet exemple est le projet modèle de CGP, une bibliothèque C++ faite pour enseigner l'informatique graphique, compilé pour le web sans changer une ligne. La souris tourne la caméra, sa fenêtre ImGui reste à l'écran, et les flèches passent toujours aux slides.
Télécharger : c1-cgp-template.zip. Le zip contient la slide en reveal.js (slides.html) et en lhtml-site (lhtml-site/), la compilation web de la démo (prête à montrer), le pont et le script de compilation. Le programme C++ est le projet modèle de CGP lui-même, nécessaire
seulement pour recompiler.
L'essayer : décompressez-le, et dans le dossier décompressé lancez python3 -m http.server 8080 ; puis ouvrez http://localhost:8080/examples/c1-cgp-template/slides.html, la slide avec sa démo. Pour modifier le programme : compiler et lancer.
Comment sont compilés les exemples CGP
Un projet CGP est un projet modèle : CMakeLists.txt, la bibliothèque dans cgp/, votre scène dans src/, les
shaders dans shaders/. Les exemples de ce tutoriel ne contiennent que les fichiers qui diffèrent du projet modèle. Le
script de compilation les pose sur une copie du projet modèle, ajoute le pont, et compile avec le CMakeLists.txt de CGP
lui-même :
build/<example>-stage/ a copy of the CGP project (CGP_DIR) src/ the template, then the files of the example on top, and the bridge CMakeLists.txt the one of CGP, plus the link options of the bridge
Cet exemple n'a aucun fichier à lui : c'est le projet modèle tel quel. Avec le SDK Emscripten activé, depuis la racine du dépôt (ou du dossier décompressé) :
git clone https://github.com/drohmer/cgp-2027.git ../cgp-2027 # the CGP project, once CGP_DIR=../cgp-2027 python3 scripts/build_examples.py c1-cgp-template CGP_DIR=../cgp-2027 python3 scripts/build_examples.py --native c1-cgp-template
CGP_DIR est le dossier du projet CGP. Sous Windows : voir les commandes d'Avant de commencer.
La première commande compile pour le web, copie le résultat dans examples/c1-cgp-template/web/ et
examples/c1-cgp-template/lhtml-site/src/_demo/, puis teste la démo dans un navigateur et capture son poster
(si Playwright est installé, voir Tester une démo) ; --native compile aussi la version bureau et la lance deux secondes. Dans votre propre
projet CGP, c'est trois étapes : copiez slide_bridge.hpp et slide_bridge.cpp dans src/, ajoutez les options
d'édition de liens du pont à la compilation web du CMakeLists.txt, et prenez slide-frame.html comme page de
la démo.
scripts/build_examples.py, le script de compilation (télécharger)
r"""Build the examples for the web, test them in a browser, and capture their posters. Usage (the Emscripten SDK active: source <emsdk>/emsdk_env.sh), from the root of the repository: git clone https://github.com/drohmer/cgp-2027.git ../cgp-2027 the CGP project, once CGP_DIR=../cgp-2027 python3 scripts/build_examples.py c3-cgp-waving-surface CGP_DIR=../cgp-2027 python3 scripts/build_examples.py all the examples On Windows (PowerShell; the Emscripten SDK active with <emsdk>\emsdk_env.ps1, and Ninja installed: winget install Ninja-build.Ninja): $env:CGP_DIR = "..\cgp-2027" python scripts\build_examples.py c3-cgp-waving-surface Options: --native also build the desktop version, and run it for two seconds --no-test skip the browser test and the poster (they need Playwright: pip install playwright, then python3 -m playwright install chromium); skipped anyway when Playwright is missing Environment: CGP_DIR a clone of the CGP project (needed for the CGP examples only) LHTML_PYTHON a Python with Playwright, for the browser test (default: this Python) Two kinds of examples, given by the field "kind" of their demo.json: "opengl" examples/<id>/CMakeLists.txt (raw OpenGL 3.3, examples/cmake/raw_opengl_demo.cmake) "cgp" only the files that differ from the CGP template project: src/ (scene.cpp...), shaders/, assets/. They are staged over a copy of the CGP project (CGP_DIR: its CMakeLists.txt, cgp/, src/, shaders/, scripts/) in build/<id>-stage/, with the bridge, and built by the CMakeLists of CGP itself. For each example: 1. web build in build/<id>-web/ (and, with --native, a native build in build/<id>-native/, run for two seconds to check that it starts); 2. copy of index.html and project.js/.wasm/.data into examples/<id>/web/ (committed: the demos work without Emscripten, and offline), and into examples/<id>/lhtml-site/src/_demo/ (with the poster and slide-controls.js): after a build, both slides show the new version; 3. test in a browser (tests/test_demo.py) and poster examples/<id>/poster.png (image for the PDF). Log: build/build_examples.log. Exit code 0 when every example builds and passes. """ import json, os, shutil, subprocess, sys, time ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) EXAMPLES = os.path.join(ROOT, 'examples') BRIDGE = os.path.join(ROOT, 'bridge') BUILD = os.path.join(ROOT, 'build') OUTPUTS = ['index.html', 'project.js', 'project.wasm', 'project.data'] # Appended to the CMakeLists.txt of CGP in a staged project CGP_CMAKE_SUFFIX = ''' # ---- interactive-3d-slides: the bridge, and the page of the demo for a slide # paths relative to the project in __FILE__ (messages of the assertions of CGP): no path of the # machine of the build in project.wasm if(NOT MSVC) target_compile_options(${{PROJECT_NAME}} PRIVATE "-fmacro-prefix-map=${{CMAKE_SOURCE_DIR}}/=") endif() if(EMSCRIPTEN) target_link_options(${{PROJECT_NAME}} PRIVATE -sEXPORTED_FUNCTIONS=_main,_slide_set,_slide_describe -sEXPORTED_RUNTIME_METHODS=ccall) # after the copy of the template of CGP (POST_BUILD commands run in order) add_custom_command(TARGET ${{PROJECT_NAME}} POST_BUILD COMMAND ${{CMAKE_COMMAND}} -E copy "{frame}" "${{CMAKE_BINARY_DIR}}/index.html") endif() ''' def log(message, stream): line = time.strftime('%H:%M:%S ') + message print(line, flush=True) stream.write(line + '\n') stream.flush() def run(command, stream, cwd=None): stream.write('$ ' + ' '.join(command) + '\n') stream.flush() return subprocess.run(command, cwd=cwd, stdout=stream, stderr=subprocess.STDOUT).returncode == 0 def stage_cgp(ident, cgp_dir): """A CGP project: the template, the files of the example on top, and the bridge.""" source = os.path.join(EXAMPLES, ident) stage = os.path.join(BUILD, ident + '-stage') shutil.rmtree(stage, ignore_errors=True) os.makedirs(stage) shutil.copy2(os.path.join(cgp_dir, 'CMakeLists.txt'), stage) for folder in ['cgp', 'src', 'shaders', 'scripts']: shutil.copytree(os.path.join(cgp_dir, folder), os.path.join(stage, folder)) for folder in ['src', 'shaders', 'assets']: if os.path.isdir(os.path.join(source, folder)): shutil.copytree(os.path.join(source, folder), os.path.join(stage, folder), dirs_exist_ok=True) for name in ['slide_bridge.hpp', 'slide_bridge.cpp']: shutil.copy2(os.path.join(BRIDGE, name), os.path.join(stage, 'src')) with open(os.path.join(stage, 'CMakeLists.txt'), 'a') as f: f.write(CGP_CMAKE_SUFFIX.format(frame=os.path.join(BRIDGE, 'slide-frame.html'))) return stage def native_program(build): """The native program: build/project, or build/project.exe on Windows, where Visual Studio puts it in a folder per configuration (build/Release/project.exe).""" for folder in ['', 'Release', 'RelWithDebInfo', 'Debug']: for name in ['project', 'project.exe']: candidate = os.path.join(build, folder, name) if os.path.isfile(candidate): return candidate return os.path.join(build, 'project') def check_native(build, project, stream): """Runs the native program for two seconds: it must start and not stop by itself. It runs from the root of its project: CGP looks for shaders/ from the current folder.""" program = native_program(build) stream.write(f'$ (cd {project}; {program}) (2 s)\n') stream.flush() process = subprocess.Popen([program], cwd=project, stdout=stream, stderr=subprocess.STDOUT) time.sleep(2) alive = process.poll() is None process.kill() process.wait() return alive def main(): args = sys.argv[1:] native = '--native' in args test = '--no-test' not in args args = [a for a in args if a not in ('--native', '--no-test')] # the full path: on Windows emcmake is emcmake.bat, which a subprocess finds only by its full name emcmake = shutil.which('emcmake') if emcmake is None: sys.exit('emcmake not found: activate the Emscripten SDK first ' '(source <emsdk>/emsdk_env.sh, or <emsdk>\\emsdk_env.bat on Windows)') python = os.environ.get('LHTML_PYTHON', sys.executable) if test and subprocess.run([python, '-c', 'import playwright'], capture_output=True).returncode != 0: print(f'Playwright is not installed for {python}: the browser test and the poster are skipped ' '(see --no-test in the help of this script)') test = False cgp_dir = os.environ.get('CGP_DIR', '') ids = args or sorted(d for d in os.listdir(EXAMPLES) if os.path.exists(os.path.join(EXAMPLES, d, 'demo.json'))) os.makedirs(BUILD, exist_ok=True) failed = [] with open(os.path.join(BUILD, 'build_examples.log'), 'w') as stream: for n, ident in enumerate(ids, 1): tag = f'[{n}/{len(ids)}] {ident}' source = os.path.join(EXAMPLES, ident) kind = json.load(open(os.path.join(source, 'demo.json'))).get('kind', 'opengl') if kind == 'cgp': if not cgp_dir or not os.path.exists(os.path.join(cgp_dir, 'cgp')): log(f'{tag}: no CGP project (CGP_DIR={cgp_dir!r}): clone it with ' 'git clone https://github.com/drohmer/cgp-2027.git, then set CGP_DIR to its folder', stream) failed.append(ident) continue project = stage_cgp(ident, cgp_dir) else: project = source build = os.path.join(BUILD, ident + '-web') log(f'{tag}: web build ({kind})', stream) started = time.time() ok = run([emcmake, 'cmake', '-S', project, '-B', build, '-DCMAKE_BUILD_TYPE=Release'], stream) \ and run(['cmake', '--build', build, '-j', '8'], stream) if not ok: log(f'{tag}: BUILD FAILED (see the log)', stream) failed.append(ident) continue log(f'{tag}: web build done in {time.time() - started:.0f} s', stream) if native: build_native = os.path.join(BUILD, ident + '-native') log(f'{tag}: native build', stream) ok = run(['cmake', '-S', project, '-B', build_native, '-DCMAKE_BUILD_TYPE=Release'], stream) \ and run(['cmake', '--build', build_native, '--config', 'Release', '-j', '8'], stream) \ and check_native(build_native, project, stream) log(f'{tag}: native ' + ('starts' if ok else 'FAILED (see the log)'), stream) if not ok: failed.append(ident) web = os.path.join(source, 'web') shutil.rmtree(web, ignore_errors=True) os.makedirs(web) for name in OUTPUTS: if os.path.exists(os.path.join(build, name)): shutil.copy2(os.path.join(build, name), web) size = sum(os.path.getsize(os.path.join(web, f)) for f in os.listdir(web)) / 1e6 log(f'{tag}: web/ {size:.1f} MB', stream) if os.path.isdir(os.path.join(source, 'lhtml-site')): demo = os.path.join(source, 'lhtml-site', 'src', '_demo') shutil.rmtree(demo, ignore_errors=True) shutil.copytree(web, demo) shutil.copy2(os.path.join(BRIDGE, 'slide-controls.js'), demo) if os.path.exists(os.path.join(source, 'poster.png')): shutil.copy2(os.path.join(source, 'poster.png'), demo) log(f'{tag}: copied into lhtml-site/src/_demo/', stream) if not test: continue log(f'{tag}: browser test', stream) ok = run([python, os.path.join(ROOT, 'tests', 'test_demo.py'), web, os.path.join(source, 'demo.json'), '--poster', os.path.join(source, 'poster.png')], stream) log(f'{tag}: ' + ('passed' if ok else 'TEST FAILED (see the log)'), stream) if not ok and ident not in failed: failed.append(ident) log('done: ' + ('all passed' if not failed else 'failed: ' + ', '.join(failed)), stream) sys.exit(1 if failed else 0) if __name__ == '__main__': main()
slides.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>The CGP template</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/c1-cgp-template/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>The CGP template</h3> <iframe class="demo" id="demo" data-src="web/index.html"></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>
lhtml-site/
La même slide en lhtml-site (l'ouvrir), organisée comme dans
l'exemple 1 ; seule la slide change, src/01_cgp-template/index.html.j2 :
{% set layout = 'side' %}
= The CGP template
* The template project of the CGP library, unchanged
* The mouse turns the camera
* Its ImGui window stays on screen
media::
demo::../_demo/index.html(.live)
img::../_demo/poster.png(.still)
::
Ce qu'ajoute la page de la démo
La compilation web de CGP écrit sa propre page, pour une fenêtre de navigateur. slide-frame.html la remplace,
et :
- remplit le cadre, quelle que soit la taille de la fenêtre que crée le programme ;
- envoie les flèches et Page suivante / Page précédente aux slides, même après un clic dans la démo ;
- fait apparaître la démo une fois ses premières images dessinées, et signale quand elle est prête (pour un export PDF) ;
- garde l'image du canvas, pour qu'elle puisse être capturée (un poster, des tests).
Ensuite : 4. Boutons dans la slide : une scène CGP à elle, pilotée depuis le texte de la slide.