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