## class kaleidoscope – the code

```class Kaleidoscope{
float periodX,periodY,side;
float rt32=sqrt(3.)/2;
float rt3=sqrt(3);
int choice;
final int RECTANGLE=0,THESQUARE=1,EQUITRIANGLE=2,RIGHTTRIANGLE=3;

Kaleidoscope(){
}
//---------------------------------------------------------------------------
//initialization and choice of kaleidoscope

//  rectangular kaleidoscope
void chooseRectangle(float cellWidth,float cellHeight){
periodX=2*cellWidth;
periodY=2*cellHeight;
choice=RECTANGLE;
}

//  square kaleidoscope with diagonal
void chooseSquare(float cellSize){
periodX=2*cellSize;
periodY=2*cellSize;
choice=THESQUARE;
}

void setTriangle(float sp){
side=sp;
periodX=3*side;
periodY=rt3*side;
}

//  equilateral triangle as kaleidoscope

void chooseEquiTriangle(float sp){
setTriangle(sp);
choice=EQUITRIANGLE;
}

//  triangle with right angle, 30- and 60 degrees angles as kaleidoscope

void chooseRightTriangle(float sp){
setTriangle(sp);
choice=RIGHTTRIANGLE;
}

//------------------------------------------------------------------
//  using the choosen kaleidoscope

Vector make(Vector v){
switch (choice){
case RECTANGLE: return rectangle(v);
case THESQUARE: return square(v);
case EQUITRIANGLE: return equiTriangle(v);
case RIGHTTRIANGLE: return rightTriangle(v);

}
return v;
}

//  periodicity, reduce vectors to the basic domain centered at the origin
//   -periodx/2 <v.x< periodX/2, v.y similarly
void reduce(Vector v){
float x=v.x/periodX;
v.x=periodX*(x-floor(x)-0.5);
x=v.y/periodY;
v.y=periodY*(x-floor(x)-0.5);
}

// simply vertical and horizontal mirrors
Vector rectangle(Vector v){
reduce(v);
v.x=abs(v.x);
v.y=abs(v.y);
return v;
}

// 3 mirrors, triangle with 90 degree and 45 degrees angle
// corresponds to a square with diagonal mirrors
Vector square(Vector v){
reduce(v);
v.x=abs(v.x);
v.y=abs(v.y);
if(v.x < v.y){
float h=v.x;
v.x=v.y;
v.y=h;
}
return v;
}

//  three mirrors forming an equilateral triangle, hexagonal symmetry
Vector equiTriangle(Vector v){
reduce(v);
v.y=abs(v.y);
if(v.x<0){
if(v.y>rt3*(v.x+side)){
v.x=v.x+0.5*periodX;
v.y=0.5*periodY-v.y;
}
}
else {
if(v.y>rt3*(side-v.x)){
v.x=v.x-0.5*periodX;
v.y=0.5*periodY-v.y;
}
}
if(v.y>rt3*v.x){
float h=-0.5*v.x+rt32*v.y;
v.y=abs(-0.5*v.y-rt32*v.x);
v.x=h;
}
return v;
}

//  three mirrors at angles of 90, 30 and 60 degrees
Vector rightTriangle(Vector v){
reduce(v);
v.y=abs(v.y);
v.x=abs(v.x);
if(v.y>rt3*(side-v.x)){
v.x=0.5*periodX-v.x;
v.y=0.5*periodY-v.y;
}
if(v.y>rt3*v.x){
float h=0.5*v.x+rt32*v.y;
v.y=0.5*v.y-rt32*v.x;
v.x=h;
return v;
}
if(rt3*v.y>v.x){
float h=0.5*v.x+rt32*v.y;
v.y=(rt32*v.x-0.5*v.y);
v.x=h;
}
return v;
}
}```
This entry was posted in Kaleidoscopes, programming and tagged , , . Bookmark the permalink.