### Example Application Setup (Python) Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/Markdown/pySymGLSL.md Demonstrates how a user would initialize the Simulation class with window and simulation dimensions to begin setting up a simulation pipeline. ```Python # main.py from simulation import Simulation # 1. Setup the simulation sim = Simulation(window_size=(800, 800), simulation_size=(512, 512)) ``` -------------------------------- ### Example User Application: Initialize Simulation Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/Markdown/pySymGLSL.md Demonstrates the initial setup of the Simulation class in a user application. It involves creating an instance of the Simulation with specified window and simulation sizes. ```Python # main.py from simulation import Simulation # 1. Initialize the toolkit sim = Simulation(window_size=(800, 800), sim_size=(512, 512)) ``` -------------------------------- ### Projectile Impact Simulation Setup Source: https://github.com/prokophapala/simplesimulationengine/blob/master/cpp/apps/Tanks/notes/ArmorPenetration.ipynb Initializes parameters and imports libraries for projectile impact simulations. It sets up arrays for velocity, thickness, and defines constants like projectile diameter and angles. ```Python %matplotlib inline import numpy as np import matplotlib import matplotlib.pyplot as plt vs = np.linspace(0.0,1500,100.0); TDs = np.linspace(0.25,4.0,0.25) D0 = 100.0e-3 angles = np.linspace(0.0,np.pi*0.5*0.9, 100) cosAs = np.cos(angles) lds = np.linspace(1.0,1.0, 100) rad2deg = 180.0/np.pi ``` -------------------------------- ### Minimal SDL2/OpenGL 2D App Boilerplate Source: https://github.com/prokophapala/simplesimulationengine/blob/master/docs/sketches_SDL_2D.md Demonstrates the basic setup for a 2D application using SDL2 and OpenGL. Includes simple camera navigation (pan, zoom) via WASD/arrow keys and draws a crosshair. Serves as a foundational starting point for other 2D demos. ```C++ #include #include #include #include // ... (AppSDL2OGL class definition and main loop) // Example of camera transformation glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 0.0f, 5.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 100.0f); glm::mat4 mvp = projection * view; ``` -------------------------------- ### Phase 3: Instancing Stabilization Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/GLCL2/doc/GLSL_to_GLCL_integration.md A placeholder for a simple instancing example to be provided in tests_bash or a Python demo, demonstrating the use of the local `InstancedData` class in ModularGL.py. ```Bash # Provide a simple example in tests_bash or a small Python demo. ``` -------------------------------- ### Python CLI Usage Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/CodingRules/workflows/documentation/extract_documentation_workflow.md Demonstrates how to document Python command-line interface (CLI) usage by extracting information from `argparse` and providing example commands and flags. ```Python from pkg import mod obj = mod.Solver(params) obj.init(state) obj.run(n=100) res = obj.result() ``` -------------------------------- ### CMake Project Setup and Dependencies Source: https://github.com/prokophapala/simplesimulationengine/blob/master/cpp/apps/CMakeLists.txt This snippet shows the basic CMake project setup, including finding required packages such as OpenGL, GLU, and SDL2. These packages are essential for graphics rendering and multimedia functionalities within the simulation engine. ```cmake project(Apps) find_package( OpenGL REQUIRED ) find_package( GLU REQUIRED ) find_package( SDL2 REQUIRED ) ``` -------------------------------- ### Python Simulation Setup and Execution Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/Markdown/pySymGLSL.md This Python code demonstrates the setup and execution of a fluid simulation using a `Simulation` class. It initializes the simulation, creates necessary textures, defines render graphs for frame updates, bakes these graphs, and runs them in a loop, alternating between two ping-pong buffers. ```python from simulation import Simulation # Assume a windowing library like pyglet or pygame is used for the context/loop # 1. Initialize the toolkit sim = Simulation(window_size=(800, 800), sim_size=(512, 512)) # 2. Create ping-pong resources. The API is now very clean. sim.create_texture("velocity_a") sim.create_texture("velocity_b") sim.create_texture("dye_a") sim.create_texture("dye_b") sim.create_texture("pressure_a") sim.create_texture("pressure_b") sim.create_texture("divergence") # Only one is needed, but we create a pair for consistency. # 3. Define render graphs using the concise tuple format. # Format: (program_path, output_name, [input_names], [dynamic_uniform_names]) # --- Graph for Frame 1 (A -> B) --- graph_A_to_B = [ # Advect velocity by itself: read from velocity_a, write to velocity_b ("shaders/advect.glsl", "velocity_b", ["velocity_a", "velocity_a"], ["u_deltatime"]), # Compute divergence from new velocity: read velocity_b, write divergence ("shaders/divergence.glsl", "divergence", ["velocity_b"], []), # Advect dye: read NEW velocity_b and OLD dye_a, write to dye_b ("shaders/advect.glsl", "dye_b", ["velocity_b", "dye_a"], ["u_deltatime"]), # ... jacobi and project passes would follow a similar explicit pattern ] # --- Graph for Frame 2 (B -> A) --- graph_B_to_A = [ # Advect velocity by itself: read from velocity_b, write to velocity_a ("shaders/advect.glsl", "velocity_a", ["velocity_b", "velocity_b"], ["u_deltatime"]), # Compute divergence from new velocity: read velocity_a, write divergence ("shaders/divergence.glsl", "divergence", ["velocity_a"], []), # Advect dye: read NEW velocity_a and OLD dye_b, write to dye_a ("shaders/advect.glsl", "dye_a", ["velocity_a", "dye_b"], ["u_deltatime"]), # ... etc. ... ] # 4. Bake both graphs *once* at setup time. baked_A_to_B = sim.bake_graph(graph_A_to_B) baked_B_to_A = sim.bake_graph(graph_B_to_A) # 5. The main application loop is simple and fast. frame_count = 0 while True: # e.g., while not window.is_closing dynamic_values = {"u_deltatime": 0.016} # Alternate between the two pre-baked graphs if frame_count % 2 == 0: sim.run_graph(baked_A_to_B, dynamic_values) # To display, we would now render the content of "dye_b" to the screen texture_to_display = sim.textures["dye_b"] else: sim.run_graph(baked_B_to_A, dynamic_values) # To display, we would now render the content of "dye_a" to the screen texture_to_display = sim.textures["dye_a"] # ... code to render texture_to_display to the screen ... frame_count += 1 # window.swap_buffers() ``` -------------------------------- ### OpenGL 3.0 Tutorials Source: https://github.com/prokophapala/simplesimulationengine/wiki/Resources A collection of tutorials for OpenGL 3.0, starting with basic concepts like rendering a colored cube. The provided path indicates downloaded tutorial files. ```C++ // OpenGL 3.0 Tutorial Code // Example from tutorial-4-a-colored-cube/ // Actual code not provided in the text, only links and file paths. ``` -------------------------------- ### C/C++ Build and Run Script Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/CodingRules/workflows/documentation/extract_documentation_workflow.md Illustrates documenting C/C++ build and run processes by referencing shell scripts, including compilation flags and execution commands. ```Shell # Example command from tests_bash/ or C/build.sh # ./build.sh -g -O2 && ./run.sh --dt 0.01 --n 1000 ``` -------------------------------- ### Python Demo Workflow Example (Markdown) Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/CodingRules/wrokflows.md An example workflow file specifically for Python, following the general workflow template structure. It serves as a concrete illustration of how to document a Python-specific simulation workflow. ```markdown # Workflow: Python Demo ## Purpose Demonstrates a basic Python simulation setup, focusing on core principles and common debugging practices. ## Inheritance - Inherits all [Global Rules] - Adds specific Python conventions for dependency management and testing. ## Workflow Steps 1. Setup: Install `numpy`, `matplotlib`. Define simulation parameters. 2. Coding strategy: Use NumPy for array operations. Small, focused functions. 3. Debugging strategy: Use `print` statements with verbosity flags. Assert invariants. 4. Testing & validation: Unit tests for core functions. Compare against known results. 5. Performance considerations: Vectorize operations. Avoid Python loops in critical paths. 6. Visualization/reporting: Use Matplotlib for plotting. Save figures to files. ## Notes Ensure correct NumPy array shapes. Handle potential division by zero in calculations. ``` -------------------------------- ### Phase 5: pySymGLSL Compute Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/GLCL2/doc/GLSL_to_GLCL_integration.md Mentions the creation of an example compute+render pipeline as part of Phase 5 to demonstrate the new compute capabilities in pySymGLSL. ```Python # Provide an example compute+render pipeline. ``` -------------------------------- ### OpenCL Kernel Documentation Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/CodingRules/workflows/documentation/extract_documentation_workflow.md Provides guidance on documenting OpenCL kernels, including their names, computational purpose, buffer interactions, and host code entry points. ```OpenCL // Example: Kernel for computing neighbor lists via grid hashing // __kernel void compute_neighbors(global float* pos, global int* neighbors, ...) // Host binding example: Python OpenCLBase.compute_neighbors(...) ``` -------------------------------- ### CMake Project Setup and Include Directories Source: https://github.com/prokophapala/simplesimulationengine/blob/master/cpp/sketches_SDL/Molecular/CMakeLists.txt Initializes the CMake project and specifies directories for source files related to molecular dynamics and general common sources. This sets up the build environment for the project. ```cmake project(sketches_SDL_Molecular) #include_directories( ${COMMON_SRCS}/dynamics/Molecular ) include_directories( ${COMMON_SRCS}/molecular ) ``` -------------------------------- ### ShaderToy Examples: Various Techniques Source: https://github.com/prokophapala/simplesimulationengine/wiki/Resources A curated list of ShaderToy examples showcasing various graphical techniques including ray tracing, analytical ambient occlusion (AO), anti-aliasing (AA), soft shadows, terrain rendering, SSAO, distance functions, noise, metaballs, and more. These are primarily written in GLSL. ```GLSL // ShaderToy Examples // Examples include: // - torus // - spheres with analytical AO and AA // - sphere ray tracer with soft shadow // - terrain analytical AO // - SSAO // - ray HeightField // - clouds // - primitives (distance function) // - voronoise // - analytical projection of sphere to screen space // - landscape of cylinders // - mandelbrot distance field // - texture noise 3D // - spherical harmonics // - quintic metabals // - smooth HSV // - hierarchical voronoi // - texture variation // - surface splat rendering // - dual complex numbers // - CUBIC SPLINE DISTANCE // - sphere soft shadow // - ray marching with dual numbers // - compile time stack in shader // - terrain analytical normals // - bicubic filtering comparison // - compressing normals by spherical fibonacci points // - inverse spherical fibonacci // - sincos approximation // - spherical-harmonics lightning // - distance from parametric curve // - minimalistic orbit trapping fractals // - cloth simulation in shader // - L-System without stack ! // - acos approximation // - GameOfLife // - smooth minimum polynomial // - Convex Cone Tracing // Actual GLSL code is not provided in the text, only links to ShaderToy. ``` -------------------------------- ### Example User Application: Create Simulation Resources Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/Markdown/pySymGLSL.md Shows how a user explicitly creates necessary textures for a simulation, such as those for velocity and dye data, which are essential for ping-ponging techniques in fluid simulations. ```Python # 2. User explicitly creates every resource needed for ping-ponging sim.create_texture("velocity_a") sim.create_texture("velocity_b") sim.create_texture("dye_a") sim.create_texture("dye_b") # ... etc. for divergence and pressure ``` -------------------------------- ### Fortran Astrodynamics Toolkit Source: https://github.com/prokophapala/simplesimulationengine/wiki/Resources A toolkit for astrodynamics implemented in Fortran. No specific code examples are provided in the text, but the repository link suggests its availability. ```Fortran ! Fortran-Astrodynamics-Toolkit ! No specific code examples provided in the text. ``` -------------------------------- ### CMake Project Setup and Options Source: https://github.com/prokophapala/simplesimulationengine/blob/master/cpp/CMakeLists.txt Initializes the CMake project and defines build options for features like release mode, SDL GUI, OpenMP, OpenCL, Lua scripting, ASAN, and networking. It then messages the selected options. ```cmake cmake_minimum_required ( VERSION 2.8 ) project ( SimpleSimulationEngine ) option(RELEASE "build optimized release (-O3 -Ofast) rather than debug? (-g -Og)" OFF) option(WITH_SDL "build with GUI and 3D graphics (SDL+OpenGL)" OFF) option(WITH_OMP "use OpenMP paralelization" OFF) option(WITH_OPENCL "build with OpenCL GPU acceleration? (can accelare >100x some forcefields and grids )" OFF) option(WITH_LUA "build with LUA scripting " OFF) option(WITH_ASAN "use runtime memory sanitizer (asan) to trace segfaults and leaks?" OFF) option(WITH_NET "build with GUI and 3D graphics (SDL+OpenGL)" OFF) option(WITH_MUSIC "build with GUI and 3D graphics (SDL+OpenGL)" OFF) message("OPTIONS: -DRELEASE=${RELEASE} -DWITH_SDL=${WITH_SDL} -DWITH_OMP=${WITH_OMP} -DWITH_OPENCL=${WITH_OPENCL} -DWITH_LUA=${WITH_LUA} -DWITH_NET=${WITH_NET} -DWITH_ASAN=${WITH_ASAN}" ) ``` -------------------------------- ### three.js Trackball Controls Initialization and Setup Source: https://github.com/prokophapala/simplesimulationengine/blob/master/projects/SpaceCombat/HTML/StickSpaceCraft.html Initializes the three.js scene, camera, and TrackballControls. It configures control sensitivity, damping, and keyboard mappings. Event listeners are added for camera changes and window resizing to ensure responsiveness. ```javascript var container, stats; var camera, controls, scene, renderer; var cross; function init() { camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 ); camera.position.z = 500; controls = new THREE.TrackballControls( camera ); controls.rotateSpeed = 1.0; controls.zoomSpeed = 5.0; controls.panSpeed = 0.8; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.keys = [ 65, 83, 68 ]; controls.addEventListener( 'change', render ); // world scene = new THREE.Scene(); //scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 ); BuildSpaceShip_1( scene ); // lights light = new THREE.DirectionalLight( 0xffffff ); light.position.set( 1, 1, 1 ); scene.add( light ); light = new THREE.DirectionalLight( 0x002288 ); light.position.set( -1, -1, -1 ); scene.add( light ); light = new THREE.AmbientLight( 0x222222 ); scene.add( light ); // renderer renderer = new THREE.WebGLRenderer( { antialias: false } ); //renderer.setClearColor( scene.fog.color ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); container = document.getElementById( 'container' ); container.appendChild( renderer.domElement ); window.addEventListener( 'resize', onWindowResize, false ); render(); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); controls.handleResize(); render(); } function animate() { requestAnimationFrame( animate ); controls.update(); } function render() { renderer.render( scene, camera ); //stats.update(); } init(); animate(); ``` -------------------------------- ### OpenCL Particle Simulation Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/cpp/sketches_OCL/NOTES.md An example of OpenCL code for simulating particles, specifically demonstrating particle handling within an OpenCL context. This snippet is part of a larger collection of NVIDIA OpenCL examples. ```OpenCL // Example snippet from nvidia-opencl-examples/OpenCL/src/oclParticles/Particles.cl // This is a placeholder for actual code content. // The original repository should be consulted for the full implementation. // Function to update particle positions (conceptual) __kernel void update_particles(__global float4* positions, __global float4* velocities, float dt) { int gid = get_global_id(0); positions[gid].xyz += velocities[gid].xyz * dt; } ``` -------------------------------- ### OpenGL Instanced Rendering Setup Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/GLCL2/doc/Soldiers2D_GLCL_design.md Illustrates the OpenGL setup for instanced rendering, including vertex buffer configuration, instancing parameters, and draw modes. This setup is used for rendering formations as instanced rectangles. ```C++ // Vertex buffer: quad_verts with layout [2] // Instancing: instance_buffer="formation_params", instance_attribs=[4,4], instance_divisor=1 // Draw mode: TRIANGLE_STRIP, instances = formation_count ``` -------------------------------- ### Install NVIDIA GPU Drivers on Linux Source: https://github.com/prokophapala/simplesimulationengine/blob/master/README.md This section provides commands for troubleshooting and reinstalling NVIDIA drivers on Linux, which can be helpful if the system breaks during driver installation. It includes commands to remove existing NVIDIA packages, install the Nouveau driver, and restart the display manager. ```bash sudo apt-get autoremove --purge nvidia-* sudo stop lightdm sudo apt-get install xserver-xorg-video-nouveau ``` -------------------------------- ### GL Initialization Lifecycle Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/pySymGLSL/doc/pySymGLSL_manifest.md Describes the process of initializing the OpenGL context and setting up the display program and Vertex Array Object (VAO) within the GLRenderWidget. ```Python # Initialize GL (GLRenderWidget.initializeGL): # Create ModernGL context # Create on‑screen display program and VAO (separate from simulation passes) ``` -------------------------------- ### Gaussian Field Pipeline Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/pySymGLSL/doc/pySymGLSL_manifest.md An example JSON configuration for a Gaussian field simulation. It defines parameters like 'pos0' and specifies the shader ('common/gauss.glslf') and its inputs for the rendering pipeline. ```JSON { "parameters": { "pos0": ["vec4", [0.0, 0.0, 0.2, 1.0], 0.1] }, "Pipeline": [ ["common/gauss.glslf", "view0", {}, ["pos0"]] ] } ``` -------------------------------- ### Immediate-Mode GUI Showcase with Various Widgets Source: https://github.com/prokophapala/simplesimulationengine/blob/master/docs/sketches_SDL_3D.md Provides a comprehensive showcase of the engine's immediate-mode Graphical User Interface (GUI) library (`GUI.h`). It displays and allows interaction with various widgets, including 2D/3D text, data tables, input fields, plots, and clipping boxes, demonstrating UI building capabilities. ```C++ /* * This program is a comprehensive showcase of the engine's immediate-mode Graphical User Interface library, GUI.h. It displays a variety of UI widgets, including 2D and 3D text rendering, data tables, text input fields, 2D plots, dropdown lists, and scissor boxes for clipping UI elements. Users can interact with all the elements to see their functionality, making this a key demo for learning how to build UIs in the engine. */ // Assuming GUI.h is included and used for UI elements. // Example: // GUI guiRenderer; // guiRenderer.renderText("Hello", 10, 10); // guiRenderer.renderTable(data); // guiRenderer.renderInputBox("Enter text", ...); ``` -------------------------------- ### Pipeline Loading Lifecycle Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/pySymGLSL/doc/pySymGLSL_manifest.md Details the steps involved in loading a simulation pipeline, from reading the JSON configuration to building the rendering pipeline using GLSL_Simulation and updating the UI. ```Python # Load Pipeline (GUI load_pipeline): # 1. Read JSON, strip comments # 2. Compute base_dir = /../shaders # 3. GLSL_Simulation.build_pipeline(Pipeline, base_dir) # 4. Update UI parameter widgets from parameters ``` -------------------------------- ### C++ OpenGL 3+ Rendering Examples: Render to Texture Source: https://github.com/prokophapala/simplesimulationengine/blob/master/README.md Provides examples of rendering scenes to textures using OpenGL 3+, a technique used for post-processing effects, reflections, and deferred rendering. ```C++ #include "test_RenderToTexture.cpp" ``` -------------------------------- ### Simple Fluid Pipeline Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/pySymGLSL/doc/pySymGLSL_manifest.md Describes an example pipeline configuration for a simple fluid simulation. It mentions the use of triplicated advection/force solve passes feeding into a view pass, referencing specific shader files. ```Markdown - __Simple fluid__ (`pipelines/fluid.json`): triplicated advection/force solve feeding into a view pass. See `shaders/fluid/solveFluid.glslf` and `shaders/fluid/view.glslf`. ``` -------------------------------- ### Run pySymGLSL GUI Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/pySymGLSL/doc/pySymGLSL_manifest.md Launches the pySymGLSL graphical user interface, which can load default or custom simulation pipelines. ```Bash python -m pySymGLSL.GLSL_GUI ``` -------------------------------- ### pySymGLSL JSON Pipeline Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/pySymGLSL/doc/pySymGLSL_manifest.md An example JSON structure defining a simulation pipeline for pySymGLSL. It includes parameters and a sequence of rendering passes, specifying fragment shaders, output textures, input texture mappings, and dynamic uniforms. ```JSON { "parameters": { "driver": ["vec4", [0.5, 0.5, 0.0, 1.0], 0.1] }, "Pipeline": [ ["fluid/solveFluid.glslf", "fieldA", {"iChannel0": "fieldC"}, ["driver"]], ["fluid/solveFluid.glslf", "fieldB", {"iChannel0": "fieldA"}, ["driver"]], ["fluid/solveFluid.glslf", "fieldC", {"iChannel0": "fieldB"}, ["driver"]], ["fluid/view.glslf", "view0", {"iChannel0": "fieldC"}, []] ] } ``` -------------------------------- ### Serving HTML Files with Python Source: https://github.com/prokophapala/simplesimulationengine/blob/master/projects/SpaceCombat/readme.md This command starts a simple Python web server in the specified directory, allowing you to view HTML files locally in a web browser. It's useful for offline browsing of generated HTML content. ```Bash cd ~/git/SimpleSimulationEngine/projects/SpaceCombat/HTML python -m SimpleHTTPServer ``` -------------------------------- ### CSS Styling for three.js Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/projects/SpaceCombat/HTML/StickSpaceCraft.html Provides basic CSS styling for the WebGL content, setting the background color, font properties, and positioning for informational elements. It ensures the canvas fills the viewport and handles overflow. ```css body { color: #808080; font-family:Monospace; font-size:13px; text-align:center; font-weight: bold; background-color: #fff; margin: 0px; overflow: hidden; } #info { color: #606060; position: absolute; top: 0px; width: 100%; padding: 5px; } a { color: red; } ``` -------------------------------- ### SAXPY Example (Python) Source: https://github.com/prokophapala/simplesimulationengine/blob/master/docs/OpenCLBase.md Demonstrates the end-to-end usage of an OpenCL kernel (SAXPY) from Python. It includes initializing OpenCL context, loading the program, creating and transferring data buffers, setting kernel parameters, launching the kernel, and retrieving results from the device. ```Python ocl = OpenCLBase(nloc=128)ocl.load_program(kernel_path='kernels.cl') n = 1_000_000 x = np.ones(n, np.float32) y = np.zeros(n, np.float32) sz = n*4 ocl.try_make_buffers({'x': sz, 'y': sz}) ocl.toGPU('x_buff', x); ocl.toGPU('y_buff', y) ocl.kernel_params = {'a': 2.0, 'n': n} args = ocl.generate_kernel_args('saxpy') g = (ocl.roundUpGlobalSize(n),) ocl.prg.saxpy(ocl.queue, g, (ocl.nloc,), *args) ocl.fromGPU('y_buff', y) ``` -------------------------------- ### N-body Simulation Examples (Python and OpenCL) Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/GLCL2/doc/Soldiers2D_GLCL_design.md Reference examples for N-body simulations provided within the project. These files demonstrate the usage of the GLCL2 framework and OpenCL for particle simulations, serving as a basis for understanding the soldiers simulation implementation. ```Python # scripts/nbody.py # ... (Python script for N-body simulation) ``` ```OpenCL # cl/nbody.cl # ... (OpenCL kernel for N-body simulation) ``` -------------------------------- ### GLSL: NBody_glsl Example with Compute and Render Passes Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/GLCL2/doc/GLSL_to_GLCL_integration.md Recreate the NBody_glsl example using the new pipeline abstraction, which includes a compute pass and a render pass. This serves to verify the design of the new pipeline. ```GLSL // Compute Shader (e.g., compute_nbody.glsl) #version 430 core layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in; layout (binding = 0, std430) buffer PosBuffer { vec4 positions[]; }; layout (binding = 1, std430) buffer VelBuffer { vec4 velocities[]; }; uniform float deltaTime; void main() { uint index = gl_GlobalInvocationID.x; // Calculate forces and update position/velocity // ... positions[index].xyz += velocities[index].xyz * deltaTime; velocities[index].xyz += /* calculated forces */ * deltaTime; } // Vertex Shader (e.g., render_nbody.vert) #version 430 core layout (location = 0) in vec4 position; void main() { gl_Position = vec4(position.xyz, 1.0); } // Fragment Shader (e.g., render_nbody.frag) #version 430 core layout (location = 0) out vec4 FragColor; void main() { FragColor = vec4(1.0, 1.0, 1.0, 1.0); } ``` -------------------------------- ### Run GLCL Browser from Command Line Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/GLCL2/doc/GLCL_manifest.md Demonstrates how to launch the GLCLBrowser from the command line with various options for specifying simulation scripts and enabling debugging features. ```Bash # Basic usage, loads the nbody.py script by default python -m pyBall.GLCL.GLCLBrowser # Specify a different script python -m pyBall.GLCL.GLCLBrowser --script path/to/my_simulation.py # Run with OpenCL debugging (prints buffer data each frame) python -m pyBall.GLCL.GLCLBrowser --debug-cl --debug-frames 10 # Run with OpenGL debugging (skips kernel execution to test rendering) python -m pyBall.GLCL.GLCLBrowser --debug-gl ``` -------------------------------- ### Minimal OpenCLBase Setup and Kernel Execution in Python Source: https://github.com/prokophapala/simplesimulationengine/blob/master/docs/OpenCLBase.md This Python code demonstrates the basic usage of OpenCLBase for a physics simulation. It initializes OpenCLBase, loads a kernel program, creates and populates GPU buffers for position, velocity, and force, sets kernel parameters, generates kernel arguments, executes the 'integrate' kernel on the GPU, and retrieves the computed force data back to the host. ```Python from pyBall.OCL.OpenCLBase import OpenCLBase import numpy as np ocl = OpenCLBase(nloc=64) ocl.load_program(kernel_path="path/to/kernels.cl") N = 100000 sizes = { 'pos': N*16, 'vel': N*16, 'force': N*16 }ocl.try_make_buffers(sizes) # creates pos_buff, vel_buff, force_buff (+ buffer_dict entries) pos = np.zeros((N,4), np.float32) vel = np.zeros((N,4), np.float32) force = np.zeros((N,4), np.float32)ocl.toGPU('pos_buff', pos); ocl.toGPU('vel_buff', vel) ocl.kernel_params = {'N': N, 'dt': 1e-3} args = ocl.generate_kernel_args('integrate') # [pos_buff, vel_buff, force_buff, N, dt] g = (ocl.roundUpGlobalSize(N),)ocl.prg.integrate(ocl.queue, g, (ocl.nloc,), *args) ocl.fromGPU('force_buff', force) ``` -------------------------------- ### Simulation Class Initialization and Resource Management Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/Markdown/pySymGLSL.md Initializes the `Simulation` class, setting up the moderngl context and fullscreen quad. It also initializes dictionaries for storing programs, textures, and framebuffers, primarily used during the baking process. ```Python class Simulation: def __init__(self, window_size, sim_size): self.ctx = moderngl.create_context() self.sim_size = sim_size self.quad_fs = self._create_fullscreen_quad() # --- Resource Dictionaries (Used ONLY during baking) --- self._programs: Dict[str, moderngl.Program] = {} self.textures: Dict[str, moderngl.Texture] = {} self.framebuffers: Dict[str, moderngl.Framebuffer] = {} ``` -------------------------------- ### GLCL NBody Example: OpenGL 4.3 Compute Shaders Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/GLCL2/doc/GLSL_to_GLCL_integration.md This example demonstrates the use of OpenGL 4.3 compute shaders for an N-body simulation. It utilizes Shader Storage Buffer Objects (SSBOs) and `glDispatchCompute` for parallel computation, followed by a simple `GL_POINTS` rendering pass. The context requirement is OpenGL 4.3 core. ```Python from OpenGL import GL # Assume context is created with GL.GL_CONTEXT_MAJOR_VERSION, GL.GL_CONTEXT_MINOR_VERSION >= (4, 3) # Example of setting up SSBOs position_ssbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_SHADER_STORAGE_BUFFER, position_ssbo) # Allocate buffer for N particles, e.g., N * 4 floats (x, y, z, w) particle_data_size = N * 4 * 4 # Assuming 4 floats per particle, 4 bytes per float GL.glBufferData(GL.GL_SHADER_STORAGE_BUFFER, particle_data_size, None, GL.GL_DYNAMIC_DRAW) # Binding SSBO to a specific binding point in the shader # e.g., in GLSL: layout(std430, binding=0) buffer ParticleBuffer { ... } particles; GL.glBindBufferBase(GL.GL_SHADER_STORAGE_BUFFER, 0, position_ssbo) # Dispatching the compute shader # gx, gy, gz are the number of workgroups in each dimension # These should be calculated based on particle count and workgroup size workgroup_size_x = 64 num_workgroups_x = (N + workgroup_size_x - 1) // workgroup_size_x GL.glUseProgram(compute_program_id) GL.glDispatchCompute(num_workgroups_x, 1, 1) # Memory barrier to ensure writes to SSBO are visible before next operation # GL_SHADER_STORAGE_BARRIER_BIT ensures SSBO writes are visible GL.glMemoryBarrier(GL.GL_SHADER_STORAGE_BARRIER_BIT) # Rendering pass using GL_POINTS # Assume a VAO and program are set up for rendering points GL.glUseProgram(render_program_id) GL.glBindVertexArray(point_vao_id) # Bind the SSBO again if needed for reading in the vertex/geometry shader GL.glBindBufferBase(GL.GL_SHADER_STORAGE_BUFFER, 0, position_ssbo) GL.glDrawArrays(GL.GL_POINTS, 0, N) GL.glBindVertexArray(0) # No geometry shader is used in this example. ``` -------------------------------- ### Buckets Querying Example Source: https://github.com/prokophapala/simplesimulationengine/blob/master/docs/Buckets.md Shows how to retrieve the number of edges connected to a vertex and a pointer to those edges using the Buckets data structure. ```cpp // Get edges connected to vertex iv int n = edgesOfVerts.cellNs[iv]; int* edgesInCell = edgesOfVerts.inCell(iv); ``` -------------------------------- ### Initialize ModernGL Simulation Context Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/Markdown/pySymGLSL.md Initializes the ModernGL context and sets up resource dictionaries for programs, textures, and framebuffers within the Simulation class. It also prepares a fullscreen quad geometry for rendering. ```Python class Simulation: def __init__(self, window_size, simulation_size): # 1. Initialize moderngl context self.ctx = moderngl.create_context() # 2. Resource Dictionaries self.programs = {} self.textures = {} self.framebuffers = {} # 3. Fullscreen Quad Geometry self.quad_fs = # ... create a simple VAO for a fullscreen triangle strip ``` -------------------------------- ### Get Picked Object Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/Markdown/cpp/common/dynamics/TrussDynamics_d.h.md Returns a pointer to the picked object based on a given mask value. This is used in interactive selection mechanisms. ```C++ getPickedObject ``` -------------------------------- ### Python Demo Workflow Guidance Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/CodingRules/README.md Recommendations for using the Python Demo workflow for small numerical scripts. Emphasizes compact code, NumPy vectorization, and controlling debug prints with verbosity levels. ```Python # Example of a compact, vectorized Python script import numpy as np # Assume a verbosity level is set globally or passed as an argument VERBOSITY = 2 def process_data(data): # Vectorized operation using NumPy processed = np.sin(data) * 10 if VERBOSITY > 1: print(f"Processed data: {processed}") return processed input_array = np.linspace(0, 10, 100) output_array = process_data(input_array) ``` -------------------------------- ### Three.js Ray Tracer Setup (JavaScript) Source: https://github.com/prokophapala/simplesimulationengine/blob/master/projects/SpaceCombat/HTML/solid_modeling.html Initializes the Three.js renderer, scene, and camera, and sets up mouse event handling for camera control. ```javascript var renderer; var scene; var camera; var uniforms = {}; var control; var mousePosOld; var camQuat = new THREE.Quaternion(); function handleMouseMove(event) { var dot, eventDoc, doc, body, pageX, pageY; if (mousePosOld) { var dx = (event.clientX-mousePosOld.x)*1.0; var dy = (event.clientY-mousePosOld.y)*1.0; var v = ``` -------------------------------- ### C++ Build and Execution Guidance Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/CodingRules/README.md Guidance for building and running C/C++ code within the project. It suggests using project bash scripts for compilation and execution, and recommends `printf` for debugging purposes. ```Shell # Example of building a C++ project ./C/build.sh # Example of running tests ./tests_bash/run_tests.sh ``` -------------------------------- ### Create Dropdown List for View Mode Selection Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/Markdown/GUI.md Demonstrates creating a DropDownList to select a view mode. It includes adding items and setting a callback to update a view mode variable. ```cpp #include "GUI.h" class MyGUI { public: GUI gui; int viewMode = 0; void init() { GUI_stepper ylay(1,2); // Create a DropDownList for view mode selection DropDownList* viewModeList = new DropDownList("View Mode:", 5, ylay.x0, 105, 3); viewModeList->addItem("Top"); viewModeList->addItem("Front"); viewModeList->addItem("Side"); viewModeList->setCommand([this](GUIAbstractPanel* p) { viewMode = ((DropDownList*)p)->iSelected; printf("View Mode: %i\n", viewMode); }); gui.addPanel(viewModeList); } }; ``` -------------------------------- ### Create test_SpaceFlightODE Executable Source: https://github.com/prokophapala/simplesimulationengine/blob/master/cpp/apps/OrbitalWar/CMakeLists.txt Defines the 'test_SpaceFlightODE' executable, linking it with SDL2OGL library, along with OpenGL, GLU, and SDL2 libraries. ```cmake add_executable( test_SpaceFlightODE \ test_SpaceFlightODE.cpp \ $ ) target_link_libraries( test_SpaceFlightODE ${OpenGL_LIBRARIES} ${GLU_LIBRARY} ${SDL2_LIBRARY} ) ``` -------------------------------- ### OpenCLBase Initialization and Program Loading Source: https://github.com/prokophapala/simplesimulationengine/blob/master/docs/OpenCLBase.md Initializes the OpenCL context, command queue, and device information. It also includes functionality to load OpenCL C source files (`.cl`) and build OpenCL programs, with options to extract kernel headers for automatic argument assembly. ```Python ocl = OpenCLBase(nloc=32, device_index=0) ocl.load_program('your_kernel.cl') ``` -------------------------------- ### C++ OpenGL 3+ Rendering Examples: Meshes Source: https://github.com/prokophapala/simplesimulationengine/blob/master/README.md Demonstrates rendering meshes using modern OpenGL (3+), showcasing techniques for displaying complex 3D models. ```C++ #include "cpp/sketches_SDL/test_MeshOGL3.cpp" ``` -------------------------------- ### Simulation Class Initialization (Python) Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/Markdown/pySymGLSL.md Initializes the Simulation class, setting up the ModernGL context, window and simulation sizes, and data structures for programs, textures, framebuffers, and the render graph. It also prepares a fullscreen quad for rendering. ```Python import moderngl class Simulation: def __init__(self, window_size, simulation_size): self.ctx = moderngl.create_context() self.window_size = window_size self.sim_size = simulation_size self.programs = {} self.textures = {} self.framebuffers = {} self.render_graph = [] self.quad_fs = # ... create a simple VAO ... ``` -------------------------------- ### Running Jupyter Notebook Locally Source: https://github.com/prokophapala/simplesimulationengine/blob/master/projects/SpaceCombat/readme.md This snippet shows the command to run a Jupyter notebook locally on your computer. It requires having Jupyter installed and the notebook file present in the current directory. ```Bash jupyter notebook ch1_basics.ipynb ``` -------------------------------- ### C++ SDL2 Application Prefabricates Source: https://github.com/prokophapala/simplesimulationengine/blob/master/README.md Offers basic SDL2 application prefabs for both 2D and 3D applications, providing a starting point for creating graphical applications with SDL2. ```C++ #include "cpp/common_SDL/SDL2OGL/AppSDL2OGL.h" #include "cpp/common_SDL/SDL2OGL/AppSDL2OGL_3D.cpp" ``` -------------------------------- ### Apply Simulation Configuration (Baking) Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/GLCL2/doc/GLCL_manifest.md Transforms declarative configuration into imperative execution pipelines. This involves parsing parameters for GUI creation, loading and compiling OpenCL sources, initializing GPU buffers with data, baking OpenCL kernels with resolved arguments, preparing OpenGL shaders, and pre-computing buffer synchronization lists. ```Python def apply_simulation_config(self): # 1. Create GUI from parameters # 2. Load CL Sources and compile kernels # 3. Initialize Buffers (copy data to GPU) # 4. Bake Kernels (resolve arguments and create BakedKernelCall objects) # 5. Prepare OpenGL (pass configurations) # 6. Pre-compute Sync List (self.buffers_to_sync) ``` -------------------------------- ### GLCL Python Simulation Script Configuration Source: https://github.com/prokophapala/simplesimulationengine/blob/master/python/GLCL2/doc/GLCL_manifest.md An example of a Python script used to configure a simulation for the GLCL framework. It defines simulation parameters, data buffers, OpenCL kernels, and OpenGL shaders. ```Python import numpy as np # The central configuration dictionary config = { # --- General Info --- "simulation_name": "NBody Simulation", "description": "...", # --- Simulation Parameters (Tunable via GUI) --- "parameters": { # name: (default_value, type, step_size) "particle_count": (2048, "int" , 1 ), "dt": (0.001, "float", 0.0001 ) }, # --- Data Buffers (for OpenCL and/or OpenGL) --- "buffers": { # name: (size_expression, stride, numpy_dtype) "positions": ("particle_count", 4, "f4"), "velocities": ("particle_count", 4, "f4") }, # --- OpenCL Computation --- "opencl_source": ["../cl/nbody.cl"], "kernels": { # kernel_name: (local_size, global_size_expr, [buffer_args], [scalar_args]) "nbody_sim" : ((32,), "particle_count", ["positions", "velocities"], ["dt", "particle_count"]) }, "kernel_pipeline": ["nbody_sim"], # --- OpenGL Visualization --- "opengl_shaders": { # shader_name: (vertex_shader_path, fragment_shader_path, [uniforms]) "nbody_render" : ("../shaders/points.glslv", "../shaders/monocolor.glslf", ["color"]) }, "render_pipeline": [ # (shader_name, element_count_expr, vertex_buffer_name, index_buffer_name) ("nbody_render", "particle_count", "positions", None), ] } ``` -------------------------------- ### Python Log Parsing and Visualization Source: https://github.com/prokophapala/simplesimulationengine/blob/master/doc/CodingRules/workflows/cpp/cpp_debugging_workflow.md Example of parsing C++ program logs using Python and visualizing summaries with matplotlib. This approach helps in analyzing the output logs to identify errors and trends. ```Python import re import matplotlib.pyplot as plt def parse_log(log_file): data = [] with open(log_file, 'r') as f: for line in f: # Example: Parse lines containing 'Array size: X' match = re.search(r'Array size: (\d+)', line) if match: data.append(int(match.group(1))) return data def plot_summary(data): plt.figure(figsize=(10, 6)) plt.plot(data, marker='o') plt.title('Array Size Over Time') plt.xlabel('Step') plt.ylabel('Size') plt.grid(True) plt.savefig('array_size_summary.png') print("Summary plot saved to array_size_summary.png") if __name__ == "__main__": log_file = 'myprogram.log' parsed_data = parse_log(log_file) if parsed_data: plot_summary(parsed_data) else: print("No relevant data found in the log file.") ```