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