0542dd15b23cc0b3c021accdf7980258393893ef
[anneal.git] / src / edu / berkeley / qfat / Viewer.java
1 package edu.berkeley.qfat;
2 import java.io.*;
3 import java.nio.*;
4 import java.awt.*;
5 import java.awt.event.*;
6 import javax.swing.*;
7 import javax.media.opengl.*;
8 import javax.media.opengl.glu.*;
9 import com.sun.opengl.util.*;
10 import java.util.*;
11 import edu.berkeley.qfat.geom.*;
12 import edu.berkeley.qfat.geom.Point;
13
14 public class Viewer implements GLEventListener, MouseListener, MouseMotionListener, KeyListener, MouseWheelListener  {
15
16     public boolean force = false;
17     public Mesh tile = new Mesh(false);
18     public Mesh goal = new Mesh(false);
19     public Matrix[] transforms;
20     public Mesh.Vertex[] points;
21
22     public int whichNeighbor = 1;
23
24     public double temp;
25     public boolean tileon = true;
26     public boolean tilemeshon = false;
27     public boolean goalon = true;
28     public boolean anneal = false;
29     public boolean hillclimb = false;
30     public boolean neighbors = false;
31     public boolean neighborsWire = false;
32     public boolean neighborsWireOne = false;
33     public boolean errorNormals = false;
34
35     public int breaks = 0;
36     boolean alt = false;
37     boolean shift = false;
38     boolean control = false;
39
40     public Point getMouse() {
41         return new Point(mousex, glcanvas.getHeight()-mousey, 0);
42     }
43
44     public void mouseWheelMoved(MouseWheelEvent e) {
45         tz -= e.getWheelRotation();
46     }
47
48     public void keyTyped(KeyEvent e)  { }
49     public void keyPressed(KeyEvent e)  {
50         switch(e.getKeyCode()) {
51             case KeyEvent.VK_CONTROL: control = true; break;
52             case KeyEvent.VK_ALT: alt = true; break;
53             case KeyEvent.VK_SHIFT: shift = true; break;
54             case KeyEvent.VK_SPACE: breaks++; force = true; break;
55             case KeyEvent.VK_UP: temp = temp * 2; break;
56             case KeyEvent.VK_ENTER: temp = 10; break;
57             case KeyEvent.VK_LEFT: whichNeighbor--; break;
58             case KeyEvent.VK_RIGHT: whichNeighbor++; break;
59             case KeyEvent.VK_D: dump(); break;
60             case KeyEvent.VK_E: errorNormals = !errorNormals; break;
61             case KeyEvent.VK_A: hillclimb = false; anneal = !anneal; break;
62             case KeyEvent.VK_H: anneal = true; hillclimb = !hillclimb; break;
63             case KeyEvent.VK_N: neighbors = !neighbors; break;
64             case KeyEvent.VK_T: tileon = !tileon; break;
65             case KeyEvent.VK_G: goalon = !goalon; break;
66             case KeyEvent.VK_M: tilemeshon = !tilemeshon; break;
67         }
68     }
69     public synchronized void dump() {
70         try {
71         PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("dump.stl")));
72         pw.println("solid dump");
73         for(Mesh.T t : tile) {
74             Vec normal = t.norm();
75             pw.println("facet normal " + normal.x + " " + normal.y + " " + normal.z);
76             pw.println("  outer loop");
77             for(Mesh.Vertex v : new Mesh.Vertex[] { t.v1(), t.v2(), t.v3() }) {
78                 pw.println("    vertex " + v.p.x + " " + v.p.y + " " + v.p.z);
79             }
80             pw.println("  endloop");
81             pw.println("endfacet");
82         }
83         pw.println("endsolid dump");
84         pw.flush();
85         pw.close();
86         } catch (Exception e) { throw new RuntimeException(e); }
87     }
88     public void keyReleased(KeyEvent e) {
89         switch(e.getKeyCode()) {
90             case KeyEvent.VK_CONTROL: control = false; break;
91             case KeyEvent.VK_ALT: alt = false; break;
92             case KeyEvent.VK_SHIFT: shift = false; break;
93         }
94     }
95
96     public void mouseClicked(MouseEvent e) { }
97     public void mouseEntered(MouseEvent e) { }
98     public void mouseExited(MouseEvent e) { }
99     public void mousePressed(MouseEvent e) {
100         clickPoint = getMouse();
101         clickClosest = closest == null ? null : closest.getPoint();
102     }
103     public void mouseReleased(MouseEvent e) {
104         clickPoint = null;
105         clickClosest = null;
106     }
107
108     Point clickPoint = null;
109     Point clickClosest = null;
110
111     int mousex;
112     int mousey;
113     public void mouseMoved(MouseEvent e) {
114         mousex = e.getX();
115         mousey = e.getY();
116     }
117
118     float tx = 0;
119     float ty = 0;
120     float tz = 0;
121     float anglex = 0;
122     float angley = 0;
123     public void mouseDragged(MouseEvent e) {
124         if (shift) {
125             /*
126             tx += (mousex - e.getX())/(float)20;
127             ty += (mousey - e.getY())/(float)20;
128             */
129             if (closest != null && lastGL != null && projection != null && clickClosest != null) {
130                 synchronized(safeTriangles) {
131                     Vec d1 = projection.inverse().times(getMouse()).minus(projection.inverse().times(clickPoint));
132                     Vec delta = d1.plus(clickClosest).minus(closest.getPoint());
133                     //System.out.println(delta + " " + closest.getPoint());
134                     System.out.println(getMouse().minus(clickPoint));
135                     closest.move(Matrix.translate(delta), true);
136                 }
137             }
138         } else {
139             anglex -= mousex - e.getX();
140             angley += mousey - e.getY();
141         }
142         mousex = e.getX();
143         mousey = e.getY();
144     }
145
146     /**
147      * Take care of initialization here.
148      */
149     public void init(GLAutoDrawable gld) {
150         GL gl = gld.getGL();
151         gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
152         gl.glViewport(0, 0, 500, 300);
153         gl.glEnable(GL.GL_DEPTH_TEST);
154         gl.glClearDepth(1.0);
155         gl.glDepthFunc(GL.GL_LEQUAL);
156         gl.glMatrixMode(GL.GL_PROJECTION);
157         gl.glLoadIdentity();
158         gl.glMatrixMode(GL.GL_MODELVIEW);
159
160         float mat_specular[] = { 0.5f, 0.5f, 0.5f, 0.5f };
161         float mat_shininess[] = { 50.0f };
162         gl.glShadeModel(GL.GL_SMOOTH);
163         //gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_specular, 0);
164         //gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular, 0);  
165         //gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, new float[] { 0.3f, 0.3f, 0.3f, 0.3f }, 0);  
166         //gl.glMaterialfv(GL.GL_FRONT, GL.GL_SHININESS, mat_shininess, 0);
167         gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, new float[] { 1.0f,    4.0f,  -10.0f, 0.0f }, 0);
168         gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, new float[] { -10.0f, 10.0f,   10.0f, 0.0f }, 0);
169         gl.glLightfv(GL.GL_LIGHT2, GL.GL_POSITION, new float[] { 10.0f, -10.0f,   10.0f, 0.0f }, 0);
170         gl.glLightfv(GL.GL_LIGHT3, GL.GL_POSITION, new float[] { 10.0f,  10.0f,  -10.0f, 0.0f }, 0);
171         gl.glLightfv(GL.GL_LIGHT4, GL.GL_POSITION, new float[] { -10.0f, 10.0f,  -10.0f, 0.0f }, 0);
172         gl.glLightfv(GL.GL_LIGHT5, GL.GL_POSITION, new float[] { 10.0f, -10.0f,  -10.0f, 0.0f }, 0);
173         gl.glEnable(GL.GL_LIGHTING);
174         gl.glEnable(GL.GL_LIGHT0);
175         /*
176         gl.glEnable(GL.GL_LIGHT1);
177         gl.glEnable(GL.GL_LIGHT2);
178         gl.glEnable(GL.GL_LIGHT3);
179         gl.glEnable(GL.GL_LIGHT4);
180         gl.glEnable(GL.GL_LIGHT5);
181         */
182         gl.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE);
183         gl.glEnable(GL.GL_COLOR_MATERIAL);
184
185         display(gld);
186     }
187
188     private GL lastGL = null;
189
190     public int temps;
191     public int accepts;
192     public    int vertss;
193     public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { }
194     public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { }
195     public void display(GLAutoDrawable drawable) {
196
197         if (transforms==null) return;
198
199
200         glcanvas.setSize(f.getWidth(), f.getHeight() - 100);
201         Graphics2D g = (Graphics2D)f.getGraphics();
202         g.setColor(Color.black);
203         g.fillRect(0, f.getHeight()-100, f.getWidth(), f.getHeight());
204         g.setColor(Color.red);
205         int top = f.getHeight()-70;
206         g.drawString("temperature: "+temps, 10, 30+top);
207         g.drawString("acceptance: "+accepts, 10, 50+top);
208         g.drawString("vertices: "+vertss, 10, 70+top);
209         g.fillRect(140, 25+top, temps, 10);
210         g.fillRect(140, 45+top, accepts, 10);
211         g.fillRect(140, 65+top, vertss, 10);
212
213         GL gl = drawable.getGL();
214         lastGL = gl;
215         GLU glu = new GLU();
216         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
217         gl.glPointSize(5.0f);
218         gl.glLoadIdentity();
219         glu.gluPerspective(50, ((float)drawable.getWidth())/drawable.getHeight(), 0.5, 10);
220         glu.gluLookAt(0, 0, -((tz/10)-1), 0, 0, 0, 0, 1, 0);
221         gl.glRotatef(anglex/3, 0, 1, 0);
222         gl.glRotatef(-(angley/3), 1, 0, 0);
223
224
225         gl.glDisable(GL.GL_LIGHTING);
226         gl.glColor4f(1, 0, 0, 1);
227         gl.glBegin(GL.GL_LINES);
228         gl.glVertex3f(0,0,0);
229         gl.glVertex3f(.3f,0,0);
230         gl.glEnd();
231         gl.glColor4f(0, 1, 0, 1);
232         gl.glBegin(GL.GL_LINES);
233         gl.glVertex3f(0,0,0);
234         gl.glVertex3f(0,.3f,0);
235         gl.glEnd();
236         gl.glColor4f(0, 0, 1, 1);
237         gl.glBegin(GL.GL_LINES);
238         gl.glVertex3f(0,0,0);
239         gl.glVertex3f(0,0,.3f);
240         gl.glEnd();
241         gl.glEnable(GL.GL_LIGHTING);
242
243
244         gl.glBegin(GL.GL_TRIANGLES);
245         if (tileon)
246             draw(gl, true, safeTriangles);
247         if (tilemeshon)
248             draw(gl, false, safeTriangles);
249         gl.glEnd();
250
251         //draw(gl, false, tile);
252
253         gl.glBegin(GL.GL_TRIANGLES);
254         gl.glColor4f((float)0.5, (float)0.5, (float)0.5, (float)0.8);
255         if (goalon)
256             draw(gl, false, goal);
257         gl.glEnd();
258
259
260         int i = 0;
261         //gl.glDisable(GL.GL_DEPTH_TEST);
262         gl.glColor4f(1,1,1,1);
263         for(Matrix m : transforms) {
264             /*
265               gl.glColor4f(0, 1, 1, 1);
266               gl.glBegin(GL.GL_LINES);
267               new Point(0,0,0).glVertex(gl);
268               new Point(0,0,0).plus(m.getTranslationalComponent()).glVertex(gl);
269               gl.glEnd();
270               gl.glEnable(GL.GL_LIGHTING);
271             */
272             //if (v1.z==0 && v1.y==0) continue;
273             i++;
274             if (neighborsWireOne && i!=whichNeighbor) continue;
275             //if (i>4) continue;
276             /*
277             Point p = new Point(0, 0, 0).times(m);
278             Vec v = new Vec(p.x, p.y, p.z);
279             v = v.times((float)1.04);
280             gl.glTranslatef(v.x, v.y, v.z);
281             */
282             if (neighbors) draw(gl, true, safeTriangles, m);
283             else if (neighborsWire || neighborsWireOne) draw(gl, false, safeTriangles, m);
284             /*
285             gl.glTranslatef(-v.x, -v.y, -v.z);
286             */
287         }
288         //gl.glEnable(GL.GL_DEPTH_TEST);
289
290         gl.glDisable(GL.GL_LIGHTING);
291         gl.glShadeModel(GL.GL_FLAT);
292         if (closest != null) {
293             gl.glColor3f(1,1,1);
294             gl.glBegin(gl.GL_POINTS);
295             closest.getPoint().glVertex(gl);
296             gl.glEnd();
297             /*
298             Mesh.Vertex v2 = closest.hack(gl, getMouse());
299             gl.glBegin(GL.GL_LINES);        
300             closest.getPoint().glVertex(gl);                                                                                                  
301             if (v2 != null) v2.getPoint().glVertex(gl);
302             gl.glEnd();
303             */
304         }
305
306         gl.glFlush();
307         gl.glDrawBuffer(GL.GL_BACK);
308         gl.glReadBuffer( GL.GL_BACK );
309         gl.glPixelStorei( GL.GL_PACK_ALIGNMENT, 1);
310         gl.glFlush();
311         gl.glDisable(GL.GL_LIGHTING);
312         gl.glShadeModel(GL.GL_FLAT);
313
314         IntBuffer buf = ByteBuffer.allocateDirect(9*4*4).order(ByteOrder.nativeOrder()).asIntBuffer();
315         gl.glColor3f(0,0,0);
316         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
317         double dist = Double.MAX_VALUE;
318         if (clickPoint==null) closest = null;
319         projection = Matrix.getProjectionMatrix(gl);
320         synchronized(safeTriangles) {
321             for(Mesh.T t : safeTriangles)
322                 t.glTriangle(gl, null);
323             for(Mesh.Vertex v : tile.vertices()) {
324                 Point p = v.getPoint();
325                 gl.glColor3f(1,1,1);
326                 gl.glBegin(gl.GL_POINTS);
327                 p.glVertex(gl);
328                 gl.glEnd();
329                 gl.glFlush();
330
331                 Point projected = projection.times(p);
332                 int x = (int)projected.x;
333                 int y = (int)projected.y;
334                 gl.glReadPixels(x-1, y-1, 3, 3, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, buf);
335
336                 boolean vis = false;
337                 for(int j=0; j<9*4; j++) vis |= buf.get(j)!=0;
338                 v.visible = vis;
339                 if (vis) {
340                     gl.glColor3f(0,0,0);
341                     gl.glBegin(gl.GL_POINTS);
342                     p.glVertex(gl);
343                     gl.glEnd();
344                     y = glcanvas.getHeight()-y;
345                     if (clickPoint==null) {
346                         if (closest==null || (x-mousex)*(x-mousex)+(y-mousey)*(y-mousey) < dist) {
347                             dist = (x-mousex)*(x-mousex)+(y-mousey)*(y-mousey);
348                             closest = v;
349                         }
350                     }
351                 }
352             }
353         }
354         gl.glShadeModel(GL.GL_SMOOTH);
355         gl.glEnable(GL.GL_LIGHTING);
356         gl.glDrawBuffer(GL.GL_FRONT);
357     }
358     Mesh.Vertex closest = null;
359     Matrix projection = null;
360
361     protected HashSet<Mesh.T> safeTriangles = new HashSet<Mesh.T>();
362
363     private void draw(GL gl, boolean triangles, Iterable<Mesh.T> tris) { draw(gl, triangles, tris, Matrix.ONE); }
364     private void draw(GL gl, boolean triangles, Iterable<Mesh.T> tris, Matrix m) {
365         float red = 0.0f;
366         float green = 0.0f;
367         float blue = 0.0f;
368         synchronized(safeTriangles) {
369         for(Mesh.T t : tris) {
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             /*
378             if (triangles) switch(t.color) {
379                 case 0: gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3); break;
380                 case 1: gl.glColor4f((float)0.25, (float)0.75, (float)0.25, (float)0.3); break;
381                 case 2: gl.glColor4f((float)0.75, (float)0.25, (float)0.25, (float)0.3); break;
382                 case 3: gl.glColor4f((float)0.50, (float)0.50, (float)0.50, (float)0.3); break;
383                 case 4: gl.glColor4f((float)0.25, (float)0.75, (float)0.75, (float)0.3); break;
384                 case 5: gl.glColor4f((float)0.25, (float)0.75, (float)0.75, (float)0.3); break;
385                 case 6: gl.glColor4f((float)0.75, (float)0.25, (float)0.75, (float)0.3); break;
386             }
387             */
388             
389             gl.glColor4f((float)(0.25+(0.05*t.color)),
390                          (float)(0.25+(0.05*t.color)),
391                          (float)(0.75+(0.05*t.color)),
392                          (float)0.3); 
393             //if (t.v1().visible && t.v2().visible && t.v3().visible) continue;
394
395             /*
396             if (t.e1().pair.t==null) gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3);
397             else if (t.e2().pair.t==null) gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3);
398             else if (t.e3().pair.t==null) gl.glColor4f((float)0.25, (float)0.25, (float)0.75, (float)0.3);
399             else  gl.glColor4f((float)0.75, (float)0.25, (float)0.25, (float)0.3);
400             */
401             //gl.glBegin(GL.GL_LINES);
402
403             if (triangles) {
404                 t.glTriangle(gl, m);
405             } else {
406                 gl.glDisable(GL.GL_LIGHTING);
407                 gl.glBegin(GL.GL_LINES);
408                 gl.glColor3f(1, 1, 1);
409                 m.times(t.e1().p1.goodp).glVertex(gl);
410                 m.times(t.e1().p2.goodp).glVertex(gl);
411                 m.times(t.e2().p1.goodp).glVertex(gl);
412                 m.times(t.e2().p2.goodp).glVertex(gl);
413                 m.times(t.e3().p1.goodp).glVertex(gl);
414                 m.times(t.e3().p2.goodp).glVertex(gl);
415                 gl.glEnd();
416                 gl.glEnable(GL.GL_LIGHTING);
417             }
418
419             Point centroid = t.centroid();
420             gl.glBegin(GL.GL_LINES);
421             gl.glColor3f(1, 1, 1);
422
423             if (triangles && errorNormals)
424                 for(Mesh.Vertex p : new Mesh.Vertex[] { t.v1(), t.v2(), t.v3() }) {
425                     if (p.ok) {
426                         //gl.glDisable(GL.GL_LIGHTING);
427                         gl.glBegin(GL.GL_LINES);
428                         gl.glColor3f(1, 1, 1);
429                         p.p.glVertex(gl);
430                         p.p.plus(p.norm().times((float)p.error()*10)).glVertex(gl);
431                         //if (p.nearest_in_other_mesh != null) p.nearest_in_other_mesh.p.glVertex(gl);
432                         //tile.nearest(p).centroid().glVertex(gl);
433                         gl.glEnd();
434                         //gl.glEnable(GL.GL_LIGHTING);
435                     }
436                 }
437             gl.glEnd();
438             
439         }
440         }
441     }
442
443     private JFrame f;
444     private GLCanvas glcanvas;
445     public Viewer(JFrame f) {
446         this.f = f;
447
448         GLCapabilities glcaps = new GLCapabilities();
449         glcanvas = new GLCanvas();
450         glcanvas.addGLEventListener(this);
451         f.add(glcanvas, BorderLayout.CENTER);
452
453         glcanvas.addMouseListener(this);
454         glcanvas.addMouseMotionListener(this);
455         glcanvas.addMouseWheelListener(this);
456         glcanvas.addKeyListener(this);
457     }
458     public void repaint() {
459         glcanvas.repaint();
460     }
461 }