Compute discrete Voronoi cell

This commit is contained in:
2024-02-21 19:12:07 -05:00
parent 0070094b94
commit fd61a4620f
5 changed files with 118 additions and 5 deletions

View File

@ -18,7 +18,7 @@ import sys
import math
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.graphics import Color,Line
from kivy.graphics import Color,Line,Rectangle
from point import Point
from polyomino import Cross,Disk
@ -127,6 +127,12 @@ class Painter(Widget):
if particle.grid>0:
self.draw_grid(particle.elements[0].pos,particle.grid)
# draw Voronoi cells
if self.lattice!=None:
for particle in self.particles:
if particle.voronoi>0:
self.draw_voronoi(particle)
for particle in self.particles:
particle.draw(self,alpha=0.5)
@ -160,6 +166,53 @@ class Painter(Widget):
Line(points=(0,self.pos_tocoord_y(yy),self.width,self.pos_tocoord_y(yy)))
yy-=mesh
# draw the discrete Voronoi cell of a particle
def draw_voronoi(self,particle):
# only works for lattices
if self.lattice!=None:
pos=particle.elements[0].pos
# loop over all points
xx=pos.x
while self.pos_tocoord_x(xx)<self.width:
yy=pos.y
while self.pos_tocoord_y(yy)<self.height:
if self.is_in_voronoi(xx,yy,particle):
self.draw_voronoi_site(xx,yy,particle.color)
yy+=self.lattice.spacing
yy=pos.y-self.lattice.spacing
while self.pos_tocoord_y(yy)>0:
if self.is_in_voronoi(xx,yy,particle):
self.draw_voronoi_site(xx,yy,particle.color)
yy-=self.lattice.spacing
xx+=self.lattice.spacing
xx=pos.x-self.lattice.spacing
while self.pos_tocoord_x(xx)>0:
yy=pos.y
while self.pos_tocoord_y(yy)<self.height:
if self.is_in_voronoi(xx,yy,particle):
self.draw_voronoi_site(xx,yy,particle.color)
yy+=self.lattice.spacing
yy=pos.y-self.lattice.spacing
while self.pos_tocoord_y(yy)>0:
if self.is_in_voronoi(xx,yy,particle):
self.draw_voronoi_site(xx,yy,particle.color)
yy-=self.lattice.spacing
xx-=self.lattice.spacing
# check whether a site is in the Voronoi cell of a particle
def is_in_voronoi(self,x,y,particle):
d_to_particle=self.lattice.distance_to_particle(x,y,particle)
# TODO: start with a particle that is close to x,y
for q in self.particles:
if q!=particle and self.lattice.distance_to_particle(x,y,q)<d_to_particle:
return False
return True
# draw a site in a Voronoi cell
def draw_voronoi_site(self,x,y,color):
Color(color[0],color[1],color[2],0.25)
#Color(1,0,0,alpha=0.25)
Rectangle(pos=(self.pos_tocoord_x(x-0.5),self.pos_tocoord_y(y-0.5)),size=(self.base_size,self.base_size))
# respond to keyboard
def on_key_down(self, keyboard, keycode, text, modifiers):
@ -465,6 +518,17 @@ class Painter(Widget):
# redraw
self.draw()
# set voronoi for selected particles
def set_voronoi(self, onoff):
for particle in self.selected:
if onoff==0:
particle.voronoi=False
elif onoff==1:
particle.voronoi=True
elif onoff==-1:
particle.voronoi=not particle.voronoi
# redraw
self.draw()
# write configuration to file
def write(self,file):