Skip to content

Instantly share code, notes, and snippets.

@tylermorganwall
Created January 4, 2025 20:12
Show Gist options
  • Save tylermorganwall/d6d4904fdfec3dd1ed9fb93107b2e294 to your computer and use it in GitHub Desktop.
Save tylermorganwall/d6d4904fdfec3dd1ed9fb93107b2e294 to your computer and use it in GitHub Desktop.
3D beeswarm
#Function to generate random 3D points within a defined space
initialize_swarm = function(n=100, range=10) {
swarm = matrix(runif(n * 3, -range, range), ncol=3)
velocities = matrix(runif(n * 3, -0.1, 0.1), ncol=3)
list(swarm=swarm, velocities=velocities)
}
spinning_vector_field = function(swarm, spin_strength=0.05) {
#Swirl around the Z-axis
x = swarm[,1]
z = swarm[,3]
vx = -spin_strength * z
vz = spin_strength * x
vy = rep(0, length(x))
return(cbind(vx, vy, vz))
}
#Function to update swarm movement
update_swarm = function(swarm, velocities, center=c(0,0,0), cohesion=0.01, randomness=0.05,spin_strength=0.05) {
n = nrow(swarm)
#Compute attraction force to center
direction_to_center = center - swarm
swarm = swarm + cohesion * direction_to_center + velocities
# Add randomness
swarm = swarm + matrix(runif(n * 3, -randomness, randomness), ncol=3)
#Apply spinning vector field
spin_effect = spinning_vector_field(swarm, spin_strength)
swarm = swarm + spin_effect
#Update velocities with some damping
velocities = velocities * 0.95 + matrix(runif(n * 3, -0.02, 0.02), ncol=3)
#Update velocities with position vector
list(swarm=swarm, velocities=velocities)
}
library(rayvertex)
#Animate the swarm
single_bee = text3d_mesh("🐝", text_height = 50, angle=c(0,180,0))
set.seed(1)
n_points = 200
swarm_data = initialize_swarm(n=n_points)
for (i in 1:360) {
swarm_data = update_swarm(swarm_data$swarm, swarm_data$velocities)
swarm_scene = list()
for(j in seq_len(200)) {
swarm_scene[[j]] = single_bee |>
translate_mesh(position = swarm_data$swarm[j,]*40+c(555,555,555)/2)
}
swarm_scene |>
scene_from_list() |>
add_shape(generate_cornell_mesh()) |>
rasterize_scene(light_info=directional_light(direction = c(0.2,0.5,-1)),
filename = sprintf("beeswarm_plot%i.png",i), width=800, height=800)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment