#include "taichi.h" // Note: You DO NOT have to install taichi or taichi_mpm.
using namespace taichi;// You only need [taichi.h] - see below for instructions.
const int n = 80 /grid resolution (cells)/, window_size = 800;
const real dt = 1e-4_f, frame_dt = 1e-3_f, dx = 1.0_f / n, inv_dx = 1.0_f / dx;
auto particle_mass = 1.0_f, vol = 1.0_f;
auto hardening = 10.0_f, E = 1e4_f, nu = 0.2_f;
real mu_0 = E / (2 * (1 + nu)), lambda_0 = E * nu / ((1+nu) * (1 - 2 * nu));
using Vec = Vector2; using Mat = Matrix2; bool plastic = true;
struct Particle { Vec x, v; Mat F, C; real Jp; int c/color/;
Particle(Vec x, int c, Vec v=Vec(0)) : x(x), v(v), F(1), C(0), Jp(1), c(c){}};
std::vector particles;
Vector3 grid[n + 1][n + 1]; // velocity + mass, node_res = cell_res + 1
void advance(real dt) {
std::memset(grid, 0, sizeof(grid)); // Reset grid
for (auto &p : particles) { // P2G
Vector2i base_coord=(p.xinv_dx-Vec(0.5_f)).cast();//element-wise floor
Vec fx = p.x * inv_dx - base_coord.cast();
// Quadratic kernels [http://mpm.graphics Eqn. 123, with x=fx, fx-1,fx-2]
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
auto e = std::exp(hardening * (1.0_f - p.Jp)), mu=mu_0e, lambda=lambda_0e;
real J = determinant(p.F); // Current volume
Mat r, s; polar_decomp(p.F, r, s); //Polar decomp. for fixed corotated model
auto stress = // Cauchy stress times dt and inv_dx
-4inv_dxinv_dxdtvol(2mu(p.F-r) * transposed(p.F)+lambda*(J-1)J);
auto affine = stress+particle_massp.C;
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { // Scatter to grid
auto dpos = (Vec(i, j) - fx) * dx;
Vector3 mv(p.v * particle_mass, particle_mass); //translational momentum
grid[base_coord.x + i][base_coord.y + j] +=
w[i].xw[j].y * (mv + Vector3(affinedpos, 0));
}
}
for(int i = 0; i <= n; i++) for(int j = 0; j <= n; j++) { //For all grid nodes
auto &g = grid[i][j];
if (g[2] > 0) { // No need for epsilon here
g /= g[2]; // Normalize by mass
g += dt * Vector3(0, -200, 0); // Gravity
real boundary=0.05,x=(real)i/n,y=real(j)/n; //boundary thick.,node coord
if (x < boundary||x > 1-boundary||y > 1-boundary) g=Vector3(0); //Sticky
if (y < boundary) g[1] = std::max(0.0_f, g[1]); //"Separate"
}
}
for (auto &p : particles) { // Grid to particle
Vector2i base_coord=(p.x*inv_dx-Vec(0.5_f)).cast();//element-wise floor
Vec fx = p.x * inv_dx - base_coord.cast();
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
p.C = Mat(0); p.v = Vec(0);
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) {
auto dpos = (Vec(i, j) - fx),
grid_v = Vec(grid[base_coord.x + i][base_coord.y + j]);
auto weight = w[i].x * w[j].y;
p.v += weight * grid_v; // Velocity
p.C += 4 * inv_dx * Mat::outer_product(weight * grid_v, dpos); // APIC C
}
p.x += dt * p.v; // Advection
auto F = (Mat(1) + dt * p.C) * p.F; // MLS-MPM F-update
Mat svd_u, sig, svd_v; svd(F, svd_u, sig, svd_v);
for (int i = 0; i < 2 * int(plastic); i++) // Snow Plasticity
sig[i][i] = clamp(sig[i][i], 1.0_f - 2.5e-2_f, 1.0_f + 7.5e-3_f);
real oldJ = determinant(F); F = svd_u * sig * transposed(svd_v);
real Jp_new = clamp(p.Jp * oldJ / determinant(F), 0.6_f, 20.0_f);
p.Jp = Jp_new; p.F = F;
}
}
void add_object(Vec center, int c) { // Seed particles with position and color
for (int i = 0; i < 500; i++) // Randomly sample 1000 particles in the square
particles.push_back(Particle((Vec::rand()*2.0_f-Vec(1))*0.08_f + center, c));
}
int main() {
GUI gui("Real-time 2D MLS-MPM", window_size, window_size);
add_object(Vec(0.55,0.45), 0xED553B); add_object(Vec(0.45,0.65), 0xF2B134);
add_object(Vec(0.55,0.85), 0x068587); auto &canvas = gui.get_canvas();int f=0;
for (int i = 0;; i++) { // Main Loop
advance(dt); // Advance simulation
if (i % int(frame_dt / dt) == 0) { // Visualize frame
canvas.clear(0x112F41); // Clear background
canvas.rect(Vec(0.04), Vec(0.96)).radius(2).color(0x4FB99F).close();// Box
for(auto p:particles)canvas.circle(p.x).radius(2).color(p.c);//Particles
gui.update(); // Update image
// canvas.img.write_as_image(fmt::format("tmp/{:05d}.png", f++));
}
}
}
Rewrite it so it uses opengl and eigen, don't use glad
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure! I'll help you rewrite the provided Material Point Method (MPM) simulation code to use OpenGL for rendering and Eigen for linear algebra operations. We'll remove dependencies on Taichi and avoid using glad. Instead, we'll use GLFW for window management and input handling, and GLEW as the OpenGL extension loader.
Here's a step-by-step guide along with the complete rewritten code.
Overview
Dependencies:
Eigen: For vector and matrix operations.
GLFW: To create a window and handle user inputs.
GLEW: To load OpenGL functions.
Structure:
Particle Struct: Represents each particle with position, velocity, deformation gradient, and other physical properties.
Grid: A 2D grid storing velocity and mass information.
Simulation Loop: Advances the simulation by updating grid and particle states.
Rendering Loop: Draws the particles and the simulation domain using OpenGL.
Compilation:
Ensure that Eigen, GLFW, and GLEW are installed on your system.
Compile with the appropriate linker flags for OpenGL, GLFW, and GLEW.
Step-by-Step Implementation
1. Install Necessary Libraries
Before proceeding, make sure you have the following libraries installed:
Eigen: Header-only library for linear algebra.
GLFW: For window and context creation.
GLEW: For loading OpenGL extensions.
You can install them via package managers or download them from their official websites.
Below is the complete C++ code rewritten to use OpenGL for rendering and Eigen for linear algebra. The code replaces Taichi's functionalities with Eigen and GLFW/GLEW.
cpp
// mpm_simulation.cpp
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <Eigen/Dense>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
// Constants and typedefs
constexpr int n = 80; // Grid resolution (cells)
constexpr int window_size = 800;
constexpr float dt = 1e-4f;
constexpr float frame_dt = 1e-3f;
constexpr float dx = 1.0f / n;
constexpr float inv_dx = 1.0f / dx;
constexpr float particle_mass = 1.0f;
constexpr float vol = 1.0f;
constexpr float hardening = 10.0f;
constexpr float E = 1e4f;
constexpr float nu = 0.2f;
typedef Eigen::Vector2f Vec;
typedef Eigen::Matrix2f Mat;
// Material properties
const float mu_0 = E / (2.0f * (1.0f + nu));
const float lambda_0 = E * nu / ((1.0f + nu) * (1.0f - 2.0f * nu));
// Particle structure
struct Particle {
Vec x; // Position
Vec v; // Velocity
Mat F; // Deformation gradient
Mat C; // APIC affine velocity
float Jp; // Plastic deformation
int color;
Particle(const Vec& position, int c, const Vec& velocity = Vec::Zero())
: x(position), v(velocity), F(Mat::Identity()), C(Mat::Zero()), Jp(1.0f), color(c) {}
};
// Grid node structure: [vx, vy, mass]
typedef Eigen::Vector3f GridNode;
// Global variables
std::vector<Particle> particles;
GridNode grid[n + 1][n + 1];
// Utility functions
inline float clamp(float x, float a, float b) {
return std::max(a, std::min(b, x));
}
inline float determinant(const Mat& m) {
return m.determinant();
}
// Polar decomposition for 2x2 matrices
void polar_decomposition(const Mat& F, Mat& R, Mat& S) {
Eigen::JacobiSVD<Mat> svd(F, Eigen::ComputeFullU | Eigen::ComputeFullV);
R = svd.matrixU() * svd.matrixV().transpose();
S = svd.matrixV() * svd.singularValues().asDiagonal() * svd.matrixV().transpose();
}
// SVD for 2x2 matrices
bool svd(const Mat& F, Mat& U, Eigen::Vector2f& S_vals, Mat& V) {
Eigen::JacobiSVD<Mat> decomposition(F, Eigen::ComputeFullU | Eigen::ComputeFullV);
U = decomposition.matrixU();
V = decomposition.matrixV();
S_vals = decomposition.singularValues();
return true;
}
// Initialize particles within a square region around 'center'
void add_object(const Vec& center, int c) {
for (int i = 0; i < 500; ++i) { // 500 particles per object
// Random positions within a small square around the center
float rand_x = ((static_cast<float>(rand()) / RAND_MAX) * 2.0f - 1.0f) * 0.08f;
float rand_y = ((static_cast<float>(rand()) / RAND_MAX) * 2.0f - 1.0f) * 0.08f;
particles.emplace_back(Vec(center.x() + rand_x, center.y() + rand_y), c);
}
}
// Advance the simulation by time step dt
void advance(float dt_sim) {
// Reset grid
for (int i = 0; i <= n; ++i)
for (int j = 0; j <= n; ++j)
grid[i][j].setZero();
// P2G (Particles to Grid)
for (auto& p : particles) {
// Base node
Vec base_f = p.x * inv_dx - Vec(0.5f, 0.5f);
Eigen::Vector2i base_coord;
base_coord.x() = static_cast<int>(std::floor(base_f.x()));
base_coord.y() = static_cast<int>(std::floor(base_f.y()));
Vec fx = p.x * inv_dx - Vec(base_coord.x(), base_coord.y());
// Quadratic B-spline weights
Eigen::Vector3f w;
w[0] = 0.5f * (1.5f - fx.x()) * (1.5f - fx.x());
w[1] = 0.75f - (fx.x() - 1.0f) * (fx.x() - 1.0f);
w[2] = 0.5f * (fx.x() - 0.5f) * (fx.x() - 0.5f);
w << 0.5f * std::pow(1.5f - fx.x(), 2),
0.75f - std::pow(fx.x() - 1.0f, 2),
0.5f * std::pow(fx.x() - 0.5f, 2);
Vec wy;
wy << 0.5f * std::pow(1.5f - fx.y(), 2),
0.75f - std::pow(fx.y() - 1.0f, 2),
0.5f * std::pow(fx.y() - 0.5f, 2);
// Compute stress
float J = determinant(p.F);
Mat R, S;
polar_decomposition(p.F, R, S);
float e = std::exp(hardening * (1.0f - p.Jp));
float mu = mu_0 * e;
float lambda_mat = lambda_0 * e;
Mat stress = -4.0f * inv_dx * inv_dx * dt_sim * vol *
(2.0f * mu * (p.F - R) * p.F.transpose() + lambda_mat * (J - 1.0f) * Mat::Identity());
// Affine matrix
Mat affine = stress + p.mass * p.C;
// Scatter to grid
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
Eigen::Vector2i node = base_coord + Eigen::Vector2i(i, j);
if (node.x() < 0 || node.x() > n || node.y() < 0 || node.y() > n)
continue;
Vec dpos = Vec(i, j) - fx;
Eigen::Vector3f momentum = Eigen::Vector3f(p.v.x(), p.v.y(), particle_mass);
float weight = w[i] * wy[j];
grid[node.x()][node.y()] += Eigen::Vector3f(weight * momentum.x(), weight * momentum.y(),
weight * 1.0f) + Eigen::Vector3f(affine * dpos, 0.0f);
}
}
}
// Update grid velocities and apply gravity
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
auto& g = grid[i][j];
if (g.z() > 0.0f) {
// Normalize
g /= g.z();
// Gravity
g.y() += dt_sim * -200.0f;
// Boundary conditions
float boundary = 0.05f;
float x = static_cast<float>(i) / n;
float y = static_cast<float>(j) / n;
if (x < boundary || x > 1.0f - boundary || y > 1.0f - boundary) {
g.setZero();
}
if (y < boundary) {
g.y() = std::max(0.0f, g.y());
}
}
}
}
// Grid to Particle (G2P)
for (auto& p : particles) {
// Base node
Vec base_f = p.x * inv_dx - Vec(0.5f, 0.5f);
Eigen::Vector2i base_coord;
base_coord.x() = static_cast<int>(std::floor(base_f.x()));
base_coord.y() = static_cast<int>(std::floor(base_f.y()));
Vec fx = p.x * inv_dx - Vec(base_coord.x(), base_coord.y());
// Quadratic B-spline weights
Eigen::Vector3f w;
w << 0.5f * std::pow(1.5f - fx.x(), 2),
0.75f - std::pow(fx.x() - 1.0f, 2),
0.5f * std::pow(fx.x() - 0.5f, 2);
Eigen::Vector3f wy;
wy << 0.5f * std::pow(1.5f - fx.y(), 2),
0.75f - std::pow(fx.y() - 1.0f, 2),
0.5f * std::pow(fx.y() - 0.5f, 2);
p.v = Vec::Zero();
p.C = Mat::Zero();
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
Eigen::Vector2i node = base_coord + Eigen::Vector2i(i, j);
if (node.x() < 0 || node.x() > n || node.y() < 0 || node.y() > n)
continue;
float weight = w[i] * wy[j];
Vec grid_v(grid[node.x()][node.y()].x(), grid[node.x()][node.y()].y());
p.v += weight * grid_v;
// APIC affine velocity
Vec dpos = Vec(i, j) - fx;
p.C += 4.0f * inv_dx * weight * grid_v * dpos.transpose();
}
}
// Advection
p.x += dt_sim * p.v;
// Update deformation gradient
Mat F_new = (Mat::Identity() + dt_sim * p.C) * p.F;
// SVD for plasticity
Mat U, V;
Eigen::Vector2f S_vals;
svd(F_new, U, S_vals, V);
// Apply snow plasticity
for (int k = 0; k < 2; ++k) {
S_vals[k] = clamp(S_vals[k], 1.0f - 2.5e-2f, 1.0f + 7.5e-3f);
}
// Reconstruct F
Mat F = U * S_vals.asDiagonal() * V.transpose();
// Update plastic deformation
float oldJ = F_new.determinant();
float new_Jp = clamp(p.Jp * oldJ / F.determinant(), 0.6f, 20.0f);
p.Jp = new_Jp;
p.F = F;
}
}
// Shader sources
const char* vertexShaderSource = R"glsl(
#version 330 core
layout(location = 0) in vec2 position;
uniform mat4 projection;
void main()
{
gl_Position = projection * vec4(position, 0.0, 1.0);
gl_PointSize = 4.0;
}
)glsl";
const char* fragmentShaderSource = R"glsl(
#version 330 core
out vec4 FragColor;
uniform vec3 uColor;
void main()
{
FragColor = vec4(uColor, 1.0);
}
)glsl";
// Function to compile shaders and link program
GLuint createShaderProgram() {
// Vertex Shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// Check for compile errors
GLint success;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success) {
char infoLog[512];
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::VERTEX_SHADER_COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Fragment Shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader,1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// Check for compile errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if(!success){
char infoLog[512];
glGetShaderInfoLog(fragmentShader,512,NULL,infoLog);
std::cout << "ERROR::FRAGMENT_SHADER_COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Link Shaders
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram,vertexShader);
glAttachShader(shaderProgram,fragmentShader);
glLinkProgram(shaderProgram);
// Check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if(!success){
char infoLog[512];
glGetProgramInfoLog(shaderProgram,512,NULL,infoLog);
std::cout << "ERROR::SHADER_PROGRAM_LINKING_FAILED\n" << infoLog << std::endl;
}
// Cleanup
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}
int main() {
// Initialize GLFW
if (!glfwInit()) {
std::cerr << "Failed to initialize GLFW\n";
return -1;
}
// OpenGL version (3.3 Core)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create Window
GLFWwindow* window = glfwCreateWindow(window_size, window_size, "Real-time 2D MLS-MPM", NULL, NULL);
if (!window){
std::cerr << "Failed to create GLFW window\n";
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize GLEW (after making context current)
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if(err != GLEW_OK){
std::cerr << "Failed to initialize GLEW: "
<< glewGetErrorString(err) << "\n";
return -1;
}
// Compile and link shaders
GLuint shaderProgram = createShaderProgram();
// Generate VAO and VBO for particles
GLuint VAO, VBO;
glGenVertexArrays(1,&VAO);
glGenBuffers(1,&VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
// Allocate buffer without data initially
glBufferData(GL_ARRAY_BUFFER, particles.size() * sizeof(Vec), nullptr, GL_DYNAMIC_DRAW);
glVertexAttribPointer(0,2,GL_FLOAT, GL_FALSE, sizeof(Vec), (void*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindVertexArray(0);
// Projection matrix (Orthographic)
Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
projection(0,0) = 2.0f / 1.0f; // Assuming simulation space [0,1]x[0,1]
projection(1,1) = 2.0f / 1.0f;
projection(3,0) = -1.0f;
projection(3,1) = -1.0f;
// Add objects (particles)
add_object(Vec(0.55f, 0.45f), 0xED553B / 255.0f); // Color will be handled differently
add_object(Vec(0.45f, 0.65f), 0xF2B134 / 255.0f);
add_object(Vec(0.55f, 0.85f), 0x068587 / 255.0f);
// Main loop variables
int frame = 0;
float accumulated_time = 0.0f;
double lastTime = glfwGetTime();
// Enable blending for transparency (optional)
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Main Loop
while(!glfwWindowShouldClose(window)){
// Calculate delta time
double currentTime = glfwGetTime();
double deltaTime = currentTime - lastTime;
lastTime = currentTime;
accumulated_time += deltaTime;
// Advance simulation as many steps as needed
while (accumulated_time >= frame_dt) {
advance(frame_dt);
accumulated_time -= frame_dt;
}
// Render
glClearColor(0.07f, 0.18f, 0.25f, 1.0f); // Clear to dark blue
glClear(GL_COLOR_BUFFER_BIT);
// Update particle positions in VBO
std::vector<Vec> positions;
for(const auto& p : particles){
positions.emplace_back(p.x);
}
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(Vec), positions.data(), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Draw particles
glUseProgram(shaderProgram);
// Set projection matrix
GLuint projLoc = glGetUniformLocation(shaderProgram, "projection");
glUniformMatrix4fv(projLoc, 1, GL_FALSE, projection.data());
glBindVertexArray(VAO);
for(const auto& p : particles){
// Convert color from integer to normalized RGB
float r = ((p.color >> 16) & 0xFF) / 255.0f;
float g = ((p.color >> 8) & 0xFF) / 255.0f;
float b = (p.color & 0xFF) / 255.0f;
GLuint colorLoc = glGetUniformLocation(shaderProgram, "uColor");
glUniform3f(colorLoc, r, g, b);
// Draw the particle as a point
glDrawArrays(GL_POINTS, &p - &particles[0], 1);
}
glBindVertexArray(0);
glUseProgram(0);
// Swap buffers and poll events
glfwSwapBuffers(window);
glfwPollEvents();
// Optional: Save frames as images
// Uncomment and implement as needed
// if (frame % 1 == 0){
// // Implement image saving if required
// frame++;
// }
}
// Cleanup
glDeleteVertexArrays(1,&VAO);
glDeleteBuffers(1,&VBO);
glDeleteProgram(shaderProgram);
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
3. Explanation of the Rewritten Code
Libraries and Dependencies:
Eigen: Used for vector and matrix operations, replacing Taichi's Vector2, Matrix2, and Vector3 types.
GLFW: Handles window creation, context management, and input handling.
GLEW: Loads OpenGL functions. It's initialized after creating the OpenGL context with GLFW.
Data Structures:
Particle Struct: Contains position (x), velocity (v), deformation gradient (F), affine velocity (C), plastic deformation (Jp), and color. The color is stored as an integer (hex format) and later converted to RGB for rendering.
Grid: A 2D array (grid) of GridNode where each grid node stores velocity components (vx, vy) and mass.
Simulation (advance Function):
P2G (Particle to Grid): Transfers particle data to the grid, computing weights using quadratic B-spline kernels and updating grid velocities and masses.
Grid Operations: Normalizes grid velocities by mass, applies gravity, and enforces boundary conditions.
G2P (Grid to Particle): Transfers grid data back to particles, updating their velocities and positions. It also updates the deformation gradient (F) using affine velocity and applies plasticity via Singular Value Decomposition (SVD).
Rendering:
Shaders: Simple vertex and fragment shaders are used to render particles as colored points.
OpenGL Setup: Vertex Array Object (VAO) and Vertex Buffer Object (VBO) are created for rendering particles.
Projection Matrix: An orthographic projection is set up to map simulation coordinates [0,1]x[0,1] to OpenGL's normalized device coordinates.
Rendering Loop: Updates particle positions in the VBO and draws each particle with its respective color.
Main Loop:
Handles simulation advancement based on accumulated real time.
Renders the particles in each frame.
Processes window events and swaps buffers.
Assuming you have saved the code in mpm_simulation.cpp, compile it using g++ (or any C++ compiler) with the appropriate flags:
Note: The linking flags (-lglfw -lGLEW -lGL -ldl -lpthread) might vary based on your operating system. Ensure that GLFW and GLEW are correctly installed and linked.
4. Running the Simulation
After successful compilation, run the simulation:
bash
./mpm_simulation
A window titled "Real-time 2D MLS-MPM" should appear, displaying particles within a bounded domain. The particles should exhibit deformable behavior based on the MPM simulation.
Additional Notes
Performance Optimization: For larger simulations, consider optimizing data structures and minimizing OpenGL state changes.
Rendering Enhancements: You can enhance rendering by implementing particle textures, varying point sizes, or using instanced rendering.
User Interaction: Integrate user inputs (e.g., mouse interactions) using GLFW's input handling to manipulate particles or simulation parameters in real-time.
Saving Frames: If you wish to save simulation frames as images, consider integrating a library like stb_image_write.h or using OpenGL's glReadPixels to capture frame buffers.
Conclusion
The rewritten code replaces Taichi with OpenGL for rendering and Eigen for linear algebra, maintaining the core MPM simulation logic. By leveraging GLFW and GLEW, the simulation runs in real-time with visual feedback provided by OpenGL. You can further expand upon this foundation to add more features, optimizations, and visual enhancements as needed.