3. CGP program
A program written with a library works the same way, if the library builds for the web. This example is the template project of CGP, a C++ library made for teaching computer graphics, compiled for the web without changing a line. The mouse turns the camera, its ImGui window stays on screen, and the arrow keys still go to the slides.
Download: c1-cgp-template.zip. The zip contains the 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 C++ program is the template
project of CGP itself, 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/c1-cgp-template/slides.html, the slide with its demo. To change the program: build and run.
How the CGP examples are built
A CGP project is a template: CMakeLists.txt, the library in cgp/, your scene in src/, the shaders in
shaders/. The examples of this tutorial hold only the files that differ from the template. The build script
puts them over a copy of the template, adds the bridge, and builds with the CMakeLists.txt of CGP itself:
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
This example has no file of its own: it is the template as it is. With the Emscripten SDK activated, from the root of the repository (or of the unzipped folder):
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 is the folder of the CGP project. On Windows: see the commands of Before you start.
The first command builds for the web, copies the result into examples/c1-cgp-template/web/ and
examples/c1-cgp-template/lhtml-site/src/_demo/, then tests it in a browser and captures its poster (when
Playwright is installed, see Testing a demo); --native also builds the desktop version and runs it for two seconds. In your own CGP project, the
same is three steps: copy slide_bridge.hpp and slide_bridge.cpp into src/, add the link options of the
bridge to the web build of the CMakeLists.txt, and use slide-frame.html as the page of the demo.
scripts/build_examples.py, the build script (download)
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/
The same slide in lhtml-site (open it), organized as in
example 1; only the slide changes, 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)
::
What the page of the demo adds
The web build of CGP writes its own page for a browser window. slide-frame.html replaces it, and:
- fills the frame, whatever the size of the window the program creates;
- sends the arrow keys and Page Down / Page Up to the slides, even after a click in the demo;
- fades the demo in once its first frames are drawn, and says when it is ready (for a PDF export);
- keeps the image of the canvas, so that it can be captured (a poster, tests).
Next: 4. Buttons in the slide: a CGP scene of its own, driven from the text of the slide.