summaryrefslogtreecommitdiffstats
path: root/src/GeometryByReference/GeometryByReferenceNIOBuffer.java
blob: 0204b64da2ee4c986b3a612a9d42c6709b1be870 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/*
 * $RCSfile$
 *
 * Copyright (c) 2004 Sun Microsystems, Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistribution of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any
 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
 * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
 * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
 * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
 * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
 * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
 * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
 * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or
 * intended for use in the design, construction, operation or
 * maintenance of any nuclear facility.
 *
 * $Revision$
 * $Date$
 * $State$
 */

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import com.sun.j3d.utils.behaviors.vp.*;
import java.nio.*;

public class GeometryByReferenceNIOBuffer extends JApplet implements ActionListener,
GeometryUpdater {

    RenderingAttributes ra;
    ColoringAttributes ca;
    Material mat;			   
    Appearance app;			   
    JComboBox geomType;
    JComboBox vertexType;
    JComboBox colorType;
    JCheckBox transparency;
    JComboBox updates;
    Shape3D shape;			   
    TransparencyAttributes transp;
    int updateIndex = 0;
    int colorCount = 0, vertexCount = 0;
    int vertexIndex = 0, colorIndex = 0;
    
    GeometryArray tetraRegular, tetraStrip, tetraIndexed, tetraIndexedStrip;
    GeometryArray[] geoArrays = new GeometryArray[4];		   

    private static final float sqrt3 = (float) Math.sqrt(3.0);
    private static final float sqrt3_3 = sqrt3 / 3.0f;
    private static final float sqrt24_3 = (float) Math.sqrt(24.0) / 3.0f;

    private static final float ycenter = 0.5f * sqrt24_3;
    private static final float zcenter = -sqrt3_3;

    private static final Point3f p1 = 
	new Point3f(-1.0f, -ycenter, -zcenter);
    private static final Point3f p2 = 
	new Point3f(1.0f, -ycenter, -zcenter);
    private static final Point3f p3 =
	new Point3f(0.0f, -ycenter, -sqrt3 - zcenter);
    private static final Point3f p4 =
	new Point3f(0.0f, sqrt24_3 - ycenter, 0.0f);

    private static final float[] floatVerts = {
	p1.x, p1.y, p1.z, // front face
	p2.x, p2.y, p2.z,
	p4.x, p4.y, p4.z,
	
	p1.x, p1.y, p1.z,// left, back face
	p4.x, p4.y, p4.z,
	p3.x, p3.y, p3.z,
	
	p2.x, p2.y, p2.z,// right, back face
	p3.x, p3.y, p3.z,
	p4.x, p4.y, p4.z,
	
	p1.x, p1.y, p1.z,// bottom face
	p3.x, p3.y, p3.z,
	p2.x, p2.y, p2.z,
    };
    
    private static final Color3f c1 = new Color3f(0.6f, 0.0f, 0.0f);
    private static final Color3f c2 = new Color3f(0.0f, 0.6f, 0.0f);
    private static final Color3f c3 = new Color3f(0.0f, 0.6f, 0.6f);
    private static final Color3f c4 = new Color3f(0.6f, 0.6f, 0.0f);


    
    private static final float[] floatClrs = {
	c1.x, c1.y, c1.z, // front face
	c2.x, c2.y, c2.z,
	c4.x, c4.y, c4.z,
	
	c1.x, c1.y, c1.z,// left, back face
	c4.x, c4.y, c4.z,
	c3.x, c3.y, c3.z,
	
	c2.x, c2.y, c2.z,// right, back face
	c3.x, c3.y, c3.z,
	c4.x, c4.y, c4.z,
	
	c1.x, c1.y, c1.z,// bottom face
	c3.x, c3.y, c3.z,
	c2.x, c2.y, c2.z,
    };	

    private static final float[] indexedFloatVerts = {
	p1.x,p1.y,p1.z,
	p2.x,p2.y,p2.z,
	p3.x,p3.y,p3.z,
	p4.x,p4.y,p4.z,

    };

    
    private static final float[] indexedFloatClrs = {
	c1.x,c1.y,c1.z,
	c2.x,c2.y,c2.z,
	c3.x,c3.y,c3.z,
	c4.x,c4.y,c4.z,
    };
    
    private static final int[] indices = {0,1,3,0,3,2,1,2,3,0,2,1};
    private int[] stripVertexCounts = {3,3,3,3};

    private SimpleUniverse u;

    private J3DBuffer floatBufferCoord;
    private J3DBuffer floatBufferColor;
    private J3DBuffer indexedFloatBufferCoord;
    private J3DBuffer indexedFloatBufferColor;

    void createJ3DBuffers() {
	int i;
	ByteOrder order =  ByteOrder.nativeOrder();
	
	FloatBuffer coord = ByteBuffer.allocateDirect(36 * 4).order(order).asFloatBuffer();
	coord.put(floatVerts, 0, 36);
	floatBufferCoord = new J3DBuffer(coord);

	FloatBuffer color = ByteBuffer.allocateDirect(36 * 4).order(order).asFloatBuffer();
	color.put(floatClrs, 0, 36);
	floatBufferColor = new J3DBuffer(color);

	FloatBuffer indexedCoord = ByteBuffer.allocateDirect(12 * 4).order(order).asFloatBuffer();
	indexedCoord.put(indexedFloatVerts, 0, 12);
	indexedFloatBufferCoord = new J3DBuffer(indexedCoord);

	FloatBuffer indexedColor = ByteBuffer.allocateDirect(12 * 4).order(order).asFloatBuffer();
	indexedColor.put(indexedFloatClrs, 0, 12); 
	indexedFloatBufferColor = new J3DBuffer(indexedColor);
    }
    
    BranchGroup createSceneGraph() {
	BranchGroup objRoot = new BranchGroup();

	// Set up attributes to render lines
        app = new Appearance();

	transp = new TransparencyAttributes();
	transp.setTransparency(0.5f);
	transp.setCapability(TransparencyAttributes.ALLOW_MODE_WRITE);
	transp.setTransparencyMode(TransparencyAttributes.NONE);
	app.setTransparencyAttributes(transp);

	//create the direct nio buffer
	createJ3DBuffers();

	tetraRegular = createGeometry(1);
	tetraStrip =createGeometry(2);
	tetraIndexed = createGeometry(3);
	tetraIndexedStrip = createGeometry(4);

	geoArrays[0] = tetraRegular;
	geoArrays[1] = tetraStrip;
	geoArrays[2] = tetraIndexed;
	geoArrays[3] = tetraIndexedStrip;
	
	shape = new Shape3D(tetraRegular, app);
	shape.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE);
	shape.setCapability(Shape3D.ALLOW_GEOMETRY_READ);

	Transform3D t = new Transform3D();
	// move the object upwards
	t.set(new Vector3f(0.0f, 0.3f, 0.0f));

	// rotate the shape
	Transform3D temp = new Transform3D();
        temp.rotX(Math.PI/4.0d);
	t.mul(temp);
        temp.rotY(Math.PI/4.0d);
        t.mul(temp);
	
	// Shrink the object 
	t.setScale(0.6);

	TransformGroup trans = new TransformGroup(t);
	trans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
	trans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);

	objRoot.addChild(trans);
	trans.addChild(shape);

	BoundingSphere bounds =
	    new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0);

	// Set up the global lights
	Color3f lColor1 = new Color3f(0.7f, 0.7f, 0.7f);
	Vector3f lDir1  = new Vector3f(-1.0f, -1.0f, -1.0f);
	Color3f alColor = new Color3f(0.2f, 0.2f, 0.2f);

	AmbientLight aLgt = new AmbientLight(alColor);
	aLgt.setInfluencingBounds(bounds);
	DirectionalLight lgt1 = new DirectionalLight(lColor1, lDir1);
	lgt1.setInfluencingBounds(bounds);
	objRoot.addChild(aLgt);
	objRoot.addChild(lgt1);
	
	// Let Java 3D perform optimizations on this scene graph.
        objRoot.compile();

	return objRoot;
    }

    JPanel createGeometryByReferencePanel() {
	JPanel panel = new JPanel();
	panel.setBorder(new TitledBorder("Geometry Type"));

	String values[] = {"Array", "Strip", "Indexed", "IndexedStrip"};
	geomType = new JComboBox(values);
	geomType.setLightWeightPopupEnabled(false);
	geomType.addActionListener(this);
	geomType.setSelectedIndex(0);
	panel.add(new JLabel("Geometry Type")); 	
	panel.add(geomType);

	return panel;
    }

    JPanel createUpdatePanel() {

	JPanel panel = new JPanel();
	panel.setBorder(new TitledBorder("Other Attributes"));

	String updateComp[] = { "None","Geometry", "Color"};
	
	transparency = new JCheckBox("EnableTransparency", 
				      false);
	transparency.addActionListener(this);
	panel.add(transparency);


	updates = new JComboBox(updateComp);
	updates.setLightWeightPopupEnabled(false);
	updates.addActionListener(this);
	updates.setSelectedIndex(0);
	panel.add(new JLabel("UpdateData")); 	
	panel.add(updates);

	return panel;
    }

    

    public GeometryByReferenceNIOBuffer() {
    }

    public void init() {
	Container contentPane = getContentPane();
	
        Canvas3D c = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
        contentPane.add("Center", c);

        BranchGroup scene = createSceneGraph();
        // SimpleUniverse is a Convenience Utility class
        u = new SimpleUniverse(c);

	// add mouse behaviors to the viewingPlatform
	ViewingPlatform viewingPlatform = u.getViewingPlatform();

        // This will move the ViewPlatform back a bit so the
        // objects in the scene can be viewed.
        viewingPlatform.setNominalViewingTransform();
        u.addBranchGraph(scene);

	// add Orbit behavior to the ViewingPlatform
	OrbitBehavior orbit = new OrbitBehavior(c, OrbitBehavior.REVERSE_ALL);
	BoundingSphere bounds =
	    new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
	orbit.setSchedulingBounds(bounds);
	viewingPlatform.setViewPlatformBehavior(orbit);

	// Create GUI
	JPanel p = new JPanel();
	BoxLayout boxlayout = new BoxLayout(p, 
					    BoxLayout.Y_AXIS);
	p.add(createGeometryByReferencePanel());
	p.add(createUpdatePanel());
	p.setLayout(boxlayout);

	contentPane.add("South", p);
    }

    public void destroy() {
	u.cleanup();
    }

    public void actionPerformed(ActionEvent e) {
	Object target = e.getSource();
	GeometryArray geo;
	boolean setColor = false, setVertex = false;
	if (target == geomType) {
	    geo = geoArrays[geomType.getSelectedIndex()];
	    // Set everything to null, and set it later ..
	    geo.setColorRefBuffer(null);
	    geo.setCoordRefBuffer(null);
	    shape.setGeometry(geoArrays[geomType.getSelectedIndex()]);

	    setColor = true;
	    setVertex= true;

	    
	} 
	else if (target == transparency) {
	    if (transparency.isSelected()) {
		transp.setTransparencyMode(TransparencyAttributes.BLENDED);
	    }
	    else {
		transp.setTransparencyMode(TransparencyAttributes.NONE);
	    }

	}
	else if (target == updates) {
	    updateIndex = updates.getSelectedIndex();
	    if (updateIndex == 1) {
		System.out.println("Doing coordinate update");
		((GeometryArray)(shape.getGeometry())).updateData(this);
	    }
	    else if (updateIndex == 2) {
		System.out.println("Doing color update");
		((GeometryArray)(shape.getGeometry())).updateData(this);
	    }

	}

	if (setVertex) {
	    geo = (GeometryArray) shape.getGeometry();
	    if (geo instanceof IndexedGeometryArray)
		geo.setCoordRefBuffer(indexedFloatBufferCoord);
	    else
		geo.setCoordRefBuffer(floatBufferCoord);
	    
	}
	if (setColor) {
	    geo = (GeometryArray) shape.getGeometry();
	    if (geo instanceof IndexedGeometryArray)
		geo.setColorRefBuffer(indexedFloatBufferColor);
	    else
		geo.setColorRefBuffer(floatBufferColor);
	}
    }


			   
    public static void main(String[] args) {
	Frame frame = new MainFrame(new GeometryByReferenceNIOBuffer(), 800, 800);
    }
			   
    public GeometryArray createGeometry (int type) {
	GeometryArray tetra = null;
	if (type == 1) {
	    tetra =new TriangleArray(12, 
				     TriangleArray.COORDINATES|
				     TriangleArray.COLOR_3|
				     TriangleArray.BY_REFERENCE|
				     TriangleArray.USE_NIO_BUFFER);
	    
	    tetra.setCoordRefBuffer(floatBufferCoord);
	    tetra.setColorRefBuffer(floatBufferColor);

	}
	else if (type == 2) {
	    tetra = new TriangleStripArray(12,
					   TriangleStripArray.COORDINATES|
					   TriangleStripArray.COLOR_3|
					   TriangleStripArray.BY_REFERENCE|
					   TriangleStripArray.USE_NIO_BUFFER,
					   stripVertexCounts);
	    tetra.setCoordRefBuffer(floatBufferCoord);
	    tetra.setColorRefBuffer(floatBufferColor);
	    
	}
	else if (type == 3) { // Indexed Geometry
	    tetra = new IndexedTriangleArray(4,
					     IndexedTriangleArray.COORDINATES|
					     IndexedTriangleArray.COLOR_3|
					     IndexedTriangleArray.BY_REFERENCE|
					     IndexedTriangleArray.USE_NIO_BUFFER,
					     //IndexedTriangleStripArray.USE_COORD_INDEX_ONLY,
					     12);
	    tetra.setCoordRefBuffer(indexedFloatBufferCoord);
	    tetra.setColorRefBuffer(indexedFloatBufferColor);
	    ((IndexedTriangleArray)tetra).setCoordinateIndices(0, indices);
	    ((IndexedTriangleArray)tetra).setColorIndices(0, indices);
	}
	else if (type == 4) { // Indexed strip geometry
	    tetra = new IndexedTriangleStripArray(4,
						  IndexedTriangleStripArray.COORDINATES|
						  IndexedTriangleStripArray.COLOR_3|
						  IndexedTriangleStripArray.BY_REFERENCE|
						  IndexedTriangleStripArray.USE_NIO_BUFFER|
						  IndexedTriangleStripArray.USE_COORD_INDEX_ONLY,
						  12,
						  stripVertexCounts);
	    tetra.setCoordRefBuffer(indexedFloatBufferCoord);
	    tetra.setColorRefBuffer(indexedFloatBufferColor);
	    ((IndexedTriangleStripArray)tetra).setCoordinateIndices(0, indices);
	    /*
	    // Do not set color indices in UCIO mode
	    ((IndexedTriangleStripArray)tetra).setColorIndices(0, indices);
	    */
	}

	if (tetra != null)
	    tetra.setCapability(GeometryArray.ALLOW_REF_DATA_WRITE);
	return tetra;
    }
    
    public void updateData(Geometry geometry) {
	int i;
	float val;
	float val1;
	if (updateIndex == 1) { // geometry
	    // Translate the geometry by a small amount in x
	    vertexCount++;
	    if ((vertexCount &1) == 1)
		val = 0.2f;
	    else
		val = -0.2f;

	    FloatBuffer indexedCoord = (FloatBuffer)indexedFloatBufferCoord.getBuffer();
	    indexedCoord.rewind();
	    FloatBuffer coord = (FloatBuffer)floatBufferCoord.getBuffer();
	    coord.rewind();
	    
	    if (vertexIndex == 0) {
		// Do Indexed geometry
		for (i = 0; i < indexedCoord.limit(); i+=3) {
		    val1 = indexedCoord.get(i);
		    indexedCoord.put(i, val1 + val);
		}
		// Do non-indexed float geometry
		for (i = 0; i < coord.limit(); i+=3) {
		    val1 = coord.get(i);
		    coord.put(i, val1 + val);
		}
	    }
	}
	else if (updateIndex == 2) { // colors
	    colorCount++;
	    if ((colorCount & 1) == 1)
		val = 0.4f;
	    else
		val = -0.4f;

	    FloatBuffer indexedColors = (FloatBuffer)indexedFloatBufferColor.getBuffer();
	    indexedColors.rewind();
	    FloatBuffer colors = (FloatBuffer)floatBufferColor.getBuffer();
	    colors.rewind();
	    
	    if (colorIndex == 0) {
		// Do Indexed geometry
		for (i = 0; i < indexedColors.limit(); i+=3) {
		    indexedColors.put(i, indexedColors.get(i) + val);
		}
		// Do non-indexed float geometry
		for (i = 0; i < colors.limit(); i+=3) {
		    colors.put(i, colors.get(i) + val);
		}
	    }

	}

    }
}