04083293bdef7ae75faea9946b6b294832b3a195
[anneal.git] / src / Main.java
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 import javax.media.opengl.*;
5 import javax.media.opengl.glu.*;
6 import java.util.*;
7
8 // FIXME: recenter goal to have centroid coincident with tile
9 // FIXME: re-orient goal (how?)
10 //        fish case: ensure that spinal axis of fish is the x-axis of the tile
11
12 public class Main implements GLEventListener, MouseListener, MouseMotionListener, KeyListener, MouseWheelListener {
13     
14     boolean alt = false;
15     boolean shift = false;
16     boolean control = false;
17
18     public void mouseWheelMoved(MouseWheelEvent e) {
19         tz -= e.getWheelRotation() ;
20     }
21
22     public void keyTyped(KeyEvent e)  { }
23     public void keyPressed(KeyEvent e)  {
24         switch(e.getKeyCode()) {
25             case KeyEvent.VK_CONTROL: control = true; break;
26             case KeyEvent.VK_ALT: alt = true; break;
27             case KeyEvent.VK_SHIFT: shift = true; break;
28         }
29     }
30     public void keyReleased(KeyEvent e) {
31         switch(e.getKeyCode()) {
32             case KeyEvent.VK_CONTROL: control = false; break;
33             case KeyEvent.VK_ALT: alt = false; break;
34             case KeyEvent.VK_SHIFT: shift = false; break;
35         }
36     }
37
38     public void mouseClicked(MouseEvent e) { }
39     public void mouseEntered(MouseEvent e) { }
40     public void mouseExited(MouseEvent e) { }
41     public void mousePressed(MouseEvent e) { }
42     public void mouseReleased(MouseEvent e) { }
43
44     int mousex;
45     int mousey;
46     public void mouseMoved(MouseEvent e) {
47         mousex = e.getX();
48         mousey = e.getY();
49     }
50
51     float tx = 0;
52     float ty = 0;
53     float tz = 0;
54     float anglex = 0;
55     float angley = 0;
56     public void mouseDragged(MouseEvent e) {
57         if (shift) {
58             tx += (mousex - e.getX())/(float)20;
59             ty += (mousey - e.getY())/(float)20;
60         } else {
61             anglex -= mousex - e.getX();
62             angley += mousey - e.getY();
63         }
64         mousex = e.getX();
65         mousey = e.getY();
66     }
67
68     private Geom tile = new Geom();
69     private Geom goal = new Geom();
70
71     /** magnification factor */
72     private static final float MAG = 1;
73
74     Geom.M[] translations;
75     Geom.V[] points;
76
77     public Main(StlFile stlf) {
78
79         for(int i=0; i<stlf.coordArray.length; i+=3) {
80             Geom.V p0 = goal.new P(stlf.coordArray[i+0].x * MAG, stlf.coordArray[i+0].y * MAG, stlf.coordArray[i+0].z * MAG).register();
81             Geom.V p1 = goal.new P(stlf.coordArray[i+1].x * MAG, stlf.coordArray[i+1].y * MAG, stlf.coordArray[i+1].z * MAG).register();
82             Geom.V p2 = goal.new P(stlf.coordArray[i+2].x * MAG, stlf.coordArray[i+2].y * MAG, stlf.coordArray[i+2].z * MAG).register();
83             Geom.Vec n  = goal.new Vec(stlf.normArray[i/3].x * MAG, stlf.normArray[i/3].y  * MAG, stlf.normArray[i/3].z * MAG);
84             Geom.T t  = goal.newT(p0, p1, p2, n);
85         }
86
87         // rotate to align major axis -- this probably needs to be done by a human.
88         goal.transform(goal.new M(goal.new Vec(0, 0, 1), (float)(Math.PI/2)));
89
90
91         float goal_width  = goal.diagonal().dot(goal.new Vec(1, 0, 0));
92         float goal_height = goal.diagonal().dot(goal.new Vec(0, 1, 0));
93         float goal_depth  = goal.diagonal().dot(goal.new Vec(0, 0, 1));
94
95         float width  = (float)0.6;
96         float height = (float)0.08;
97         float depth  = (float)0.3;
98         translations = new Geom.M[] {
99
100             tile.new M(tile.new Vec(-(width/2),  height,    0)),
101             tile.new M(tile.new Vec( (width/2),  height,    0)),
102             tile.new M(tile.new Vec(-(width/2), -height,    0)),
103             tile.new M(tile.new Vec( (width/2), -height,    0)),
104             tile.new M(tile.new Vec(-(width/2),       0,  depth)),
105             tile.new M(tile.new Vec( (width/2),       0,  depth)),
106             tile.new M(tile.new Vec(-(width/2),       0, -depth)),
107             tile.new M(tile.new Vec( (width/2),       0, -depth)),
108
109             tile.new M(tile.new Vec( width,           0,    0)),
110             tile.new M(tile.new Vec(-width,           0,    0)),
111             /*
112             tile.new M(tile.new Vec(     0,           0,    depth)),
113             tile.new M(tile.new Vec(     0,           0,   -depth)),
114             */
115         };
116
117
118         Geom.V ltf = tile.new P(-(width/2),  (height/2),  (depth/2)).register();
119         Geom.V mtf = tile.new P( 0.0,        (height/2),  (depth/2)).register();
120         Geom.V rtf = tile.new P( (width/2),  (height/2),  (depth/2)).register();
121         Geom.V ltn = tile.new P(-(width/2),  (height/2), -(depth/2)).register();
122         Geom.V mtn = tile.new P( 0.0,        (height/2), -(depth/2)).register();
123         Geom.V rtn = tile.new P( (width/2),  (height/2), -(depth/2)).register();
124         Geom.V lbf = tile.new P(-(width/2), -(height/2),  (depth/2)).register();
125         Geom.V mbf = tile.new P( 0.0,       -(height/2),  (depth/2)).register();
126         Geom.V rbf = tile.new P( (width/2), -(height/2),  (depth/2)).register();
127         Geom.V lbn = tile.new P(-(width/2), -(height/2), -(depth/2)).register();
128         Geom.V mbn = tile.new P( 0.0,       -(height/2), -(depth/2)).register();
129         Geom.V rbn = tile.new P( (width/2), -(height/2), -(depth/2)).register();
130         
131         points = new Geom.V[] {
132             ltf,
133             mtf,
134             rtf,
135             ltn,
136             mtn,
137             rtn,
138             lbf,
139             mbf,
140             rbf,
141             lbn,
142             mbn,
143             rbn
144         };
145
146
147         // top
148         tile.newT(ltf, mtf, mtn);
149         tile.newT(mtn, ltn, ltf);
150         tile.newT(mtf, rtf, rtn);
151         tile.newT(rtn, mtn, mtf);
152
153         // bottom (swap normals)
154         tile.newT(mbf, lbf, mbn);
155         tile.newT(lbn, mbn, lbf);
156         tile.newT(rbf, mbf, rbn);
157         tile.newT(mbn, rbn, mbf);
158         
159         // left
160         tile.newT(ltf, ltn, lbn);
161         tile.newT(lbn, lbf, ltf);
162
163         // right (swap normals)
164         tile.newT(rtn, rtf, rbn);
165         tile.newT(rbf, rbn, rtf);
166
167         // front
168         tile.newT(ltn, mtn, mbn);
169         tile.newT(ltn, mbn, lbn);
170         tile.newT(mtn, rtn, rbn);
171         tile.newT(mtn, rbn, mbn);
172
173         // back
174         tile.newT(mtf, ltf, mbf);
175         tile.newT(mbf, ltf, lbf);
176         tile.newT(rtf, mtf, rbf);
177         tile.newT(rbf, mtf, mbf);
178
179         for(Geom.M m : translations) {
180             for(Geom.T t1 : tile) {
181                 for(Geom.T t2 : tile) {
182                     if (t1==t2) continue;
183
184                     if ((t1.p1().p.times(m).minus(t2.p1().p).mag() < Geom.EPSILON) &&
185                         (t1.p2().p.times(m).minus(t2.p3().p).mag() < Geom.EPSILON) &&
186                         (t1.p3().p.times(m).minus(t2.p2().p).mag() < Geom.EPSILON)) {
187                         t1.e1().bind(t2.e3().pair);
188                         t1.e2().bind(t2.e2().pair);
189                         t1.e3().bind(t2.e1().pair);
190                     }
191                     if ((t1.p2().p.times(m).minus(t2.p1().p).mag() < Geom.EPSILON) &&
192                         (t1.p3().p.times(m).minus(t2.p3().p).mag() < Geom.EPSILON) &&
193                         (t1.p1().p.times(m).minus(t2.p2().p).mag() < Geom.EPSILON)) {
194                         t1.e2().bind(t2.e3().pair);
195                         t1.e3().bind(t2.e2().pair);
196                         t1.e1().bind(t2.e1().pair);
197                     }
198                     if ((t1.p3().p.times(m).minus(t2.p1().p).mag() < Geom.EPSILON) &&
199                         (t1.p1().p.times(m).minus(t2.p3().p).mag() < Geom.EPSILON) &&
200                         (t1.p2().p.times(m).minus(t2.p2().p).mag() < Geom.EPSILON)) {
201                         t1.e3().bind(t2.e3().pair);
202                         t1.e1().bind(t2.e2().pair);
203                         t1.e2().bind(t2.e1().pair);
204                     }
205                 }
206             }
207         }
208
209         //xGeom.V mid = lbf.getE(mbn).shatter();
210
211         // rescale to match volume
212         float factor = (float)Math.pow(tile.volume() / goal.volume(), 1.0/3.0);
213         goal.transform(goal.new M(factor));
214
215         // translate to match centroid
216         goal.transform(goal.new M(tile.centroid().minus(goal.centroid())));
217
218         //tx.e2.shatter();
219         //tx.e3.shatter();
220
221
222         tile.bind();
223
224         //mid.move(tile.new Vec((float)0,0,(float)-0.05));
225         //ltn.move(tile.new Vec((float)0,0,(float)-0.05));
226
227         //mtf.move(tile.new Vec(0, (float)-0.05, (float)0.05));
228
229
230         System.out.println("tile volume: " + tile.volume());
231         System.out.println("goal volume: " + goal.volume());
232
233         tile.score_against = goal;
234         goal.score_against = tile;
235     }
236         Random random = new Random();
237
238     public synchronized void breakit() {
239         if (verts > 300) return;
240         //double min = (tile.avgedge/tile.numedges)*(1+(4/(double)verts));
241         //if (verts>0 && tile.es.peek().length() < min) return;
242         PriorityQueue<Geom.E> es = new PriorityQueue<Geom.E>();
243         for(Geom.E e : tile.es) es.add(e);
244         for(int i=0; i<10; i++) {
245             Geom.E e = es.poll();
246             verts++;
247             System.out.println("shatter " + e);
248             e.shatter();
249             tile.unbind();
250             tile.bind();
251         }
252     }
253
254     public synchronized void rand(double temperature, Geom.V p) {
255         double tile_score = tile.score();
256         double goal_score = goal.score();
257         
258         p.rescore();
259         //if (p.watch==null) return;
260         float r1 = Math.abs(random.nextFloat());
261         r1 = r1 - (float)Math.floor(r1);
262         r1 = r1 * (float)0.01;
263         r1 = r1 - (float)0.005;
264         Geom.Vec v = p.watchback().p.minus(p.p).norm().times(r1);
265
266         //v = p.norm().times(v.dot(p.norm()));
267
268         boolean aspect = false;//(Math.abs(random.nextInt()) % 100) <= 2;
269         Geom.M old_tile_aspect = null;//goal.aspect;
270         boolean good = true;
271         if (aspect) {
272             /*
273             v = v.times(10);
274             tile.aspect = tile.new M(tile.aspect.a / (v.x+1), tile.aspect.f / (v.y+1), tile.aspect.k / (v.z+1));
275             tile.invaspect = tile.new M(1/tile.aspect.a, 1/tile.aspect.f, 1/tile.aspect.k);
276             goal.rescore();
277             tile.rescore();
278             */
279         } else {
280             good = p.move(v);
281         }
282         double new_tile_score = tile.score();
283         double new_goal_score = goal.score();
284         double tile_delta = new_tile_score - tile_score;
285         double goal_delta = new_goal_score - goal_score;
286         double delta = tile_delta + goal_delta;
287         double swapProbability = Math.exp((-1 * delta) / temperature);
288         //boolean doSwap = Math.random() < swapProbability;
289         boolean doSwap = good && (tile_delta <= 0 && goal_delta <= 0);
290         if (doSwap) {
291             tile_score = new_tile_score;
292             goal_score = new_goal_score;
293             //System.out.println("score: " + tile_score + " / " + goal_score);
294             if (aspect) System.out.println("aspect " + v);
295         } else {
296             if (aspect) {
297                 //tile.aspect = old_tile_aspect;
298                 //tile.invaspect = tile.new M(1/tile.aspect.a, 1/tile.aspect.f, 1/tile.aspect.k);
299                 goal.rescore();
300                 tile.rescore();
301             } else {
302                 p.move(v.times(-1));
303             }
304         }
305     }
306
307     /**
308      * Take care of initialization here.
309      */
310     public void init(GLAutoDrawable gld) {
311         GL gl = gld.getGL();
312         gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
313         gl.glViewport(0, 0, 500, 300);
314         gl.glEnable(GL.GL_DEPTH_TEST);
315         gl.glClearDepth(1.0);
316         gl.glDepthFunc(GL.GL_LEQUAL);
317         gl.glMatrixMode(GL.GL_PROJECTION);
318         gl.glLoadIdentity();
319         gl.glMatrixMode(GL.GL_MODELVIEW);
320         display(gld);
321     }
322
323     public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { }
324     public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { }
325     public synchronized void display(GLAutoDrawable drawable) {
326         GL gl = drawable.getGL();
327         GLU glu = new GLU();
328         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
329         gl.glPointSize(5.0f);
330         gl.glLoadIdentity();
331         glu.gluPerspective(50-tz, ((float)drawable.getWidth())/drawable.getHeight(), 0.5, 10);
332         glu.gluLookAt(0, 0, -1, 0, 0, 0, 0, 1, 0);
333         gl.glTranslatef(tx/(float)20, ty/(float)20, 0);
334         gl.glRotatef(anglex/3, 0, 1, 0);
335         gl.glRotatef(angley/3, 1, 0, 0);
336
337         gl.glBegin(GL.GL_TRIANGLES);
338         draw(gl, true, tile);
339         gl.glEnd();
340
341         gl.glBegin(GL.GL_TRIANGLES);
342         gl.glColor4f((float)0.5, (float)0.5, (float)0.5, (float)0.8);
343         //draw(gl, false, goal);
344         gl.glEnd();
345
346
347         int i = 0;
348         //gl.glDisable(GL.GL_DEPTH_TEST);
349         gl.glColor4f(1,1,1,1);
350         for(Geom.M m : translations) {
351             //if (v1.z==0 && v1.y==0) continue;
352             i++;
353             if (i != 1 /*&& i!=4*/) continue;
354             Geom.V p = tile.new P(0, 0, 0).times(m).register();
355             Geom.Vec v = tile.new Vec(p.p.x, p.p.y, p.p.z);
356             v = v.times((float)1.04);
357             gl.glTranslatef(v.x, v.y, v.z);
358             draw(gl, false, tile);
359             gl.glTranslatef(-v.x, -v.y, -v.z);
360         }
361         //gl.glEnable(GL.GL_DEPTH_TEST);
362     }
363
364     private synchronized void draw(GL gl, boolean triangles, Geom mesh) {
365         float red = 0.0f;
366         float green = 0.0f;
367         float blue = 0.0f;
368         for(Geom.T t : mesh) {
369             if (red < 0.15) red = 1.0f;
370             if (green < 0.15) green = 1.0f;
371             if (blue < 0.15) blue = 1.0f;
372             red -= .09f;
373             green -= .12f;
374             blue -= .15f;
375
376             if (triangles) switch(t.color) {
377                 case 0: gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3); break;
378                 case 1: gl.glColor4f((float)0.25, (float)0.75, (float)0.25, (float)0.3); break;
379                 case 2: gl.glColor4f((float)0.75, (float)0.25, (float)0.25, (float)0.3); break;
380                 case 3: gl.glColor4f((float)0.50, (float)0.50, (float)0.50, (float)0.3); break;
381             }
382             //gl.glBegin(GL.GL_LINES);
383
384             if (triangles) {
385                 gl.glBegin(GL.GL_TRIANGLES);
386                 t.glVertices(gl);
387                 gl.glEnd();
388             } else {
389                 gl.glBegin(GL.GL_LINES);
390                 t.e1().p1.p.glVertex(gl);
391                 t.e1().p2.p.glVertex(gl);
392                 t.e2().p1.p.glVertex(gl);
393                 t.e2().p2.p.glVertex(gl);
394                 t.e3().p1.p.glVertex(gl);
395                 t.e3().p2.p.glVertex(gl);
396                 gl.glEnd();
397             }
398
399             Geom.V centroid = t.centroid().register();
400             gl.glBegin(GL.GL_LINES);
401             gl.glColor3f(1, 1, 1);
402             /*
403             centroid.glVertex(gl);
404             centroid.plus(t.norm().times(t.diameter())).glVertex(gl);
405             */
406
407             if (mesh==goal)
408                 for(Geom.V p : new Geom.V[] { t.p1(), t.p2(), t.p3() }) {
409                     p.p.glVertex(gl);
410                     //p.plus(p.norm().times(p.score()*10)).glVertex(gl);
411                     p.partner().p.glVertex(gl);
412                     //tile.nearest(p).centroid().glVertex(gl);
413                 }
414
415             gl.glEnd();
416
417         }
418     }
419
420     public static void main(String[] s) throws Exception {
421         StlFile stlf = new StlFile();
422         stlf.load("simplefish.stl");
423         Main main = new Main(stlf);
424         Frame f = new Frame();
425         GLCapabilities glcaps = new GLCapabilities();
426         GLCanvas glcanvas = new GLCanvas();
427         glcanvas.addGLEventListener(main);
428         f.add(glcanvas, BorderLayout.CENTER);
429         f.pack();
430         f.show();
431         f.setSize(900, 900);
432         f.doLayout();
433
434         glcanvas.addMouseListener(main);
435         glcanvas.addMouseMotionListener(main);
436         glcanvas.addMouseWheelListener(main);
437         glcanvas.addKeyListener(main);
438
439         main.anneal(glcanvas);
440     }
441     public static int verts = 0;
442     public void anneal(GLCanvas glcanvas) throws Exception {
443         int verts = 0;
444         while(true) {
445             //Thread.sleep(10);
446             for(int i=0; i<1; i++) {
447                 glcanvas.repaint();
448                 //tile.ts.get(Math.abs(random.nextInt()) % tile.ts.size()).e1().p1
449                 for(Geom.T t : tile)
450                     for(Geom.V p : new Geom.V[] { t.p1(), t.p2(), t.p3() }) {
451                         rand(10,p);
452                     }
453                 goal.rescore();
454                 tile.rescore();
455             }
456             breakit();
457        }
458
459     }
460
461 }