final int MAX_SIZE = 128;
int currentSize = 96;
boolean[][][] grid = new boolean[MAX_SIZE][MAX_SIZE][MAX_SIZE];
boolean[][][] nextGrid = new boolean[MAX_SIZE][MAX_SIZE][MAX_SIZE];
int[][][] cellAge = new int[MAX_SIZE][MAX_SIZE][MAX_SIZE];
float rotX, rotY;
float zoom = 1.0; // Zoom level
int cellSize = 3;
boolean paused = false;
int framesPerGeneration = 5;
int frameCounter = 0;
PShader cellShader;
ThreadPoolExecutor executor;
// Rule set
int minSurvive = 4;
int maxSurvive = 5;
int birthCount = 5;
// Initialize cell age
for (int x = 0; x < MAX_SIZE; x++) {
for (int y = 0; y < MAX_SIZE; y++) {
for (int z = 0; z < MAX_SIZE; z++) {
cellAge[x][y][z] = 0;
}
}
}
// Prepare positions for instanced rendering
cellShader.set("cellSize", cellSize);
cellShader.set("gridSize", currentSize);
beginShape(POINTS);
for (int x = 0; x < currentSize; x++) {
for (int y = 0; y < currentSize; y++) {
for (int z = 0; z < currentSize; z++) {
if (grid[x][y][z]) {
vertex(x, y, z);
}
}
}
}
endShape();
resetShader();
popMatrix(); // End of 3D scene
// Reset transformations and coordinate system
camera();
// Disable depth test to ensure GUI is on top
hint(DISABLE_DEPTH_TEST);
// Draw GUI controls
cp5.draw();
// Re-enable depth test if you plan to draw more 3D content afterward
hint(ENABLE_DEPTH_TEST);
}
void updateGrid() {
CountDownLatch latch = new CountDownLatch(currentSize);
for (int x = 0; x < currentSize; x++) {
final int fx = x;
executor.execute(() -> {
for (int y = 0; y < currentSize; y++) {
for (int z = 0; z < currentSize; z++) {
int neighbors = countNeighbors(fx, y, z);
if (grid[fx][y][z]) {
nextGrid[fx][y][z] = (neighbors >= minSurvive && neighbors <= maxSurvive);
if (nextGrid[fx][y][z]) {
cellAge[fx][y][z] = min(cellAge[fx][y][z] + 1, 255);
}
} else {
nextGrid[fx][y][z] = (neighbors == birthCount);
if (nextGrid[fx][y][z]) {
cellAge[fx][y][z] = 0;
}
}
}
}
latch.countDown();
});
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean[][][] temp = grid;
grid = nextGrid;
nextGrid = temp;
}
Assistant
int countNeighbors(int x, int y, int z) {
int count = 0;
for (int dx = -1; dx <= 1; dx++) {
int nx = x + dx;
if (nx < 0 || nx >= currentSize) continue;
for (int dy = -1; dy <= 1; dy++) {
int ny = y + dy;
if (ny < 0 || ny >= currentSize) continue;
for (int dz = -1; dz <= 1; dz++) {
int nz = z + dz;
if (nz < 0 || nz >= currentSize) continue;
if (dx == 0 && dy == 0 && dz == 0) continue;
if (grid[nx][ny][nz]) count++;
}
}
}
return count;
}
void randomizeGrid() {
for (int x = 0; x < currentSize; x++) {
for (int y = 0; y < currentSize; y++) {
for (int z = 0; z < currentSize; z++) {
grid[x][y][z] = random(1) < 0.1;
cellAge[x][y][z] = 0;
}
}
}
}
void mouseDragged() {
// Prevent rotation when interacting with GUI
if (!cp5.isMouseOver()) {
rotY += (mouseX - pmouseX) * 0.01;
rotX += (mouseY - pmouseY) * 0.01;
}
}
// Add or remove cells by clicking
void mouseClicked() {
// Avoid interference when clicking on GUI
if (!cp5.isMouseOver()) {
PVector pos = screenToWorld(mouseX, mouseY);
int x = int(pos.x / cellSize);
int y = int(pos.y / cellSize);
int z = int(pos.z / cellSize);
if (x >= 0 && x < currentSize && y >= 0 && y < currentSize && z >= 0 && z < currentSize) {
grid[x][y][z] = !grid[x][y][z];
cellAge[x][y][z] = 0;
}
}
}
// Get inverse of modelview-projection matrix
PMatrix3D modelViewProj = new PMatrix3D();
modelViewProj.apply(p3d.projection);
modelViewProj.apply(p3d.modelview);
modelViewProj.invert();
// Map screen coordinates to NDC
float ndcX = map(screenX, 0, width, -1, 1);
float ndcY = map(screenY, 0, height, 1, -1); // Note the Y inversion
// Far and near points
PVector nearPoint = new PVector(ndcX, ndcY, -1);
PVector farPoint = new PVector(ndcX, ndcY, 1);
// Transform to world coordinates
PVector nearPointWorld = modelViewProj.mult(nearPoint, null);
PVector farPointWorld = modelViewProj.mult(farPoint, null);
// Direction from near to far point
PVector direction = PVector.sub(farPointWorld, nearPointWorld).normalize();
// Compute intersection with Z=0 plane
float t = -nearPointWorld.z / direction.z;
PVector point = PVector.add(nearPointWorld, PVector.mult(direction, t));
return point;
}
void keyPressed() {
if (key == ' ') paused = !paused;
if (key == 'r') randomizeGrid();
if (key == 's') saveState();
if (key == 'l') loadState();
}
void saveState() {
JSONArray json = new JSONArray();
for (int x = 0; x < currentSize; x++) {
for (int y = 0; y < currentSize; y++) {
for (int z = 0; z < currentSize; z++) {
if (grid[x][y][z]) {
JSONObject cell = new JSONObject();
cell.setInt("x", x);
cell.setInt("y", y);
cell.setInt("z", z);
cell.setInt("age", cellAge[x][y][z]);
json.append(cell);
}
}
}
}
saveJSONArray(json, "data/saved_state.json");
}
// Clear the current grid
for (int x = 0; x < currentSize; x++) {
for (int y = 0; y < currentSize; y++) {
for (int z = 0; z < currentSize; z++) {
grid[x][y][z] = false;
cellAge[x][y][z] = 0;
}
}
}
// Load saved cells
for (int i = 0; i < json.size(); i++) {
JSONObject cell = json.getJSONObject(i);
int x = cell.getInt("x");
int y = cell.getInt("y");
int z = cell.getInt("z");
int age = cell.getInt("age");
if (x < currentSize && y < currentSize && z < currentSize) {
grid[x][y][z] = true;
cellAge[x][y][z] = age;
}
}
}
void setupControls() {
int guiY = 20; // Starting Y position for controls
int guiSpacing = 30; // Spacing between controls
To convert your code into an isometric projection, you'll need to make some adjustments to your camera setup and transformations. Specifically, you'll switch from a perspective projection to an orthographic projection and apply rotations that simulate an isometric view.
Below is the modified code with the necessary changes. I will explain each change step by step.
1. Use Orthographic Projection
In your draw() function, you should set up an orthographic projection by calling ortho() before any transformations. This changes the projection from perspective (default in P3D) to orthographic, which is essential for an isometric view.
java
void draw() {
background(30);
// Set up orthographic projection
ortho();
// Rest of your drawing code...
}
2. Apply Isometric Rotations
For an isometric projection, you need to rotate your scene by specific angles:
Rotate around the X-axis by 35.264° (which is arctangent(1/sqrt(2))).
Rotate around the Y-axis by 45°.
You can set these angles directly in your setup() function and apply them during your transformations.
java
// Define the isometric rotation angles
float isoAngleX = radians(35.264); // Approximately 35.264 degrees
float isoAngleY = radians(45); // 45 degrees
void setup() {
size(1200, 800, P3D); // Increased canvas size
// Other setup code...
// Set rotations for isometric projection
rotX = isoAngleX;
rotY = isoAngleY;
}
Then, in your draw() function, apply these rotations after the scale and translations.
java
void draw() {
background(30);
// Set up orthographic projection
ortho();
// 3D transformations and rendering
pushMatrix(); // Start of 3D scene
lights();
translate(width / 2, height / 2, 0);
scale(zoom); // Apply zoom
// Apply isometric rotations
rotateX(rotX);
rotateY(rotY);
// Center the grid
translate(-currentSize * cellSize / 2, -currentSize * cellSize / 2, -currentSize * cellSize / 2);
// Rest of your rendering code...
}
3. Remove Interactive Rotation
Since an isometric projection has fixed angles, you should disable the interactive rotation to maintain the isometric view. You can comment out or remove the mouseDragged() function and any code that modifies rotX and rotY.
java
// Comment out or remove the mouseDragged function
// void mouseDragged() {
// // Prevent rotation when interacting with GUI
// if (!cp5.isMouseOver()) {
// rotY += (mouseX - pmouseX) * 0.01;
// rotX += (mouseY - pmouseY) * 0.01;
// }
// }
4. Adjust Translations
You might need to adjust translations to ensure your grid is centered correctly in the new projection. The existing translations should suffice, but verify if the grid appears centered and adjust if necessary.
Modified Code Snippet
Here is the modified version of your setup() and draw() functions with the changes applied:
java
// Define the isometric rotation angles
float isoAngleX = radians(35.264); // Approximately 35.264 degrees
float isoAngleY = radians(45); // 45 degrees
void setup() {
size(1200, 800, P3D); // Increased canvas size
// Initialize ControlP5
cp5 = new ControlP5(this);
setupControls();
randomizeGrid();
// Initialize thread pool
int processors = Runtime.getRuntime().availableProcessors();
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(processors);
// Load shader
cellShader = loadShader("cellFrag.glsl", "cellVert.glsl");
// Initialize cell age
for (int x = 0; x < MAX_SIZE; x++) {
for (int y = 0; y < MAX_SIZE; y++) {
for (int z = 0; z < MAX_SIZE; z++) {
cellAge[x][y][z] = 0;
}
}
}
// Create cell shape for instanced rendering
cellShape = createShape(BOX, cellSize);
cellShape.setStroke(false);
// Set rotations for isometric projection
rotX = isoAngleX;
rotY = isoAngleY;
}
void draw() {
background(30);
// Set up orthographic projection
ortho();
// 3D transformations and rendering
pushMatrix(); // Start of 3D scene
lights();
translate(width / 2, height / 2, 0);
scale(zoom); // Apply zoom
// Apply isometric rotations
rotateX(rotX);
rotateY(rotY);
// Center the grid
translate(-currentSize * cellSize / 2, -currentSize * cellSize / 2, -currentSize * cellSize / 2);
// Update grid
if (!paused && frameCounter % framesPerGeneration == 0) {
updateGrid();
}
frameCounter++;
// Use shader
shader(cellShader);
// Prepare positions for instanced rendering
cellShader.set("cellSize", cellSize);
cellShader.set("gridSize", currentSize);
beginShape(POINTS);
for (int x = 0; x < currentSize; x++) {
for (int y = 0; y < currentSize; y++) {
for (int z = 0; z < currentSize; z++) {
if (grid[x][y][z]) {
vertex(x, y, z);
}
}
}
}
endShape();
resetShader();
popMatrix(); // End of 3D scene
// Reset transformations and coordinate system
camera();
// Disable depth test to ensure GUI is on top
hint(DISABLE_DEPTH_TEST);
// Draw GUI controls
cp5.draw();
// Re-enable depth test if you plan to draw more 3D content afterward
hint(ENABLE_DEPTH_TEST);
}
5. Verify the Shader (Optional)
Your shader code doesn't need changes unless you're doing specific operations that assume a perspective projection. Since orthographic projection doesn't involve perspective scaling, any calculations dependent on depth or perspective may need adjustments. However, if your shader only colors the cells based on attributes like cellAge, it should work without modifications.
Summary of Changes
Set Orthographic Projection: Added ortho() in the draw() function.
Applied Isometric Rotations: Set rotX and rotY to isometric angles and applied them in the transformations.
Disabled Interactive Rotation: Commented out the mouseDragged() function to prevent changing the fixed isometric view.
With these changes, your scene should now render using an isometric projection, providing a clear and consistent view of your 3D grid without perspective distortion.
Note: Make sure to adjust any other parts of your code that might conflict with these changes, especially if there are other transformations or camera settings elsewhere in your code.