Source Code Cross Referenced for ObjLoadCg.java in  » 6.0-JDK-Modules » java-3d » org » jdesktop » j3d » examples » cg_shader » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » 6.0 JDK Modules » java 3d » org.jdesktop.j3d.examples.cg_shader 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * $RCSfile: ObjLoadCg.java,v $
003:         *
004:         * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved.
005:         *
006:         * Redistribution and use in source and binary forms, with or without
007:         * modification, are permitted provided that the following conditions
008:         * are met:
009:         *
010:         * - Redistribution of source code must retain the above copyright
011:         *   notice, this list of conditions and the following disclaimer.
012:         *
013:         * - Redistribution in binary form must reproduce the above copyright
014:         *   notice, this list of conditions and the following disclaimer in
015:         *   the documentation and/or other materials provided with the
016:         *   distribution.
017:         *
018:         * Neither the name of Sun Microsystems, Inc. or the names of
019:         * contributors may be used to endorse or promote products derived
020:         * from this software without specific prior written permission.
021:         *
022:         * This software is provided "AS IS," without a warranty of any
023:         * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
024:         * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
025:         * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
026:         * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
027:         * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
028:         * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
029:         * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
030:         * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
031:         * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
032:         * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
033:         * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
034:         * POSSIBILITY OF SUCH DAMAGES.
035:         *
036:         * You acknowledge that this software is not designed, licensed or
037:         * intended for use in the design, construction, operation or
038:         * maintenance of any nuclear facility.
039:         *
040:         * $Revision: 1.6 $
041:         * $Date: 2007/02/09 17:21:32 $
042:         * $State: Exp $
043:         */
044:
045:        package org.jdesktop.j3d.examples.cg_shader;
046:
047:        import com.sun.j3d.loaders.objectfile.ObjectFile;
048:        import com.sun.j3d.loaders.ParsingErrorException;
049:        import com.sun.j3d.loaders.IncorrectFormatException;
050:        import com.sun.j3d.loaders.Scene;
051:        import com.sun.j3d.utils.shader.StringIO;
052:        import com.sun.j3d.utils.universe.*;
053:        import javax.media.j3d.*;
054:        import javax.vecmath.*;
055:        import java.awt.GraphicsConfiguration;
056:        import java.net.MalformedURLException;
057:        import java.util.Enumeration;
058:        import java.io.*;
059:        import java.net.URL;
060:        import com.sun.j3d.utils.behaviors.vp.*;
061:        import java.io.FileNotFoundException;
062:        import javax.swing.JOptionPane;
063:        import org.jdesktop.j3d.examples.Resources;
064:
065:        /**
066:         * Simple Java 3D example program to display an .obj object with shader programs.
067:         */
068:        public class ObjLoadCg extends javax.swing.JFrame {
069:
070:            private boolean spin = false;
071:            private boolean noTriangulate = false;
072:            private boolean noStripify = false;
073:            private double creaseAngle = 60.0;
074:            private URL filename = null;
075:
076:            private SimpleUniverse univ = null;
077:            private BranchGroup scene = null;
078:
079:            public BranchGroup createSceneGraph() {
080:                // Create the root of the branch graph
081:                BranchGroup objRoot = new BranchGroup();
082:
083:                // Create a Transformgroup to scale all objects so they
084:                // appear in the scene.
085:                TransformGroup objScale = new TransformGroup();
086:                Transform3D t3d = new Transform3D();
087:                t3d.setScale(0.7);
088:                objScale.setTransform(t3d);
089:                objRoot.addChild(objScale);
090:
091:                // Create the transform group node and initialize it to the
092:                // identity.  Enable the TRANSFORM_WRITE capability so that
093:                // our behavior code can modify it at runtime.  Add it to the
094:                // root of the subgraph.
095:                TransformGroup objTrans = new TransformGroup();
096:                objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
097:                objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
098:                objScale.addChild(objTrans);
099:
100:                int flags = ObjectFile.RESIZE;
101:                if (!noTriangulate)
102:                    flags |= ObjectFile.TRIANGULATE;
103:                if (!noStripify)
104:                    flags |= ObjectFile.STRIPIFY;
105:                ObjectFile f = new ObjectFile(flags, (float) (creaseAngle
106:                        * Math.PI / 180.0));
107:                Scene s = null;
108:                try {
109:                    s = f.load(filename);
110:                } catch (FileNotFoundException e) {
111:                    e.printStackTrace();
112:                    System.exit(1);
113:                } catch (ParsingErrorException e) {
114:                    e.printStackTrace();
115:                    System.exit(1);
116:                } catch (IncorrectFormatException e) {
117:                    e.printStackTrace();
118:                    System.exit(1);
119:                }
120:
121:                // Set vertex and fragment shader program for all Shape3D nodes in scene
122:                String vertexProgram = null;
123:                String fragmentProgram = null;
124:                try {
125:                    vertexProgram = StringIO.readFully(Resources
126:                            .getResource("cg_shader/simple_vp.cg"));
127:                    fragmentProgram = StringIO.readFully(Resources
128:                            .getResource("cg_shader/simple_fp.cg"));
129:                } catch (IOException e) {
130:                    e.printStackTrace();
131:                    System.exit(1);
132:                }
133:                Shader[] shaders = new Shader[2];
134:                shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_CG,
135:                        Shader.SHADER_TYPE_VERTEX, vertexProgram);
136:                shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_CG,
137:                        Shader.SHADER_TYPE_FRAGMENT, fragmentProgram);
138:                ShaderProgram shaderProgram = new CgShaderProgram();
139:                shaderProgram.setShaders(shaders);
140:                setShaderProgram(s.getSceneGroup(), shaderProgram);
141:
142:                objTrans.addChild(s.getSceneGroup());
143:
144:                BoundingSphere bounds = new BoundingSphere(new Point3d(0.0,
145:                        0.0, 0.0), 100.0);
146:
147:                if (spin) {
148:                    Transform3D yAxis = new Transform3D();
149:                    Alpha rotationAlpha = new Alpha(-1,
150:                            Alpha.INCREASING_ENABLE, 0, 0, 4000, 0, 0, 0, 0, 0);
151:
152:                    RotationInterpolator rotator = new RotationInterpolator(
153:                            rotationAlpha, objTrans, yAxis, 0.0f,
154:                            (float) Math.PI * 2.0f);
155:                    rotator.setSchedulingBounds(bounds);
156:                    objTrans.addChild(rotator);
157:                }
158:
159:                // Set up the background
160:                Color3f bgColor = new Color3f(0.05f, 0.05f, 0.5f);
161:                Background bgNode = new Background(bgColor);
162:                bgNode.setApplicationBounds(bounds);
163:                objRoot.addChild(bgNode);
164:
165:                return objRoot;
166:            }
167:
168:            private Canvas3D createUniverse() {
169:                // Get the preferred graphics configuration for the default screen
170:                GraphicsConfiguration config = SimpleUniverse
171:                        .getPreferredConfiguration();
172:
173:                // Create a Canvas3D using the preferred configuration
174:                Canvas3D canvas3d = new Canvas3D(config);
175:
176:                // Create simple universe with view branch
177:                univ = new SimpleUniverse(canvas3d);
178:                BoundingSphere bounds = new BoundingSphere(new Point3d(0.0,
179:                        0.0, 0.0), 100.0);
180:
181:                // Add a ShaderErrorListener
182:                univ.addShaderErrorListener(new ShaderErrorListener() {
183:                    public void errorOccurred(ShaderError error) {
184:                        error.printVerbose();
185:                        JOptionPane.showMessageDialog(ObjLoadCg.this , error
186:                                .toString(), "ShaderError",
187:                                JOptionPane.ERROR_MESSAGE);
188:                    }
189:                });
190:
191:                // add mouse behaviors to the ViewingPlatform
192:                ViewingPlatform viewingPlatform = univ.getViewingPlatform();
193:
194:                PlatformGeometry pg = new PlatformGeometry();
195:
196:                // Set up the ambient light
197:                Color3f ambientColor = new Color3f(0.1f, 0.1f, 0.1f);
198:                AmbientLight ambientLightNode = new AmbientLight(ambientColor);
199:                ambientLightNode.setInfluencingBounds(bounds);
200:                pg.addChild(ambientLightNode);
201:
202:                // Set up the directional lights
203:                Color3f light1Color = new Color3f(1.0f, 1.0f, 0.9f);
204:                Vector3f light1Direction = new Vector3f(1.0f, 1.0f, 1.0f);
205:                Color3f light2Color = new Color3f(1.0f, 1.0f, 1.0f);
206:                Vector3f light2Direction = new Vector3f(-1.0f, -1.0f, -1.0f);
207:
208:                DirectionalLight light1 = new DirectionalLight(light1Color,
209:                        light1Direction);
210:                light1.setInfluencingBounds(bounds);
211:                pg.addChild(light1);
212:
213:                DirectionalLight light2 = new DirectionalLight(light2Color,
214:                        light2Direction);
215:                light2.setInfluencingBounds(bounds);
216:                pg.addChild(light2);
217:
218:                viewingPlatform.setPlatformGeometry(pg);
219:
220:                // This will move the ViewPlatform back a bit so the
221:                // objects in the scene can be viewed.
222:                viewingPlatform.setNominalViewingTransform();
223:
224:                if (!spin) {
225:                    OrbitBehavior orbit = new OrbitBehavior(canvas3d,
226:                            OrbitBehavior.REVERSE_ALL);
227:                    orbit.setSchedulingBounds(bounds);
228:                    viewingPlatform.setViewPlatformBehavior(orbit);
229:                }
230:
231:                // Ensure at least 5 msec per frame (i.e., < 200Hz)
232:                univ.getViewer().getView().setMinimumFrameCycleTime(5);
233:
234:                return canvas3d;
235:            }
236:
237:            private void usage() {
238:                System.out
239:                        .println("Usage: java ObjLoadCg [-s] [-n] [-t] [-c degrees] <.obj file>");
240:                System.out.println("  -s Spin (no user interaction)");
241:                System.out.println("  -n No triangulation");
242:                System.out.println("  -t No stripification");
243:                System.out
244:                        .println("  -c Set crease angle for normal generation (default is 60 without");
245:                System.out
246:                        .println("     smoothing group info, otherwise 180 within smoothing groups)");
247:                System.exit(0);
248:            } // End of usage
249:
250:            // Set shader program for all nodes in specified branch graph
251:            private void setShaderProgram(BranchGroup g,
252:                    ShaderProgram shaderProgram) {
253:                ShaderAppearance myApp = new ShaderAppearance();
254:                Material mat = new Material();
255:                Texture2D tex2d = new Texture2D();
256:                myApp.setCapability(Appearance.ALLOW_TEXTURE_WRITE);
257:                myApp.setShaderProgram(shaderProgram);
258:                myApp.setMaterial(mat);
259:                myApp.setTexture(tex2d);
260:                setShaderProgram(g, myApp);
261:            }
262:
263:            // Recursively set shader program for all children of specified group
264:            private void setShaderProgram(Group g, ShaderAppearance myApp) {
265:
266:                Enumeration e = g.getAllChildren();
267:                while (e.hasMoreElements()) {
268:                    Node n = (Node) (e.nextElement());
269:                    if (n instanceof  Group) {
270:                        setShaderProgram((Group) n, myApp);
271:                    } else if (n instanceof  Shape3D) {
272:                        Shape3D s = (Shape3D) n;
273:                        s.setAppearance(myApp);
274:                    }
275:                }
276:            }
277:
278:            /**
279:             * Creates new form ObjLoadCg
280:             */
281:            public ObjLoadCg(String args[]) {
282:                if (args.length != 0) {
283:                    for (int i = 0; i < args.length; i++) {
284:                        if (args[i].startsWith("-")) {
285:                            if (args[i].equals("-s")) {
286:                                spin = true;
287:                            } else if (args[i].equals("-n")) {
288:                                noTriangulate = true;
289:                            } else if (args[i].equals("-t")) {
290:                                noStripify = true;
291:                            } else if (args[i].equals("-c")) {
292:                                if (i < args.length - 1) {
293:                                    creaseAngle = (new Double(args[++i]))
294:                                            .doubleValue();
295:                                } else
296:                                    usage();
297:                            } else {
298:                                usage();
299:                            }
300:                        } else {
301:                            try {
302:                                if ((args[i].indexOf("file:") == 0)
303:                                        || (args[i].indexOf("http") == 0)) {
304:                                    filename = new URL(args[i]);
305:                                } else if (args[i].charAt(0) != '/') {
306:                                    filename = new URL("file:./" + args[i]);
307:                                } else {
308:                                    filename = new URL("file:" + args[i]);
309:                                }
310:                            } catch (MalformedURLException e) {
311:                                System.err.println(e);
312:                                System.exit(1);
313:                            }
314:                        }
315:                    }
316:                }
317:
318:                if (filename == null) {
319:                    filename = Resources
320:                            .getResource("resources/geometry/galleon.obj");
321:                    if (filename == null) {
322:                        System.err
323:                                .println("resources/geometry/galleon.obj not found");
324:                        System.exit(1);
325:                    }
326:                }
327:
328:                // Initialize the GUI components
329:                initComponents();
330:
331:                // Create Canvas3D and SimpleUniverse; add canvas to drawing panel
332:                Canvas3D c = createUniverse();
333:                drawingPanel.add(c, java.awt.BorderLayout.CENTER);
334:
335:                // Create the content branch and add it to the universe
336:                scene = createSceneGraph();
337:                univ.addBranchGraph(scene);
338:            }
339:
340:            // ----------------------------------------------------------------
341:
342:            /** This method is called from within the constructor to
343:             * initialize the form.
344:             * WARNING: Do NOT modify this code. The content of this method is
345:             * always regenerated by the Form Editor.
346:             */
347:            // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
348:            private void initComponents() {
349:                drawingPanel = new javax.swing.JPanel();
350:
351:                setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
352:                setTitle("ObjLoadCg");
353:                drawingPanel.setLayout(new java.awt.BorderLayout());
354:
355:                drawingPanel.setPreferredSize(new java.awt.Dimension(700, 700));
356:                getContentPane()
357:                        .add(drawingPanel, java.awt.BorderLayout.CENTER);
358:
359:                pack();
360:            }// </editor-fold>//GEN-END:initComponents
361:
362:            /**
363:             * @param args the command line arguments
364:             */
365:            public static void main(final String args[]) {
366:                java.awt.EventQueue.invokeLater(new Runnable() {
367:                    public void run() {
368:                        ObjLoadCg objLoadCg = new ObjLoadCg(args);
369:                        objLoadCg.setVisible(true);
370:                    }
371:                });
372:            }
373:
374:            // Variables declaration - do not modify//GEN-BEGIN:variables
375:            private javax.swing.JPanel drawingPanel;
376:            // End of variables declaration//GEN-END:variables
377:
378:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.