### Build a Single Example Project Source: https://docs.flamegpu.com/api/page_md_README.html Configures and builds an individual example as a standalone CMake project. ```bash cd examples/game_of_life mkdir -p build cd build cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=61 cmake --build . --target all ``` -------------------------------- ### Build and Install Python Bindings from Source Source: https://docs.flamegpu.com/_sources/quickstart/index.rst.txt Configure and build the pyflamegpu target using CMake, then install the resulting wheel. ```bash # Create and activate your venv python3 -m venv venv source venv/bin/activate # Build the python bindings, producing a .whl mkdir -p build && cd build cmake .. -DCMAKE_CUDA_ARCHITECTURES=75 -DFLAMEGPU_BUILD_PYTHON=ON -DCMAKE_BUILD_TYPE=Release cmake --build . --target pyflamegpu -j 8 # Install the wheel via pip python3 -m pip install lib/Release/python/venv/dist/*.whl ``` ```bat :: Create and activate your venv python -m venv venv call "venv/Scripts/activate.bat" :: Build the python bindings, producing a .whl mkdir build && cd build cmake .. -G "Visual Studio 17 2022" -DCMAKE_CUDA_ARCHITECTURES=75 -DFLAMEGPU_BUILD_PYTHON=ON cmake --build . --target pyflamegpu --config Release -j 8 :: Install the wheel via pip python -m pip install lib/Release/python/venv/dist/*.whl ``` -------------------------------- ### Install FLAME GPU 2 Wheel Source: https://docs.flamegpu.com/_sources/quickstart/index.rst.txt Install a downloaded .whl file into the current Python environment. ```bash python3 -m pip install filename.whl ``` ```bat python -m pip install filename.whl ``` -------------------------------- ### Simulation Initial State File Examples Source: https://docs.flamegpu.com/guide/running-a-simulation/initial-state.html Examples of simulation state files in XML and JSON formats. These files define configuration, environment, and agent data for simulation execution. ```xml 100 true 1643029170 1 1 false false 0 true 100 0.05 <_stepCount>1 1,1,1,1,0,0,0,0 Circle default <_auto_sort_bin_index>0 <_id>241 0.0 0.8293430805206299 1.5674132108688355 14.034683227539063 Circle default <_auto_sort_bin_index>0 <_id>242 0.0 23.089038848876954 24.715721130371095 2.3497250080108644 ``` ```json { "config": { "simulation": { "input_file": "", "step_log_file": "", "exit_log_file": "", "common_log_file": "", "truncate_log_files": true, "random_seed": 1643029117, "steps": 1, "verbosity": 1, "timing": false, "console_mode": false }, "cuda": { "device_id": 0, "inLayerConcurrency": true } }, "stats": { "step_count": 100 }, "environment": { "repulse": 0.05, "_stepCount": 1 }, "macro_environment": { "heat": [1,1,1,1,0,0,0,0] }, "agents": { "Circle": { "default": [ { "_auto_sort_bin_index": 0, "_id": 241, "drift": 0.0, "x": 0.8293430805206299, "y": 1.5674132108688355, "z": 14.034683227539063 }, { "_auto_sort_bin_index": 168, "_id": 242, "drift": 0.0, "x": 23.089038848876954, "y": 24.715721130371095, "z": 2.3497250080108644 } ] } } } ``` -------------------------------- ### XML Initial State File Example Source: https://docs.flamegpu.com/_sources/guide/running-a-simulation/initial-state.rst.txt Example of an XML file structure used for simulation input and output in FLAME GPU 2. ```xml 100 true 1643029170 1 1 false false 0 true 100 0.05 <_stepCount>1 1,1,1,1,0,0,0,0 Circle default <_auto_sort_bin_index>0 <_id>241 0.0 0.8293430805206299 1.5674132108688355 14.034683227539063 Circle default <_auto_sort_bin_index>0 <_id>242 0.0 23.089038848876954 24.715721130371095 2.3497250080108644 ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://docs.flamegpu.com/_sources/quickstart/index.rst.txt Set up an isolated environment for installing the pyflamegpu package. ```bash # If using a python venv: python3 -m venv venv source venv/bin/activate/bash ``` ```bat :: If using a python venv python -m venv venv call "venv/Scripts/activate.bat" ``` -------------------------------- ### start() Source: https://docs.flamegpu.com/api/classflamegpu_1_1detail_1_1SteadyClockTimer.html Records the start time using the steady clock. ```APIDOC ## void start() ### Description Record the start steady clock time. ``` -------------------------------- ### Initialize and run a simulation Source: https://docs.flamegpu.com/guide/running-a-simulation/index.html Demonstrates the basic workflow of creating a CUDASimulation from a model and executing it. ```cpp // Fully declare a model flamegpu::ModelDescription model("example model"); ... // Create a simulation object from the model flamegpu::CUDASimulation simulation(model); // Configure the simulation ... // Run the simulation simulation.simulate(); ``` ```python # Fully declare a model model = pyflamegpu.ModelDescription("example model") ... # Create a simulation object from the model simulation = pyflamegpu.CUDASimulation(model) # Configure the Simulation ... # Run the simulation simulation.simulate() ``` -------------------------------- ### start() Source: https://docs.flamegpu.com/api/classflamegpu_1_1detail_1_1CUDAEventTimer.html Records the start event and resets the synchronization flag. ```APIDOC ### Method `void start()` Records the start event to begin timing. ``` -------------------------------- ### Install pyflamegpu via Pip Source: https://docs.flamegpu.com/_sources/quickstart/index.rst.txt Install the pyflamegpu package from the wheelhouse using pip. ```bash python3 -m pip install --extra-index-url https://whl.flamegpu.com/whl/cuda130/ pyflamegpu ``` ```bat python -m pip install --extra-index-url https://whl.flamegpu.com/whl/cuda130/ pyflamegpu ``` -------------------------------- ### Configure Logging and Simulation Source: https://docs.flamegpu.com/_sources/tutorial/index.rst.txt Set up step logging and initialize the CUDA simulation environment. ```python # Specify the desired StepLoggingConfig step_log_cfg = pyflamegpu.StepLoggingConfig(model) # Log every step step_log_cfg.setFrequency(1) # Include the mean of the "point" agent population's variable 'drift' step_log_cfg.agent("point").logMeanFloat("drift") # Create and init the simulation cuda_model = pyflamegpu.CUDASimulation(model) cuda_model.initialise(sys.argv) # Attach the logging config cuda_model.setStepLog(step_log_cfg) ``` -------------------------------- ### Configure and Run Simulation Visualisation Source: https://docs.flamegpu.com/_sources/tutorial/index.rst.txt Sets up the visualisation environment, including camera parameters, agent models, and boundary sketches, conditional on visualisation support. ```cpp #ifdef FLAMEGPU_VISUALISATION // Create visualisation flamegpu::visualiser::ModelVis m_vis = cuda_model.getVisualisation(); // Set the initial camera location and speed const float INIT_CAM = ENV_WIDTH / 2.0f; m_vis.setInitialCameraTarget(INIT_CAM, INIT_CAM, 0); m_vis.setInitialCameraLocation(INIT_CAM, INIT_CAM, ENV_WIDTH); m_vis.setCameraSpeed(0.01f); m_vis.setSimulationSpeed(25); // Add "point" agents to the visualisation flamegpu::visualiser::AgentVis point_agt = m_vis.addAgent("point"); // Location variables have names "x" and "y" so will be used by default point_agt.setModel(flamegpu::visualiser::Stock::Models::ICOSPHERE); point_agt.setModelScale(1/10.0f); // Mark the environment bounds flamegpu::visualiser::LineVis pen = m_vis.newPolylineSketch(1, 1, 1, 0.2f); pen.addVertex(0, 0, 0); pen.addVertex(0, ENV_WIDTH, 0); pen.addVertex(ENV_WIDTH, ENV_WIDTH, 0); pen.addVertex(ENV_WIDTH, 0, 0); pen.addVertex(0, 0, 0); // Open the visualiser window m_vis.activate(); #endif // Run the simulation cuda_model.simulate(); #ifdef FLAMEGPU_VISUALISATION // Keep the visualisation window active after the simulation has completed m_vis.join(); #endif ``` ```python # Only run this block if pyflamegpu was built with visualisation support if pyflamegpu.VISUALISATION: # Create visualisation m_vis = cuda_model.getVisualisation() # Set the initial camera location and speed INIT_CAM = ENV_WIDTH / 2 m_vis.setInitialCameraTarget(INIT_CAM, INIT_CAM, 0) m_vis.setInitialCameraLocation(INIT_CAM, INIT_CAM, ENV_WIDTH) m_vis.setCameraSpeed(0.01) m_vis.setSimulationSpeed(25) # Add "point" agents to the visualisation point_agt = m_vis.addAgent("point") # Location variables have names "x" and "y" so will be used by default point_agt.setModel(pyflamegpu.ICOSPHERE); point_agt.setModelScale(1/10.0); # Mark the environment bounds pen = m_vis.newPolylineSketch(1, 1, 1, 0.2) pen.addVertex(0, 0, 0) pen.addVertex(0, ENV_WIDTH, 0) pen.addVertex(ENV_WIDTH, ENV_WIDTH, 0) pen.addVertex(ENV_WIDTH, 0, 0) pen.addVertex(0, 0, 0) # Open the visualiser window m_vis.activate() # Run the simulation cuda_model.simulate() if pyflamegpu.VISUALISATION: # Keep the visualisation window active after the simulation has completed m_vis.join() ``` -------------------------------- ### Directed Graph JSON Format Example Source: https://docs.flamegpu.com/_sources/guide/host-functions/interacting-with-environment.rst.txt Example structure for the JSON format used by importGraph and exportGraph. ```json { "nodes": [ { "id": "1", "bar": [ 12.0, 22.0 ] }, { "id": "2", "bar": [ 13.0, 23.0 ] } ], "links": [ { "source": "1", "target": "2", "foo": 21 }, { "source": "2", "target": "1", "foo": 22 } ] } ``` -------------------------------- ### Configure Window and Visual Settings Source: https://docs.flamegpu.com/_sources/api/program_listing_file_src_flamegpu_visualiser_ModelVis.cpp.rst.txt Methods to set window properties, clear color, and FPS display settings. ```cpp void ModelVis::setWindowTitle(const std::string& title) { ModelConfig::setString(&data->modelCfg.windowTitle, title); } void ModelVis::setWindowDimensions(const unsigned int& width, const unsigned int& height) { data->modelCfg.windowDimensions[0] = width; data->modelCfg.windowDimensions[1] = height; } void ModelVis::setClearColor(const float& red, const float& green, const float& blue) { data->modelCfg.clearColor[0] = red; data->modelCfg.clearColor[1] = green; data->modelCfg.clearColor[2] = blue; } void ModelVis::setFPSVisible(const bool& showFPS) { data->modelCfg.fpsVisible = showFPS; } void ModelVis::setFPSColor(const float& red, const float& green, const float& blue) { data->modelCfg.fpsColor[0] = red; data->modelCfg.fpsColor[1] = green; data->modelCfg.fpsColor[2] = blue; } ``` -------------------------------- ### Find Bin Start Indices Source: https://docs.flamegpu.com/api/program_listing_file_src_flamegpu_simulation_detail_CUDAEnvironmentDirectedGraphBuffers.cu.html Kernel to identify the starting index of edges for each vertex in a sorted edge list. ```cuda __global__ void findBinStart(unsigned int *pbm, uint64_t* keys, unsigned int edge_count, unsigned int vertex_count) { unsigned int index = (blockIdx.x * blockDim.x) + threadIdx.x; if (index < edge_count) { // Bins correspond to the first uint32 of the pair const uint32_t my_vertex = reinterpret_cast(keys)[(index * 2)+1]; if (index == 0 || my_vertex != reinterpret_cast(keys)[((index - 1) * 2)+1]) { // Store the Index of the first edges for the corresponding vertex pbm[my_vertex] = index; } } // 1 thread must init the final cell of the PBM if (index == 0) { pbm[vertex_count] = edge_count; } } ``` -------------------------------- ### Singleton Initialization Source: https://docs.flamegpu.com/_sources/api/program_listing_file_src_flamegpu_simulation_CUDASimulation.cu.rst.txt Initializes simulation singletons and environment managers once a device is selected. ```cpp void CUDASimulation::initialiseSingletons() { // Only do this once. if (!singletonsInitialised) { // If the device has not been specified, also check the compute capability is OK // Check the compute capability of the device, throw an exception if not valid for the executable. if (!detail::compute_capability::checkComputeCapability(static_cast(config.device_id))) { int min_cc = detail::compute_capability::minimumCompiledComputeCapability(); std::string compiled_ccs = detail::compute_capability::compiledCompiledComputeCapabilitiesString(); int cc = detail::compute_capability::getComputeCapability(static_cast(config.device_id)); THROW exception::InvalidCUDAComputeCapability("Error application compiled for CUDA Compute Capabilities \"%s\". Rebuild including compute capability <= %d for device %u.", compiled_ccs.c_str(), cc, config.device_id); } gpuErrchk(cudaGetDevice(&deviceInitialised)); // Get references to all required singleton and store in the instance. singletons = new Singletons((!submodel)? detail::EnvironmentManager::create(*model->environment) : detail::EnvironmentManager::create(*model->environment, mastermodel->singletons->environment, *submodel->subenvironment)); // Reinitialise random for this simulation instance singletons->rng.reseed(getSimulationConfig().random_seed); cudaStream_t stream_0 = getStream(0); // Pass created RandomManager to host api ``` -------------------------------- ### Configure and Run Simulation Source: https://docs.flamegpu.com/_sources/guide/running-a-simulation/configuring-execution.rst.txt Update simulation steps, input files, and device IDs before applying the configuration and executing the simulation. ```cpp // Create a simulation object from the model flamegpu::CUDASimulation simulation(model); // Update the configuration simulation.SimulationConfig().steps = 100; simulation.SimulationConfig().input_file = "input.json"; simulation.CUDAConfig().device_id = 1; // Apply the updated configuration simulation.applyConfig(); // Run the simulation simulation.simulate(); ``` ```python # Create a simulation object from the model simulation = pyflamegpu.CUDASimulation(model) # Update the configuration simulation.SimulationConfig().steps = 100 simulation.SimulationConfig().input_file = "input.json" simulation.CUDAConfig().device_id = 1 # Apply the updated configuration simulation.applyConfig() # Run the simulation simulation.simulate() ``` -------------------------------- ### Print Simulation Help Source: https://docs.flamegpu.com/_sources/api/program_listing_file_src_flamegpu_simulation_Simulation.cu.rst.txt Displays the command-line usage and available arguments for the simulation executable. ```cpp void Simulation::printHelp(const char* executable) { printf("FLAME GPU %s\n", flamegpu::VERSION_FULL); printf("Usage: %s [-s steps] [-d device_id] [-r random_seed]\n", executable); printf("Optional Arguments:\n"); const char *line_fmt = "%-18s %s\n"; printf(line_fmt, "-h, --help", "show this help message and exit"); printf(line_fmt, "-i, --in ", "Initial state file (XML or JSON)"); printf(line_fmt, " --out-step ", "Step log file (XML or JSON)"); printf(line_fmt, " --out-exit ", "Exit log file (XML or JSON)"); printf(line_fmt, " --out-log ", "Common log file (XML or JSON)"); printf(line_fmt, "-s, --steps ", "Number of simulation iterations"); printf(line_fmt, "-r, --random ", "RandomManager seed"); printf(line_fmt, "-q, --quiet", "Do not print progress information to console"); printf(line_fmt, "-v, --verbose", "Print config, progress and timing (-t) information to console."); printf(line_fmt, "-t, --timing", "Output timing information to stdout"); printf(line_fmt, "-u, --silence-unknown-args", "Silence warnings for unknown arguments passed after this flag."); #ifdef FLAMEGPU_VISUALISATION printf(line_fmt, "-c, --console", "Console mode, disable the visualisation"); #endif printHelp_derived(); } ``` -------------------------------- ### Get Model Name Source: https://docs.flamegpu.com/api/program_listing_file_src_flamegpu_model_ModelDescription.cpp.html Retrieves the name of the model. ```cpp std::string ModelDescription::getName() const { return model->name; } ``` -------------------------------- ### void newEndSection() Source: https://docs.flamegpu.com/api/classflamegpu_1_1visualiser_1_1PanelVis.html Ends a previously started collapsible section. ```APIDOC ### Method `void newEndSection()` ### Description End a section, the following elements are not part of the previous collapsible section. If this is not preceded by a call to newSection() it will have no effect. ``` -------------------------------- ### StateWriter::beginWrite Source: https://docs.flamegpu.com/api/classflamegpu_1_1io_1_1StateWriter.html Starts the writing process to a specified file. ```APIDOC ## virtual void beginWrite(const std::string &output_file, bool pretty_print) ### Description Starts writing to the specified file. Throws an exception if called a second time before endWrite() has been called. ### Parameters - **output_file** (const std::string &) - Required - Filename of the output file. - **pretty_print** (bool) - Required - Whether the output file should be formatted or minified. ``` -------------------------------- ### Timer::start Source: https://docs.flamegpu.com/api/classflamegpu_1_1detail_1_1Timer.html Starts the recording process for the timer instance. ```APIDOC ## virtual void start() = 0 ### Description Starts recording with this timer instance. ``` -------------------------------- ### Simulation::initialise Source: https://docs.flamegpu.com/api/classflamegpu_1_1Simulation.html Initializes the simulation with command line arguments. ```APIDOC ## void initialise(int argc, const char **argv) ### Description Initializes the simulation environment using the provided command line arguments. ### Parameters - **argc** (int) - The number of arguments. - **argv** (const char**) - The array of argument strings. ``` -------------------------------- ### File System and Directory Initialization Source: https://docs.flamegpu.com/_sources/api/program_listing_file_src_flamegpu_simulation_CUDAEnsemble.cu.rst.txt Handles the removal of existing exit logs and the creation of output directories for simulation runs. ```cpp if (std::filesystem::exists(exit_path)) { THROW exception::FileAlreadyExists("Exit log file '%s' already exists, in CUDAEnsemble::simulate()", exit_path.generic_string().c_str()); } } } else { // Delete pre-existing exit log files for (const auto& exit_path : exit_files) { std::filesystem::remove(exit_path); // Returns false if the file didn't exist } } } // Create any missing directories try { std::filesystem::create_directories(config.out_directory); } catch (const std::exception &e) { THROW exception::InvalidArgument("Unable to use output directory '%s', in CUDAEnsemble::simulate(): %s", config.out_directory.c_str(), e.what()); } for (const auto &p : plans) { const auto subdir = p.getOutputSubdirectory(); if (!subdir.empty()) { std::filesystem::path sub_path = config.out_directory; try { sub_path.append(subdir); std::filesystem::create_directories(sub_path); } catch (const std::exception &e) { THROW exception::InvalidArgument("Unable to use output subdirectory '%s', in CUDAEnsemble::simulate(): %s", sub_path.generic_string().c_str(), e.what()); } } } } ``` -------------------------------- ### void clear() Source: https://docs.flamegpu.com/api/classflamegpu_1_1visualiser_1_1LineVis.html Removes all sketch data to start drawing a replacement. ```APIDOC ### Method void clear() ``` -------------------------------- ### getElapsedSeconds() Source: https://docs.flamegpu.com/api/classflamegpu_1_1detail_1_1CUDAEventTimer.html Calculates the elapsed time between the start and stop events in seconds. ```APIDOC ### Method `float getElapsedSeconds()` Returns the elapsed time in seconds. ``` -------------------------------- ### Initialize Simulation Visualization Source: https://docs.flamegpu.com/_sources/tutorial/index.rst.txt Configures camera settings, agent rendering, and environment bounds for the FLAME GPU visualizer. ```cpp // Only compile this block if being built with visualisation support #ifdef FLAMEGPU_VISUALISATION // Create visualisation flamegpu::visualiser::ModelVis m_vis = cuda_model.getVisualisation(); // Set the initial camera location and speed const float INIT_CAM = ENV_WIDTH / 2.0f; m_vis.setInitialCameraTarget(INIT_CAM, INIT_CAM, 0); m_vis.setInitialCameraLocation(INIT_CAM, INIT_CAM, ENV_WIDTH); m_vis.setCameraSpeed(0.01f); m_vis.setSimulationSpeed(25); // Add "point" agents to the visualisation flamegpu::visualiser::AgentVis point_agt = m_vis.addAgent("point"); // Location variables have names "x" and "y" so will be used by default point_agt.setModel(flamegpu::visualiser::Stock::Models::ICOSPHERE); point_agt.setModelScale(1/10.0f); // Mark the environment bounds flamegpu::visualiser::LineVis pen = m_vis.newPolylineSketch(1, 1, 1, 0.2f); pen.addVertex(0, 0, 0); pen.addVertex(0, ENV_WIDTH, 0); pen.addVertex(ENV_WIDTH, ENV_WIDTH, 0); pen.addVertex(ENV_WIDTH, 0, 0); pen.addVertex(0, 0, 0); // Open the visualiser window m_vis.activate(); #endif #ifdef FLAMEGPU_VISUALISATION // Keep the visualisation window active after the simulation has completed m_vis.join(); #endif ``` -------------------------------- ### getElapsedMilliseconds() Source: https://docs.flamegpu.com/api/classflamegpu_1_1detail_1_1CUDAEventTimer.html Calculates the elapsed time between the start and stop events in milliseconds. ```APIDOC ### Method `float getElapsedMilliseconds()` Returns the elapsed time in milliseconds. ``` -------------------------------- ### Initialize Simulation Logging Source: https://docs.flamegpu.com/api/program_listing_file_src_flamegpu_simulation_CUDAEnsemble.cu.html Sets up timers, thread-safe queues, and the simulation logger for tracking ensemble execution. ```cpp const unsigned int TOTAL_RUNNERS = static_cast(devices.size()) * config.concurrent_runs; // Log Time (We can't use CUDA events here, due to device resets) auto ensemble_timer = detail::SteadyClockTimer(); ensemble_timer.start(); // Reset the elapsed time. ensemble_elapsed_time = 0.; // Logging thread-safety items std::queue log_export_queue; std::mutex log_export_queue_mutex; std::condition_variable log_export_queue_cdn; #ifdef FLAMEGPU_ENABLE_MPI // In MPI mode, Rank 0 will collect errors from all ranks std::multimap err_detail = {}; #endif std::vector err_detail_local = {}; // Init log worker detail::SimLogger *log_worker = nullptr; if (!config.out_directory.empty()) { log_worker = new detail::SimLogger(run_logs, plans, config.out_directory, config.out_format, log_export_queue, log_export_queue_mutex, log_export_queue_cdn, step_log_config.get(), exit_log_config.get(), step_log_config && step_log_config->log_timing, exit_log_config && exit_log_config->log_timing); } ``` -------------------------------- ### WrapFilter::begin() Source: https://docs.flamegpu.com/api/classflamegpu_1_1MessageSpatial2D_1_1In.html Returns an iterator to the start of the message list subset. ```APIDOC ## iterator begin(void) const ### Description Returns an iterator to the start of the message list subset about the search origin defined in the WrapFilter. ``` -------------------------------- ### Create Visualisation Objects Source: https://docs.flamegpu.com/_sources/api/program_listing_file_src_flamegpu_visualiser_ModelVis.cpp.rst.txt Methods to instantiate static models, line sketches, and UI panels. ```cpp StaticModelVis ModelVis::newStaticModel(const std::string &modelPath, const std::string &texturePath) { // Create ModelConfig::StaticModel auto m = std::make_shared(); // set modelPath, texturePath m->path = modelPath; m->texture = texturePath; // add to ModelConfig.staticModels data->modelCfg.staticModels.push_back(m); // Create return type return StaticModelVis(data->modelCfg.staticModels.back()); } LineVis ModelVis::newLineSketch(float r, float g, float b, float a) { auto m = std::make_shared(LineConfig::Type::Lines); data->modelCfg.lines.push_back(m); return LineVis(m, r, g, b, a); } LineVis ModelVis::newPolylineSketch(float r, float g, float b, float a) { auto m = std::make_shared(LineConfig::Type::Polyline); data->modelCfg.lines.push_back(m); return LineVis(m, r, g, b, a); } PanelVis ModelVis::newUIPanel(const std::string& panel_title) { if (data->modelCfg.panels.find(panel_title) != data->modelCfg.panels.end()) { THROW exception::InvalidOperation("Panel with title '%s' already exists.\n", panel_title.c_str()); } auto m = std::make_shared(panel_title); data->modelCfg.panels.emplace(panel_title, m); return PanelVis(m, data->model.getModelDescription().environment); } ``` -------------------------------- ### Variable Accessors Source: https://docs.flamegpu.com/api/classflamegpu_1_1AgentInstance.html Methods for getting and setting agent variables by name. ```APIDOC ## Methods ### getVariable - **template T getVariable(const std::string &variable_name)**: Retrieve a variable value. - **template std::array getVariable(const std::string &variable_name)**: Retrieve an array variable. - **template T getVariable(const std::string &variable_name, unsigned int index)**: Retrieve a specific index of an array variable. ### setVariable - **template void setVariable(const std::string &variable_name, T value)**: Set a variable value. - **template void setVariable(const std::string &variable_name, const std::array &value)**: Set an array variable. - **template void setVariable(const std::string &variable_name, unsigned int index, T value)**: Set a specific index of an array variable. ``` -------------------------------- ### Initialize Agent Population with AgentVector Source: https://docs.flamegpu.com/_sources/guide/running-a-simulation/initial-state.rst.txt Demonstrates creating an AgentVector, setting agent variables, and passing the population to the simulation. ```cpp // Create a population of 1000 'Boid' agents flamegpu::AgentVector population(model.Agent("Boid"), 1000); // Manually initialise the "speed" variable in each agent for (flamegpu::AgentVector::Agent &instance : population) { instance.setVariable("speed", 1.0f); } // Specifically set the 12th agent's variable differently population[11].setVariable("speed", 0.0f); // Set the "Boid" population in the default state with the AgentVector simulation.setPopulationData(population); // Set the "Boid" population in the "healthy" state with the AgentVector // simulation.setPopulationData(population, "healthy"); ``` ```python # Create a population of 1000 'Boid' agents population = pyflamegpu.AgentVector(model.Agent("Boid"), 1000) for instance in population: instance.setVariableFloat("speed", 1.0) # Specifically set the 12th agent's variable differently population[11].setVariableFloat("speed", 0.0) # Set the "Boid" population in the default state with the AgentVector simulation.setPopulationData(population) # Set the "Boid" population in the "healthy" state with the AgentVector # simulation.setPopulationData(population, "healthy") ``` -------------------------------- ### flamegpu::util::nvtx::push Source: https://docs.flamegpu.com/api/file_include_flamegpu_util_nvtx.h.html Starts a new NVTX range for profiling. ```APIDOC ## void flamegpu::util::nvtx::push(const char* name, uint32_t color) ### Description Starts a new NVTX range with the specified name and color for performance profiling. ### Parameters - **name** (const char*) - The name of the range. - **color** (uint32_t) - The color associated with the range. ``` -------------------------------- ### Initialize CUDASimulation and Environment Source: https://docs.flamegpu.com/_sources/api/program_listing_file_src_flamegpu_simulation_CUDASimulation.cu.rst.txt Handles the setup of HostAPI, message maps, environment properties, and device strings. It also manages submodel initialization and conditional visualization hooks. ```cpp host_api = std::make_unique(*this, singletons->rng, singletons->scatter, agentOffsets, agentData, singletons->environment, macro_env, directed_graph_map, 0, stream_0); // Host fns are currently all serial for (auto &cm : message_map) { cm.second->init(singletons->scatter, 0, stream_0); } // Populate the environment properties if (!submodel) { for (const auto &it : model->environment->directed_graphs) { // insert into map using value_type and store a reference to the map pair directed_graph_map.emplace(it.first, std::make_shared(*it.second)); } macro_env->init(stream_0); } else { for (const auto& it : model->environment->directed_graphs) { const auto sub_it = submodel->subenvironment->directed_graphs.find(it.first); if (sub_it != submodel->subenvironment->directed_graphs.end()) { // if is linked to parent graph, instead store that graph's ptr // insert into map using value_type and store a reference to the map pair const auto master_graph_it = mastermodel->directed_graph_map.find(sub_it->second); if (master_graph_it != mastermodel->directed_graph_map.end()) { directed_graph_map.emplace(it.first, master_graph_it->second); } else { THROW exception::UnknownInternalError("Failed to find master model '%s's directed graph '%s' when intialising submodel '%s', this should not happen, please report this as a bug.\n", mastermodel->model->name.c_str(), sub_it->second.c_str(), this->model->name.c_str()); } } else { // insert into map using value_type and store a reference to the map pair directed_graph_map.emplace(it.first, std::make_shared(*it.second)); } } macro_env->init(*submodel->subenvironment, mastermodel->macro_env, stream_0); } // Populate device strings for (const auto& [agent_name, agent] : model->agents) { singletons->strings.registerDeviceString(agent_name); for (const auto& state_name : agent->states) { singletons->strings.registerDeviceString(state_name); } } // Propagate singleton init to submodels for (auto &sm : submodel_map) { sm.second->initialiseSingletons(); } // Store the WDDM/TCC driver mode status, for timer class decisions. Result is cached in the anon namespace to avoid multiple queries deviceUsingWDDM = detail::wddm::deviceIsWDDM(); #ifdef FLAMEGPU_VISUALISATION if (visualisation) { visualisation->updateRandomSeed(); // Incase user hasn't triggered applyConfig() visualisation->registerEnvProperties(); } #endif singletonsInitialised = true; } else { int t = -1; gpuErrchk(cudaGetDevice(&t)); if (t != deviceInitialised) { THROW exception::CUDAError("CUDASimulation initialised on device %d, but stepped on device %d.\n", deviceInitialised, t); } } // Populate the environment properties initEnvironmentMgr(); initMacroEnvironment(); // Ensure there are enough streams to execute the layer. // Taking into consideration if in-layer concurrency is disabled or not. unsigned int nStreams = getMaximumLayerWidth(); this->createStreams(nStreams); // Ensure RTC is set up. initialiseRTC(); #ifdef FLAMEGPU_VISUALISATION if (visualisation) { visualisation->hookVis(visualisation, directed_graph_map); } } ``` -------------------------------- ### Configure Camera and View Settings Source: https://docs.flamegpu.com/_sources/api/program_listing_file_src_flamegpu_visualiser_ModelVis.cpp.rst.txt Methods to define initial camera position, target, speed, and projection settings. ```cpp void ModelVis::setInitialCameraLocation(const float &x, const float &y, const float &z) { data->modelCfg.cameraLocation[0] = x; data->modelCfg.cameraLocation[1] = y; data->modelCfg.cameraLocation[2] = z; } void ModelVis::setInitialCameraTarget(const float &x, const float &y, const float &z) { data->modelCfg.cameraTarget[0] = x; data->modelCfg.cameraTarget[1] = y; data->modelCfg.cameraTarget[2] = z; } void ModelVis::setInitialCameraRoll(const float &roll) { data->modelCfg.cameraRoll = roll; } void ModelVis::setCameraSpeed(const float &speed, const float &shiftMultiplier) { data->modelCfg.cameraSpeed[0] = speed; data->modelCfg.cameraSpeed[1] = shiftMultiplier; } void ModelVis::setViewClips(const float &nearClip, const float &farClip) { data->modelCfg.nearFarClip[0] = nearClip; data->modelCfg.nearFarClip[1] = farClip; } void ModelVis::setOrthographic(const bool& isOrtho) { data->modelCfg.isOrtho = isOrtho; } void ModelVis::setOrthographicZoomModifier(const float& zoomMod) { data->modelCfg.orthoZoom = zoomMod; } ``` -------------------------------- ### Activate Python Environment Source: https://docs.flamegpu.com/_sources/quickstart/index.rst.txt Activate the virtual environment containing the pyflamegpu installation. ```bash # Assuming a python venv was created in the current directory, named venv source venv/bin/bash/activate ``` ```bat :: Assuming a python venv was created in the current directory, named venv call "venv/Scripts/activate.bat" ``` -------------------------------- ### Print Ensemble Help Information Source: https://docs.flamegpu.com/api/program_listing_file_src_flamegpu_simulation_CUDAEnsemble.cu.html Displays the available command-line arguments and usage instructions for the ensemble executable. ```cpp void CUDAEnsemble::printHelp(const char *executable) { printf("FLAME GPU %s\n", flamegpu::VERSION_FULL); printf("Usage: %s [optional arguments]\n", executable); printf("Optional Arguments:\n"); const char *line_fmt = "%-18s %s\n"; printf(line_fmt, "-h, --help", "show this help message and exit"); printf(line_fmt, "-d, --devices ", "Comma separated list of device ids to be used"); printf(line_fmt, "", "By default, all available devices will be used."); printf(line_fmt, "-c, --concurrent ", "Number of concurrent simulations to run per device"); printf(line_fmt, "", "By default, 4 will be used."); printf(line_fmt, "-o, --out ", "Directory and filetype for ensemble outputs"); printf(line_fmt, "-q, --quiet", "Do not print progress information to console"); printf(line_fmt, "-v, --verbose", "Print config, progress and timing (-t) information to console"); printf(line_fmt, "-t, --timing", "Output timing information to stdout"); printf(line_fmt, "-e, --error ", "The error level 0, 1, 2, off, slow or fast"); printf(line_fmt, "", "By default, \"slow\" will be used."); printf(line_fmt, "-u, --silence-unknown-args", "Silence warnings for unknown arguments passed after this flag."); #ifdef _MSC_VER printf(line_fmt, " --standby", "Allow the machine to enter standby during execution"); #endif } ``` -------------------------------- ### Get Metadata Device Pointer Source: https://docs.flamegpu.com/_sources/api/program_listing_file_src_flamegpu_simulation_detail_CUDAMessage.cu.rst.txt Retrieves the device pointer for the message metadata. ```cpp const void *CUDAMessage::getMetaDataDevicePtr() const { return specialisation_handler->getMetaDataDevicePtr(); } ``` -------------------------------- ### WrapFilter::begin() Source: https://docs.flamegpu.com/api/classflamegpu_1_1MessageArray2D_1_1In_1_1WrapFilter.html Returns an iterator to the start of the message list subset about the search origin. ```APIDOC ## __device__ iterator begin(void) const ### Description Returns an iterator to the start of the message list subset about the search origin. ``` -------------------------------- ### Display model help information Source: https://docs.flamegpu.com/api/page_md_README.html Executes a compiled model with the help flag to list available command line arguments. ```bash ./bin/Release/game_of_life --help ``` -------------------------------- ### OutEdgeFilter::begin Source: https://docs.flamegpu.com/api/classflamegpu_1_1DeviceEnvironmentDirectedGraph_1_1OutEdgeFilter.html Returns an iterator to the start of the edge list subset for the specified vertex. ```APIDOC ### __device__ iterator begin(void) const Returns an iterator to the start of the message list subset about the search origin. ``` -------------------------------- ### List CMake Configuration Options Source: https://docs.flamegpu.com/api/page_md_README.html Run this command from the build directory to view all available CMake configuration options for the project. ```bash cmake -LH .. ``` -------------------------------- ### Initialize Header Environment Source: https://docs.flamegpu.com/api/program_listing_file_src_flamegpu_runtime_detail_curve_curve_rtc.cpp.html Calculates buffer sizes and generates dynamic variable definitions for the runtime compilation header. ```cpp void CurveRTCHost::initHeaderEnvironment(const size_t env_buffer_len) { // Calculate size of, and generate dynamic variables buffer std::stringstream variables; data_buffer_size = env_buffer_len; // Fix alignment data_buffer_size += (data_buffer_size % sizeof(void*) != 0) ? sizeof(void*) - (data_buffer_size % sizeof(void*)) : 0; agent_data_offset = data_buffer_size; data_buffer_size += agent_variables.size() * sizeof(void*); messageOut_data_offset = data_buffer_size; data_buffer_size += messageOut_variables.size() * sizeof(void*); messageIn_data_offset = data_buffer_size; data_buffer_size += messageIn_variables.size() * sizeof(void*); newAgent_data_offset = data_buffer_size; data_buffer_size += newAgent_variables.size() * sizeof(void*); directedGraphVertex_data_offset = data_buffer_size; data_buffer_size += directedGraph_vertexProperties.size() * sizeof(void*); directedGraphEdge_data_offset = data_buffer_size; data_buffer_size += directedGraph_edgeProperties.size() * sizeof(void*); envMacro_data_offset = data_buffer_size; data_buffer_size += RTCEnvMacroProperties.size() * sizeof(void*); count_data_offset = data_buffer_size; data_buffer_size += count_buffer.size() * sizeof(unsigned int); variables << "__constant__ char " << getVariableSymbolName() << "[" << data_buffer_size << "];\n"; setHeaderPlaceholder("$DYNAMIC_VARIABLES", variables.str()); // generate Environment::get func implementation ($DYNAMIC_ENV_GETVARIABLE_IMPL) { std::stringstream getEnvVariableImpl; for (std::pair element : RTCEnvVariables) { RTCEnvVariableProperties props = element.second; { getEnvVariableImpl << " if (strings_equal(name, \"" << element.first << "\")) {\n"; getEnvVariableImpl << "#if !defined(FLAMEGPU_SEATBELTS) || FLAMEGPU_SEATBELTS\n"; getEnvVariableImpl << " if(sizeof(detail::type_decode::type_t) != " << element.second.type_size << ") {\n"; getEnvVariableImpl << " DTHROW(\"Environment property '%s' type mismatch.\\n\", name);\n"; getEnvVariableImpl << " return {};\n"; getEnvVariableImpl << " } else if(detail::type_decode::len_t != " << element.second.elements << ") {\n"; ``` -------------------------------- ### InEdgeFilter::begin() Source: https://docs.flamegpu.com/api/classflamegpu_1_1DeviceEnvironmentDirectedGraph_1_1InEdgeFilter.html Returns an iterator to the start of the in-edge list subset joining the vertex. ```APIDOC ## __device__ iterator begin(void) const ### Description Returns an iterator to the start of the in-edge list subset joining the vertex. ```