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