`
universsky
  • 浏览: 99473 次
文章分类
社区版块
存档分类
最新评论

Java图形学源代码 Draw3D

 
阅读更多

Java图形学源代码 Draw3D


Java图形学源代码 Draw3D - universsky@126 - 东海陈光剑的博客
Java图形学源代码 Draw3D - universsky@126 - 东海陈光剑的博客
 
/**
*
 * @author 东海陈光剑  2013-4-2上午1:29:59
* hello_3d.java
* chenguangjian iSword
* Email:universsky@126.com
* Blog: http://blog.sina.com.cn/universsky11/
 *      http://blog.csdn.com/universsky
*
*/
 
package isword;
 
import edu.princeton.cs.introcs.*;
 
 
/**
*
 * @author 东海陈光剑  2013-4-2上午1:29:59
* hello_3d.java
* chenguangjian iSword
* Email:universsky@126.com
* Blog: http://blog.sina.com.cn/universsky11/
 *       http://blog.csdn.com/universsky
*
*/
public class hello_3d
    {
 
        /**
         * @param args
         */
        public static void main(String[] args)
            {
                // Sets the scale of the drawing window
 
                StdDraw3D.setScale(-1,1);
 
                // Draws a sphere of radius 1 centered at (0,0,0)
                /**
                 * isword.StdDraw3D.sphere(double x, double y, double z, double r)
 
 
                    Draws a sphere at (x, y, z) with radius r.
 
                    Parameters:
                    x
                    y
                    z
                    r
                 */
                StdDraw3D.sphere(0, 0, 0, 1);
 
                // Renders to the drawing window
                StdDraw3D.finished();
 
 
            }
 
    }
 


Java图形学源代码 Draw3D - universsky@126 - 东海陈光剑的博客
/******************************************************************************
*StdDraw3D.java
*HaykMartirosyan
******************************************************************************
*3DDrawingLibrary
*
*StandardDraw3DisaJavalibrarywiththeexpressgoalofmakingit
*simpletocreatethree-dimensionalmodels,simulations,andgames.
*
*IntroductoryTutorial:
*http://introcs.cs.princeton.edu/java/stddraw3d
*
*Referencemanual:
*http://introcs.cs.princeton.edu/java/stddraw3d-manual.html
*
*NOTE:Thecodebelowisonlypartiallydocumented.Refertothe
*referencemanualforcompletedocumentation.
*
*****************************************************************************/
//NativeJavalibraries.
packageisword;
importjava.io.*;
importjava.net.*;
importjava.awt.*;
importjava.util.*;
importjavax.swing.*;
importjavax.swing.event.*;
importjava.text.*;
importjava.awt.geom.*;
importjava.awt.event.*;
importjava.awt.image.*;
importjavax.imageio.ImageIO;
//Java3Dlibraries.
importjavax.vecmath.*;
importjavax.media.j3d.*;
importcom.sun.j3d.utils.image.*;
importcom.sun.j3d.utils.geometry.*;
importcom.sun.j3d.utils.universe.*;
importcom.sun.j3d.utils.behaviors.vp.OrbitBehavior;
importcom.sun.j3d.utils.scenegraph.io.*;
importcom.sun.j3d.loaders.objectfile.ObjectFile;
importcom.sun.j3d.loaders.lw3d.Lw3dLoader;
importcom.sun.j3d.loaders.Loader;
/**
*StandardDraw3DisaJavalibrarywiththeexpressgoalofmakingit
*simpletocreatethree-dimensionalmodels,simulations,andgames.
*Hereisa<ahref="http://introcs.cs.princeton.edu/java/stddraw3d">StdDraw3Dtutorial</a>
*andthe
*<ahref="http://introcs.cs.princeton.edu/java/stddraw3d/stddraw3d-manual.html">StdDraw3Dreferencemanual</a>.
*/
publicfinalclassStdDraw3Dimplements
MouseListener,MouseMotionListener,MouseWheelListener,
KeyListener,ActionListener,ChangeListener,ComponentListener,WindowFocusListener
{
/****************************************************************
*GlobalVariables*
*****************************************************************/
/*Publicconstantvalues.*/
//-------------------------------------------------------------------------
//Presetcolors.
publicstaticfinalColorBLACK=Color.BLACK;
publicstaticfinalColorBLUE=Color.BLUE;
publicstaticfinalColorCYAN=Color.CYAN;
publicstaticfinalColorDARK_GRAY=Color.DARK_GRAY;
publicstaticfinalColorGRAY=Color.GRAY;
publicstaticfinalColorGREEN=Color.GREEN;
publicstaticfinalColorLIGHT_GRAY=Color.LIGHT_GRAY;
publicstaticfinalColorMAGENTA=Color.MAGENTA;
publicstaticfinalColorORANGE=Color.ORANGE;
publicstaticfinalColorPINK=Color.PINK;
publicstaticfinalColorRED=Color.RED;
publicstaticfinalColorWHITE=Color.WHITE;
publicstaticfinalColorYELLOW=Color.YELLOW;
//Cameramodes.
publicstaticfinalintORBIT_MODE=0;
publicstaticfinalintFPS_MODE=1;
publicstaticfinalintAIRPLANE_MODE=2;
publicstaticfinalintLOOK_MODE=3;
publicstaticfinalintFIXED_MODE=4;
publicstaticfinalintIMMERSIVE_MODE=5;
/*Globalvariables.*/
//-------------------------------------------------------------------------
//GUIComponents
privatestaticJFrameframe;
privatestaticPanelcanvasPanel;
privatestaticJMenuBarmenuBar;
privatestaticJMenufileMenu,cameraMenu,graphicsMenu;
privatestaticJMenuItemloadButton,saveButton,save3DButton,quitButton;
privatestaticJSpinnerfovSpinner;
privatestaticJRadioButtonMenuItem
orbitModeButton,fpsModeButton,airplaneModeButton,lookModeButton,fixedModeButton;
privatestaticJRadioButtonMenuItemperspectiveButton,parallelButton;
privatestaticJCheckBoxMenuItemantiAliasingButton;
privatestaticJSpinnernumDivSpinner;
privatestaticJCheckBoxinfoCheckBox;
//Scenegroups.
privatestaticSimpleUniverseuniverse;
privatestaticBranchGrouprootGroup,lightGroup,soundGroup,fogGroup,appearanceGroup;
privatestaticBranchGrouponscreenGroup,offscreenGroup;
privatestaticOrbitBehaviororbit;
privatestaticBackgroundbackground;
privatestaticGroupbgGroup;
privatestaticViewview;
//Drawingcanvas.
privatestaticCanvas3Dcanvas;
//Cameraobject
privatestaticCameracamera;
//BufferedImagesfor2Ddrawing
privatestaticBufferedImageoffscreenImage,onscreenImage;
privatestaticBufferedImageinfoImage;
//Canvasdimensions.
privatestaticintwidth;
privatestaticintheight;
privatestaticdoubleaspectRatio;
//Cameramode.
privatestaticintcameraMode;
//Centeroforbit
privatestaticPoint3dorbitCenter;
//Coordinatebounds.
privatestaticdoublemin,max,zoom;
//Currentbackgroundcolor.
privatestaticColorbgColor;
//Penproperties.
privatestaticColorpenColor;
privatestaticfloatpenRadius;
privatestaticFontfont;
//Keepstrackofscreenclearing.
privatestaticbooleanclear3D;
privatestaticbooleanclearOverlay;
privatestaticbooleaninfoDisplay;
//Numberoftrianglespershape.
privatestaticintnumDivisions;
//Mousestates.
privatestaticbooleanmouse1;
privatestaticbooleanmouse2;
privatestaticbooleanmouse3;
privatestaticdoublemouseX;
privatestaticdoublemouseY;
//Keyboardstates.
privatestaticTreeSet<Integer>keysDown=newTreeSet<Integer>();
privatestaticLinkedList<Character>keysTyped=newLinkedList<Character>();
//Foreventsynchronization.
privatestaticObjectmouseLock=newObject();
privatestaticObjectkeyLock=newObject();
//Helpertoseewheninitializationcomplete
privatestaticbooleaninitialized=false;
privatestaticbooleanfullscreen=false;
privatestaticbooleanimmersive=false;
//Pausestherenderer
privatestaticbooleanshowedOnce=true;
privatestaticbooleanrenderedOnce=false;
/*Finalvariablesfordefaultvalues.*/
//-------------------------------------------------------------------------
//Defaultsquarecanvasdimensioninpixels.
privatestaticfinalintDEFAULT_SIZE=600;
//Defaultboundariesofcanvasscale.
privatestaticfinaldoubleDEFAULT_MIN=0.0;
privatestaticfinaldoubleDEFAULT_MAX=1.0;
//Defaultcameramode
privatestaticfinalintDEFAULT_CAMERA_MODE=ORBIT_MODE;
//Defaultfieldofvisionforperspectiveprojection.
privatestaticfinaldoubleDEFAULT_FOV=0.9;
privatestaticfinalintDEFAULT_NUM_DIVISIONS=100;
//Defaultclippingdistancesforrendering.
privatestaticfinaldoubleDEFAULT_FRONT_CLIP=0.01;
privatestaticfinaldoubleDEFAULT_BACK_CLIP=10;
//Defaultpensettings.
privatestaticfinalFontDEFAULT_FONT=newFont("Arial",Font.PLAIN,16);
privatestaticfinaldoubleDEFAULT_PEN_RADIUS=0.002;
privatestaticfinalColorDEFAULT_PEN_COLOR=StdDraw3D.WHITE;
//Defaultbackgroundcolor.
privatestaticfinalColorDEFAULT_BGCOLOR=StdDraw3D.BLACK;
//ScalesthesizeofText3D.
privatestaticfinaldoubleTEXT3D_SHRINK_FACTOR=0.005;
privatestaticfinaldoubleTEXT3D_DEPTH=1.5;
//Defaultshapeflags.
privatestaticfinalintPRIMFLAGS=
Primitive.GENERATE_NORMALS+Primitive.GENERATE_TEXTURE_COORDS;
//Infiniteboundingsphere.
privatestaticfinalBoundingSphereINFINITE_BOUNDS=
newBoundingSphere(newPoint3d(0.0,0.0,0.0),1e100);
//Axisvectors.
privatestaticfinalVector3DxAxis=newVector3D(1,0,0);
privatestaticfinalVector3DyAxis=newVector3D(0,1,0);
privatestaticfinalVector3DzAxis=newVector3D(0,0,1);
/*Housekeeping.*/
//-------------------------------------------------------------------------
//Singletonforcallbacks-avoidsgenerationofextra.classfiles.
privatestaticStdDraw3Dstd=newStdDraw3D();
//Blankconstructor.
privateStdDraw3D(){}
//Staticinitializer.
static{
//System.setProperty("j3d.rend","ogl");
System.setProperty("j3d.audiodevice","com.sun.j3d.audioengines.javasound.JavaSoundMixer");
setCanvasSize(DEFAULT_SIZE,DEFAULT_SIZE);
}
/****************************************************************
*InitializationMethods*
*****************************************************************/
/**
*Initializesthe3Dengine.
*/
privatestaticvoidinitialize(){
numDivisions=DEFAULT_NUM_DIVISIONS;
onscreenImage=createBufferedImage();
offscreenImage=createBufferedImage();
infoImage=createBufferedImage();
initializeCanvas();
if(frame!=null)frame.setVisible(false);
frame=newJFrame();
frame.setVisible(false);
frame.setResizable(fullscreen);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("StandardDraw3D");
frame.add(canvasPanel);
frame.setJMenuBar(createMenuBar());
frame.addComponentListener(std);
frame.addWindowFocusListener(std);
//frame.getContentPane().setCursor(newCursor(Cursor.MOVE_CURSOR));
frame.pack();
rootGroup=createBranchGroup();
lightGroup=createBranchGroup();
bgGroup=createBranchGroup();
soundGroup=createBranchGroup();
fogGroup=createBranchGroup();
appearanceGroup=createBranchGroup();
onscreenGroup=createBranchGroup();
offscreenGroup=createBranchGroup();
rootGroup.addChild(onscreenGroup);
rootGroup.addChild(lightGroup);
rootGroup.addChild(bgGroup);
rootGroup.addChild(soundGroup);
rootGroup.addChild(fogGroup);
rootGroup.addChild(appearanceGroup);
universe=newSimpleUniverse(canvas,2);
universe.addBranchGraph(rootGroup);
setDefaultLight();
Viewerviewer=universe.getViewer();
viewer.createAudioDevice();
view=viewer.getView();
view.setTransparencySortingPolicy(View.TRANSPARENCY_SORT_GEOMETRY);
view.setScreenScalePolicy(View.SCALE_EXPLICIT);
view.setLocalEyeLightingEnable(true);
setAntiAliasing(false);
//view.setMinimumFrameCycleTime(longminimumTime);
ViewingPlatformviewingPlatform=universe.getViewingPlatform();
viewingPlatform.setNominalViewingTransform();
orbit=newOrbitBehavior(canvas,OrbitBehavior.REVERSE_ALL^OrbitBehavior.STOP_ZOOM);
BoundingSpherebounds=INFINITE_BOUNDS;
orbit.setMinRadius(0);
orbit.setSchedulingBounds(bounds);
setOrbitCenter(newPoint3d(0,0,0));
viewingPlatform.setViewPlatformBehavior(orbit);
TransformGroupcameraTG=viewingPlatform.getViewPlatformTransform();
Transform3DcameraTrans=newTransform3D();
cameraTG.getTransform(cameraTrans);
viewingPlatform.detach();
cameraTG.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
cameraTG.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
camera=newCamera(cameraTG);
universe.addBranchGraph(viewingPlatform);
setPerspectiveProjection();
setCameraMode();
setPenColor();
setPenRadius();
setFont();
setScale();
setInfoDisplay(true);
setBackground(DEFAULT_BGCOLOR);
frame.setVisible(true);
frame.toFront();
frame.setState(Frame.NORMAL);
initialized=true;
}
/**
*AddsaCanvas3DtothegivenPanelp.
*/
privatestaticvoidinitializeCanvas(){
Panelp=newPanel();
GridBagLayoutgl=newGridBagLayout();
GridBagConstraintsgbc=newGridBagConstraints();
p.setLayout(gl);
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=5;
gbc.gridheight=5;
GraphicsConfigurationconfig=SimpleUniverse.getPreferredConfiguration();
canvas=newCanvas3D(config){
publicvoidpreRender(){
if(camera.pair!=null){
camera.setPosition(camera.pair.getPosition());
camera.setOrientation(camera.pair.getOrientation());
}
}
publicvoidpostRender(){
J3DGraphics2Dgraphics=this.getGraphics2D();
graphics.drawRenderedImage(onscreenImage,newAffineTransform());
if(infoDisplay){
graphics.drawRenderedImage(infoImage,newAffineTransform());
}
graphics.flush(false);
/*while(!showedOnce){
try{Thread.currentThread().sleep(0);}
catch(InterruptedExceptione){System.out.println("Errorsleeping");}
}
showedOnce=false;*/
Thread.yield();
}
/*publicvoidpostSwap(){
while(!showedOnce){
try{Thread.currentThread().sleep(5);}
catch(InterruptedExceptione){System.out.println("Errorsleeping");}
}
//if(!showedOnce){
//try{Thread.currentThread().sleep(30);}
//catch(InterruptedExceptione){System.out.println("Errorsleeping");}
//}
//StdOut.println("showedonceisfalse,renderedonce");
showedOnce=false;
//renderedOnce=true;
//Thread.yield();
}*/
};
canvas.addKeyListener(std);
canvas.addMouseListener(std);
canvas.addMouseMotionListener(std);
canvas.addMouseWheelListener(std);
canvas.setSize(width,height);
p.add(canvas,gbc);
canvasPanel=p;
//canvas.stopRenderer();
}
/**
*CreatesamenubarasabasicGUI.
*
*@returnThecreatedJMenuBar.
*/
privatestaticJMenuBarcreateMenuBar(){
menuBar=newJMenuBar();
fileMenu=newJMenu("File");
menuBar.add(fileMenu);
loadButton=newJMenuItem("Load3DModel..");
loadButton.addActionListener(std);
loadButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
fileMenu.add(loadButton);
saveButton=newJMenuItem("SaveImage...");
saveButton.addActionListener(std);
saveButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
fileMenu.add(saveButton);
save3DButton=newJMenuItem("Export3DScene...");
save3DButton.addActionListener(std);
save3DButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
//fileMenu.add(save3DButton);
fileMenu.addSeparator();
quitButton=newJMenuItem("Quit...");
quitButton.addActionListener(std);
quitButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
fileMenu.add(quitButton);
cameraMenu=newJMenu("Camera");
menuBar.add(cameraMenu);
JLabelcameraLabel=newJLabel("CameraMode");
cameraLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
cameraLabel.setForeground(GRAY);
cameraMenu.add(cameraLabel);
cameraMenu.addSeparator();
ButtonGroupcameraButtonGroup=newButtonGroup();
orbitModeButton
=newJRadioButtonMenuItem("OrbitMode");
orbitModeButton.setSelected(true);
cameraButtonGroup.add(orbitModeButton);
cameraMenu.add(orbitModeButton);
orbitModeButton.addActionListener(std);
orbitModeButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
fpsModeButton
=newJRadioButtonMenuItem("First-PersonMode");
cameraButtonGroup.add(fpsModeButton);
cameraMenu.add(fpsModeButton);
fpsModeButton.addActionListener(std);
fpsModeButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
airplaneModeButton
=newJRadioButtonMenuItem("AirplaneMode");
cameraButtonGroup.add(airplaneModeButton);
cameraMenu.add(airplaneModeButton);
airplaneModeButton.addActionListener(std);
airplaneModeButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
lookModeButton
=newJRadioButtonMenuItem("LookMode");
cameraButtonGroup.add(lookModeButton);
cameraMenu.add(lookModeButton);
lookModeButton.addActionListener(std);
lookModeButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
fixedModeButton
=newJRadioButtonMenuItem("FixedMode");
cameraButtonGroup.add(fixedModeButton);
cameraMenu.add(fixedModeButton);
fixedModeButton.addActionListener(std);
fixedModeButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
cameraMenu.addSeparator();
JLabelprojectionLabel=newJLabel("ProjectionMode");
projectionLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
projectionLabel.setForeground(GRAY);
cameraMenu.add(projectionLabel);
cameraMenu.addSeparator();
SpinnerNumberModelsnm=newSpinnerNumberModel(DEFAULT_FOV,0.5,3.0,0.05);
fovSpinner=newJSpinner(snm);
JPanelfovPanel=newJPanel();
fovPanel.setLayout(newBoxLayout(fovPanel,BoxLayout.X_AXIS));
JLabelfovLabel=newJLabel("FieldofView:");
fovPanel.add(javax.swing.Box.createRigidArea(newDimension(30,5)));
fovPanel.add(fovLabel);
fovPanel.add(javax.swing.Box.createRigidArea(newDimension(10,5)));
fovPanel.add(fovSpinner);
finalButtonGroupprojectionButtons=newButtonGroup();
perspectiveButton=newJRadioButtonMenuItem("PerspectiveProjection");
parallelButton=newJRadioButtonMenuItem("ParallelProjection");
fovSpinner.addChangeListener(std);
perspectiveButton.addActionListener(std);
parallelButton.addActionListener(std);
cameraMenu.add(parallelButton);
cameraMenu.add(perspectiveButton);
cameraMenu.add(fovPanel);
projectionButtons.add(parallelButton);
projectionButtons.add(perspectiveButton);
perspectiveButton.setSelected(true);
graphicsMenu=newJMenu("Graphics");
//Leavingoutgraphicsmenufornow!!
//menuBar.add(graphicsMenu);
JLabelgraphicsLabel=newJLabel("PolygonCount");
graphicsLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
graphicsLabel.setForeground(GRAY);
graphicsMenu.add(graphicsLabel);
graphicsMenu.addSeparator();
SpinnerNumberModelsnm2=
newSpinnerNumberModel(DEFAULT_NUM_DIVISIONS,4,4000,5);
numDivSpinner=newJSpinner(snm2);
JPanelnumDivPanel=newJPanel();
numDivPanel.setLayout(newBoxLayout(numDivPanel,BoxLayout.X_AXIS));
JLabelnumDivLabel=newJLabel("Triangles:");
numDivPanel.add(javax.swing.Box.createRigidArea(newDimension(5,5)));
numDivPanel.add(numDivLabel);
numDivPanel.add(javax.swing.Box.createRigidArea(newDimension(15,5)));
numDivPanel.add(numDivSpinner);
graphicsMenu.add(numDivPanel);
numDivSpinner.addChangeListener(std);
graphicsMenu.addSeparator();
JLabelgraphicsLabel2=newJLabel("AdvancedRendering");
graphicsLabel2.setAlignmentX(Component.CENTER_ALIGNMENT);
graphicsLabel2.setForeground(GRAY);
graphicsMenu.add(graphicsLabel2);
graphicsMenu.addSeparator();
antiAliasingButton=newJCheckBoxMenuItem("EnableAnti-Aliasing");
antiAliasingButton.setSelected(false);
antiAliasingButton.addActionListener(std);
graphicsMenu.add(antiAliasingButton);
infoCheckBox=newJCheckBox("ShowInfoDisplay");
infoCheckBox.setFocusable(false);
infoCheckBox.addActionListener(std);
menuBar.add(javax.swing.Box.createRigidArea(newDimension(50,5)));
menuBar.add(infoCheckBox);
returnmenuBar;
}
publicvoidstateChanged(ChangeEvente){
Objectsource=e.getSource();
if(source==numDivSpinner)
numDivisions=(Integer)numDivSpinner.getValue();
if(source==fovSpinner){
setPerspectiveProjection((Double)fovSpinner.getValue());
perspectiveButton.setSelected(true);
}
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidactionPerformed(ActionEvente){
Objectsource=e.getSource();
if(source==saveButton)
saveAction();
elseif(source==loadButton)
loadAction();
elseif(source==save3DButton)
save3DAction();
elseif(source==quitButton)
quitAction();
elseif(source==orbitModeButton)
setCameraMode(ORBIT_MODE);
elseif(source==fpsModeButton)
setCameraMode(FPS_MODE);
elseif(source==airplaneModeButton)
setCameraMode(AIRPLANE_MODE);
elseif(source==lookModeButton)
setCameraMode(LOOK_MODE);
elseif(source==fixedModeButton)
setCameraMode(FIXED_MODE);
elseif(source==perspectiveButton)
setPerspectiveProjection((Double)fovSpinner.getValue());
elseif(source==parallelButton)
setParallelProjection();
elseif(source==antiAliasingButton)
setAntiAliasing(antiAliasingButton.isSelected());
elseif(source==infoCheckBox)
setInfoDisplay(infoCheckBox.isSelected());
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidcomponentHidden(ComponentEvente){keysDown=newTreeSet<Integer>();}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidcomponentMoved(ComponentEvente){keysDown=newTreeSet<Integer>();}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidcomponentShown(ComponentEvente){keysDown=newTreeSet<Integer>();}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidcomponentResized(ComponentEvente){keysDown=newTreeSet<Integer>();}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidwindowGainedFocus(WindowEvente){keysDown=newTreeSet<Integer>();}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidwindowLostFocus(WindowEvente){keysDown=newTreeSet<Integer>();}
/**
*CreatesablankBranchGroupwiththepropercapabilities.
*/
privatestaticBranchGroupcreateBranchGroup(){
BranchGroupbg=newBranchGroup();
bg.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
bg.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
bg.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
bg.setCapability(BranchGroup.ALLOW_DETACH);
bg.setPickable(false);
bg.setCollidable(false);
returnbg;
}
/**
*CreatesablankTransformGroupwiththepropercapabilities.
*/
privatestaticTransformGroupcreateTransformGroup(){
TransformGrouptg=newTransformGroup();
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
tg.setPickable(false);
tg.setCollidable(false);
returntg;
}
/**
*CreatesablankBackgroundwiththepropercapabilities.
*
*@returnThecreatedBackground.
*/
privatestaticBackgroundcreateBackground(){
Backgroundbackground=newBackground();
background.setCapability(Background.ALLOW_COLOR_WRITE);
background.setCapability(Background.ALLOW_IMAGE_WRITE);
background.setCapability(Background.ALLOW_GEOMETRY_WRITE);
background.setApplicationBounds(INFINITE_BOUNDS);
returnbackground;
}
/**
*Createsatexturefromthegivenfilename.
*
*@paramimageURLImagefileforcreatingtexture.
*@returnThecreatedTexture.
*@throwsRuntimeExceptionifthefilecouldnotberead.
*/
privatestaticTexturecreateTexture(StringimageURL){
TextureLoaderloader;
try{
loader=newTextureLoader(imageURL,"RGBA",TextureLoader.Y_UP,newContainer());
}catch(Exceptione){
thrownewRuntimeException("Couldnotreadfromthefile'"+imageURL+"'");
}
Texturetexture=loader.getTexture();
texture.setBoundaryModeS(Texture.WRAP);
texture.setBoundaryModeT(Texture.WRAP);
texture.setBoundaryColor(newColor4f(0.0f,1.0f,0.0f,0.0f));
returntexture;
}
privatestaticAppearancecreateBlankAppearance(){
Appearanceap=newAppearance();
ap.setCapability(Appearance.ALLOW_MATERIAL_READ);
ap.setCapability(Appearance.ALLOW_MATERIAL_WRITE);
ap.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ);
ap.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_WRITE);
returnap;
}
/**
*CreatesanAppearance.
*
*@paramimageURLWrapsatexturearoundfromthisimagefile.
*@paramfillIftrue,fillsinfaces.Iffalse,outlines.
*@returnThecreatedappearance.
*/
privatestaticAppearancecreateAppearance(StringimageURL,booleanfill){
Appearanceap=createBlankAppearance();
PolygonAttributespa=newPolygonAttributes();
if(!fill)pa.setPolygonMode(PolygonAttributes.POLYGON_LINE);
pa.setCullFace(PolygonAttributes.CULL_NONE);
ap.setPolygonAttributes(pa);
if(imageURL!=null){
Texturetexture=createTexture(imageURL);
TextureAttributestexAttr=newTextureAttributes();
texAttr.setTextureMode(TextureAttributes.REPLACE);
ap.setTexture(texture);
ap.setTextureAttributes(texAttr);
}
Color3fcol=newColor3f(penColor);
Color3fblack=newColor3f(0,0,0);
Color3fspecular=newColor3f(GRAY);
//Materialproperties
Materialmaterial=newMaterial(col,black,col,specular,64);
material.setCapability(Material.ALLOW_COMPONENT_READ);
material.setCapability(Material.ALLOW_COMPONENT_WRITE);
material.setLightingEnable(true);
ap.setMaterial(material);
//Transparecyproperties
floatalpha=((float)penColor.getAlpha())/255;
if(alpha<1.0){
TransparencyAttributest=newTransparencyAttributes();
t.setTransparencyMode(TransparencyAttributes.BLENDED);
t.setTransparency(1-alpha);
ap.setTransparencyAttributes(t);
}
LineAttributesla=newLineAttributes();
la.setLineWidth(penRadius);
la.setLineAntialiasingEnable(view.getSceneAntialiasingEnable());
PointAttributespoa=newPointAttributes();
poa.setPointAntialiasingEnable(view.getSceneAntialiasingEnable());
ColoringAttributesca=newColoringAttributes();
ca.setShadeModel(ColoringAttributes.SHADE_GOURAUD);
ca.setColor(col);
ap.setLineAttributes(la);
ap.setPointAttributes(poa);
ap.setColoringAttributes(ca);
returnap;
}
//FIXTHIScheckthataddingspeculardidn'tmessupcustomshapes(lines,triangles,points)
privatestaticAppearancecreateCustomAppearance(booleanfill){
Appearanceap=createBlankAppearance();
PolygonAttributespa=newPolygonAttributes();
if(!fill)pa.setPolygonMode(PolygonAttributes.POLYGON_LINE);
pa.setCullFace(PolygonAttributes.CULL_NONE);
LineAttributesla=newLineAttributes();
la.setLineWidth(penRadius);
la.setLineAntialiasingEnable(view.getSceneAntialiasingEnable());
PointAttributespoa=newPointAttributes();
poa.setPointAntialiasingEnable(view.getSceneAntialiasingEnable());
ap.setPolygonAttributes(pa);
ap.setLineAttributes(la);
ap.setPointAttributes(poa);
Color3fcol=newColor3f(penColor);
Color3fblack=newColor3f(0,0,0);
Color3fspecular=newColor3f(GRAY);
//Materialproperties
Materialmaterial=newMaterial(col,black,col,specular,64);
material.setCapability(Material.ALLOW_COMPONENT_READ);
material.setCapability(Material.ALLOW_COMPONENT_WRITE);
material.setLightingEnable(true);
ap.setMaterial(material);
returnap;
}
privatestaticShape3DcreateShape3D(Geometrygeom){
Shape3Dshape=newShape3D(geom);
shape.setPickable(false);
shape.setCollidable(false);
shape.setCapability(Shape3D.ALLOW_APPEARANCE_READ);
shape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE);
shape.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_READ);
shape.setCapability(Shape3D.ALLOW_APPEARANCE_OVERRIDE_WRITE);
returnshape;
}
/**
*CreatesablankBufferedImage.
*
*@returnThecreatedBufferedImage.
*/
privatestaticBufferedImagecreateBufferedImage(){
returnnewBufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
}
/**ConvertsaVector3DtoaVector3d.*/
privatestaticVector3dcreateVector3d(Vector3Dv){
returnnewVector3d(v.x,v.y,v.z);
}
/**ConvertsthreedoublescalarstoaVector3f.**/
privatestaticVector3fcreateVector3f(doublex,doubley,doublez){
returnnewVector3f((float)x,(float)y,(float)z);
}
/**ConvertsaVector3DtoaVector3f.*/
privatestaticVector3fcreateVector3f(Vector3Dv){
returncreateVector3f(v.x,v.y,v.z);
}
/**ConvertsaVector3DtoaPoint3f.*/
privatestaticPoint3fcreatePoint3f(Vector3Dv){
returncreatePoint3f(v.x,v.y,v.z);
}
/**ConvertsthreedoublescalarstoaPoint3f.*/
privatestaticPoint3fcreatePoint3f(doublex,doubley,doublez){
returnnewPoint3f((float)x,(float)y,(float)z);
}
/**
*Createsascannerfromthefilenameorwebsitename.
*/
privatestaticScannercreateScanner(Strings){
Scannerscanner;
StringcharsetName="ISO-8859-1";
java.util.LocaleusLocale=newjava.util.Locale("en","US");
try{
//firsttrytoreadfilefromlocalfilesystem
Filefile=newFile(s);
if(file.exists()){
scanner=newScanner(file,charsetName);
scanner.useLocale(usLocale);
returnscanner;
}
//nexttryforwebsite
URLurl=newURL(s);
URLConnectionsite=url.openConnection();
InputStreamis=site.getInputStream();
scanner=newScanner(newBufferedInputStream(is),charsetName);
scanner.useLocale(usLocale);
returnscanner;
}
catch(IOExceptionioe){
System.err.println("Couldnotopen"+s+".");
returnnull;
}
}
/****************************************************************
*ScalingandScreenMethods*
*****************************************************************/
/**
*Setsthewindowsizetow-by-hpixels.
*
*@paramwThewidthasanumberofpixels.
*@paramhTheheightasanumberofpixels.
*@throwsaRuntimeExceptionifthewidthorheightis0ornegative.
*/
publicstaticvoidsetCanvasSize(intw,inth){
setCanvasSize(w,h,false);
}
privatestaticvoidsetCanvasSize(intw,inth,booleanfs){
fullscreen=fs;
if(w<1||h<1)thrownewRuntimeException("Dimensionsmustbepositiveintegers!");
width=w;
height=h;
aspectRatio=(double)width/(double)height;
initialize();
}
/**
*Setsthedefaultscaleforallthreedimensions.
*/
publicstaticvoidsetScale(){setScale(DEFAULT_MIN,DEFAULT_MAX);}
/**
*Setsthescaleforallthreedimensions.
*
*@paramminimumTheminimumvalueofeachscale.
*@parammaximumThemaximumvalueofeachscale.
*/
publicstaticvoidsetScale(doubleminimum,doublemaximum){
min=minimum;
max=maximum;
zoom=(max-min)/2;
doublecenter=min+zoom;
//doublenominalDist=camera.getPosition().z;
camera.setPosition(center,center,zoom*(2+Math.sqrt(2)));
doubleorbitScale=0.5*zoom;
orbit.setZoomFactor(orbitScale);
orbit.setTransFactors(orbitScale,orbitScale);
setOrbitCenter(newPoint3d(center,center,center));
view.setFrontClipDistance(DEFAULT_FRONT_CLIP*zoom);
view.setBackClipDistance(DEFAULT_BACK_CLIP*zoom);
}
/**
*Scalesthegivenx-coordinatefromusercoordinatesinto2Dpixelcoordinates.
*/
privatestaticfloatscaleX(doublex){
doublescale=1;
if(width>height)scale=1/aspectRatio;
return(float)(width*(x*scale-min)/(2*zoom));
}
/**
*Scalesthegiveny-coordinatefromusercoordinatesinto2Dpixelcoordinates.
*/
privatestaticfloatscaleY(doubley){
doublescale=1;
if(height>width)scale=aspectRatio;
return(float)(height*(max-y*scale)/(2*zoom));
}
/**
*Scalesthegivenwidthfromusercoordinatesinto2Dpixelcoordinates.
*/
privatestaticdoublefactorX(doublew){
doublescaleDist=width;
if(width>height)scaleDist=height;
returnscaleDist*(w/(2*zoom));
}
/**
*Scalesthegivenheightfromusercoordinatesinto2Dpixelcoordinates.
*/
privatestaticdoublefactorY(doubleh){
doublescaleDist=height;
if(height>width)scaleDist=width;
returnscaleDist*(h/(2*zoom));
}
/**
*Scalesthegivenx-coordinatefrom2Dpixelcoordinatesintousercoordinates.
*/
privatestaticdoubleunscaleX(doublexs){
doublescale=1;
if(width>height)scale=1/aspectRatio;
return(xs*(2*zoom)/width+min)/scale;
}
/**
*Scalesthegiveny-coordinatefrom2Dpixelcoordinatesintousercoordinates.
*/
privatestaticdoubleunscaleY(doubleys){
doublescale=1;
if(height>width)scale=aspectRatio;
//System.out.println("unscaleYscale="+scale);
return(max-ys*(2*zoom)/height)/scale;
}
/****************************************************************
*PenPropertiesMethods*
*****************************************************************/
/**
*Setsthepencolortothegivencolorandtransparency.
*
*@paramcolThegivenopaquecolor.
*@paramalphaThetransparencyvalue(0-255).
*/
publicstaticvoidsetPenColor(Colorcol,intalpha){
setPenColor(newColor(col.getRed(),col.getGreen(),col.getBlue(),alpha));
}
/**
*Setsthepencolortothedefault.
*/
publicstaticvoidsetPenColor(){penColor=DEFAULT_PEN_COLOR;}
/**
*Setsthepencolortothegivencolor.
*
*@paramcolThegivencolor.
*/
publicstaticvoidsetPenColor(Colorcol){penColor=col;}
publicstaticvoidsetPenColor(intr,intg,intb){
penColor=newColor(r,g,b);
}
/**
*Returnsthecurrentpencolor.
*
*@returnThecurrentpencolor.
*/
publicstaticColorgetPenColor(){returnpenColor;}
/**
*Setsthepenradiustothedefaultvalue.
*/
publicstaticvoidsetPenRadius(){setPenRadius(DEFAULT_PEN_RADIUS);}
/**
*Setsthepenradiustothegivenvalue.
*
*@paramrThepenradius.
*/
publicstaticvoidsetPenRadius(doubler){penRadius=(float)r*500;}
/**
*Getsthecurrentpenradius.
*
*@returnThecurrentpenradius.
*/
publicstaticfloatgetPenRadius(){returnpenRadius/500f;}
/**
*Setsthedefaultfont.
*/
publicstaticvoidsetFont(){font=DEFAULT_FONT;}
/**
*Setsthefonttodrawtextwith.
*
*@paramfThefonttoset.
*/
publicstaticvoidsetFont(Fontf){font=f;}
/**
*GetsthecurrentdrawingFont.
*
*@returnThecurrentFont.
*/
publicstaticFontgetFont(){returnfont;}
publicstaticvoidsetInfoDisplay(booleanenabled){
infoDisplay=enabled;
infoCheckBox.setSelected(enabled);
camera.move(0,0,0);
infoDisplay();
}
/****************************************************************
*ViewPropertiesMethods*
*****************************************************************/
publicstaticvoidfullscreen(){
frame.setResizable(true);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
intw=frame.getSize().width;
inth=frame.getSize().height;
//intw=(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
//inth=(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
intborderY=frame.getInsets().top+frame.getInsets().bottom;
intborderX=frame.getInsets().left+frame.getInsets().right;
setCanvasSize(w-borderX,h-borderY-menuBar.getHeight(),true);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
}
/**
*Setsanti-aliasingonoroff.Anti-aliasingmakesgraphics
*lookmuchsmoother,butisveryresourceheavy.Itisgood
*forsavingimagesthatlookprofessional.Thedefaultisoff.
*
*@paramenabledThestateofanti-aliasing.
*/
publicstaticvoidsetAntiAliasing(booleanenabled){
view.setSceneAntialiasingEnable(enabled);
antiAliasingButton.setSelected(enabled);
//System.out.println("Antialiasingenabled:"+enabled);
}
/**
*Returnstrueifanti-aliasingisenabled.
*/
publicstaticbooleangetAntiAliasing(){returnantiAliasingButton.isSelected();}
/**
*Setsthenumberoftriangulardivisonsofcurvedobjects.
*Thedefaultis100divisons.Decreasethistoincreaseperformance.
*
*@paramNThenumberofdivisions.
*/
publicstaticvoidsetNumDivisions(intN){numDivisions=N;}
/**
*Getsthenumberoftriangulardivisonsofcurvedobjects.
*
*@returnThenumberofdivisions.
*/
publicstaticintgetNumDivisions(){returnnumDivisions;}
/**
*Getsthecurrentcameramode.
*
*@returnThecurrentcameramode.
*/
publicstaticintgetCameraMode(){returncameraMode;}
/**
*Setsthecurrentcameramode.<br>
*--------------------------------------<br>
*StdDraw3D.ORBIT_MODE:<br>
*Rotatesandzoomsaroundacentralpoint.<br>
*<br>
*MouseClickLeft-Orbit<br>
*MouseClickRight-Pan<br>
*MouseWheel/Alt-Click-Zoom<br>
*--------------------------------------<br>
*StdDraw3D.FPS_MODE:<br>
*First-person-shooterstylecontrols.<br>
*Upisalwaysthepositivey-axis.<br>
*<br>
*W/Up-Forward<br>
*S/Down-Backward<br>
*A/Left-Left<br>
*D/Right-Right<br>
*Q/PageUp-Up<br>
*E/PageDown-Down<br>
*Mouse-Look<br>
*--------------------------------------<br>
*StdDraw3D.AIRPLANE_MODE:<br>
*Similartofps_mode,butcanbeoriented<br>
*withupinanydirection.<br>
*<br>
*W/Up-Forward<br>
*S/Down-Backward<br>
*A/Left-Left<br>
*D/Right-Right<br>
*Q/PageUp-RotateCCW<br>
*E/PageDown-RotateCW<br>
*Mouse-Look<br>
*--------------------------------------<br>
*StdDraw3D.LOOK_MODE:<br>
*Nomovement,butusesmousetolookaround.<br>
*<br>
*Mouse-Look<br>
*--------------------------------------<br>
*StdDraw3D.FIXED_MODE:<br>
*Nomovementorlooking.<br>
*--------------------------------------<br>
*@parammodeThecameramode.
*/
publicstaticvoidsetCameraMode(intmode){
cameraMode=mode;
if(cameraMode==ORBIT_MODE){
orbit.setRotateEnable(true);
if(view.getProjectionPolicy()!=View.PARALLEL_PROJECTION)
orbit.setZoomEnable(true);
orbit.setTranslateEnable(true);
orbit.setRotationCenter(orbitCenter);
orbitModeButton.setSelected(true);
}else{
orbit.setRotateEnable(false);
orbit.setZoomEnable(false);
orbit.setTranslateEnable(false);
}
if(cameraMode==FPS_MODE){
fpsModeButton.setSelected(true);
camera.rotateFPS(0,0,0);
}
if(cameraMode==AIRPLANE_MODE){
airplaneModeButton.setSelected(true);
}
if(cameraMode==LOOK_MODE){
//System.out.println("Camerainlookmode.");
lookModeButton.setSelected(true);
}
if(cameraMode==FIXED_MODE){
//System.out.println("Camerainfixedmode.");
fixedModeButton.setSelected(true);
}
if(cameraMode==IMMERSIVE_MODE){
BufferedImagecursorImg=newBufferedImage(16,16,BufferedImage.TYPE_INT_ARGB);
CursorblankCursor=Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg,newjava.awt.Point(0,0),"blankcursor");
frame.getContentPane().setCursor(blankCursor);
//System.out.println("Camerainfpsmode.");
}else{
frame.getContentPane().setCursor(Cursor.getDefaultCursor());
}
}
/**
*Setsthedefaultcameramode.
*/
publicstaticvoidsetCameraMode(){setCameraMode(DEFAULT_CAMERA_MODE);}
/**
*SetsthecenterofrotationforthecameramodeORBIT_MODE.
*/
publicstaticvoidsetOrbitCenter(doublex,doubley,doublez){
setOrbitCenter(newPoint3d(x,y,z));
}
/**
*SetsthecenterofrotationforthecameramodeORBIT_MODE.
*/
publicstaticvoidsetOrbitCenter(Vector3Dv){
setOrbitCenter(newPoint3d(v.x,v.y,v.z));
}
privatestaticvoidsetOrbitCenter(Point3dcenter){
orbitCenter=center;
orbit.setRotationCenter(orbitCenter);
}
publicstaticVector3DgetOrbitCenter(){
returnnewVector3D(orbitCenter);
}
/**
*Setstheprojectionmodetoperspectiveprojectionwitha
*defaultfieldofview.Inthismode,closerobjectsappear
*larger,asinreallife.
*/
publicstaticvoidsetPerspectiveProjection(){
setPerspectiveProjection(DEFAULT_FOV);
}
/**
*Setstheprojectionmodetoperspectiveprojectionwiththe
*givenfieldofview.Inthismode,closerobjectsappear
*larger,asinreallife.Alargerfieldofviewmeansthat
*thereismoreperspectivedistortion.Reasonablevaluesare
*between0.5and3.0.
*
*@paramfovThefieldofviewtouse.Try[0.5-3.0].
*/
publicstaticvoidsetPerspectiveProjection(doublefov){
view.setProjectionPolicy(View.PERSPECTIVE_PROJECTION);
view.setWindowEyepointPolicy(View.RELATIVE_TO_FIELD_OF_VIEW);
view.setFieldOfView(fov);
setScreenScale(1);
orbit.setZoomEnable(true);
perspectiveButton.setSelected(true);
if((Double)fovSpinner.getValue()!=fov)
fovSpinner.setValue(fov);
//if(view.getProjectionPolicy()==View.PERSPECTIVE_PROJECTION)return;
}
/**
*Setstheprojectionmodetoorthographicprojection.
*Inthismode,parallellinesremainparallelafter
*projection,andthereisnoperspective.Itisas
*lookingfrominfinitelyfarawaywithatelescope.
*AutoCADprogramsusethisprojectionmode.
*/
publicstaticvoidsetParallelProjection(){
if(view.getProjectionPolicy()==View.PARALLEL_PROJECTION)return;
view.setProjectionPolicy(View.PARALLEL_PROJECTION);
orbit.setZoomEnable(false);
parallelButton.setSelected(true);
setScreenScale(0.3/zoom);
}
privatestaticvoidsetScreenScale(doublescale){
doubleratio=scale/view.getScreenScale();
view.setScreenScale(scale);
view.setFrontClipDistance(view.getFrontClipDistance()*ratio);
view.setBackClipDistance(view.getBackClipDistance()*ratio);
}
/****************************************************************
*MouseListenerMethods*
*****************************************************************/
/**Isanymousebuttonpressed?*/
publicstaticbooleanmousePressed(){
synchronized(mouseLock){
return(mouse1Pressed()||mouse2Pressed()||mouse3Pressed());
}
}
/**
*Isthemouse1buttonpresseddown?
*/
publicstaticbooleanmouse1Pressed(){
synchronized(mouseLock){
returnmouse1;
}
}
/**
*Isthemouse2buttonpresseddown?
*/
publicstaticbooleanmouse2Pressed(){
synchronized(mouseLock){
returnmouse2;
}
}
/**
*Isthemouse3buttonpresseddown?
*/
publicstaticbooleanmouse3Pressed(){
synchronized(mouseLock){
returnmouse3;
}
}
/**
*Whereisthemouse?
*
*@returnThevalueoftheX-coordinateofthemouse.
*/
publicstaticdoublemouseX(){
synchronized(mouseLock){
returnunscaleX(mouseX);
}
}
/**
*Whereisthemouse?
*@returnThevalueoftheY-coordinateofthemouse.
*/
publicstaticdoublemouseY(){
synchronized(mouseLock){
returnunscaleY(mouseY);
}
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidmouseClicked(MouseEvente){
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidmouseEntered(MouseEvente){}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidmouseExited(MouseEvente){
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidmousePressed(MouseEvente){
synchronized(mouseLock){
mouseX=e.getX();
mouseY=e.getY();
if(e.getButton()==1)mouse1=true;
if(e.getButton()==2)mouse2=true;
if(e.getButton()==3)mouse3=true;
//System.out.println("Mousebutton="+e.getButton());
}
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidmouseReleased(MouseEvente){
synchronized(mouseLock){
if(e.getButton()==1)mouse1=false;
if(e.getButton()==2)mouse2=false;
if(e.getButton()==3)mouse3=false;
}
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidmouseDragged(MouseEvente){
synchronized(mouseLock){
mouseMotionEvents(e,e.getX(),e.getY(),true);
mouseX=e.getX();
mouseY=e.getY();
}
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidmouseMoved(MouseEvente){
synchronized(mouseLock){
//System.out.println(e.getX()+""+e.getY());
mouseMotionEvents(e,e.getX(),e.getY(),false);
}
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidmouseWheelMoved(MouseWheelEvente){
doublenotches=e.getWheelRotation();
//System.out.println(notches);
if((cameraMode==ORBIT_MODE)&&(view.getProjectionPolicy()==View.PARALLEL_PROJECTION)){
camera.moveRelative(0,0,notches*zoom/20);
}
}
privatestaticvoidmouseMotionEvents(MouseEvente,doublenewX,doublenewY,booleandragged){
//System.out.println("x="+mouseX()+"y="+mouseY());
if(cameraMode==FIXED_MODE)return;
if(cameraMode==FPS_MODE){
if(dragged||immersive){
camera.rotateFPS((mouseY-newY)/4,(mouseX-newX)/4,0);
}
return;
}
if((cameraMode==AIRPLANE_MODE)){
if(dragged||immersive)
camera.rotateRelative((mouseY-newY)/4,(mouseX-newX)/4,0);
return;
}
if((cameraMode==LOOK_MODE)){
if(dragged||immersive)
camera.rotateFPS((mouseY-newY)/4,(mouseX-newX)/4,0);
return;
}
if((cameraMode==ORBIT_MODE)&&(dragged&&isKeyPressed(KeyEvent.VK_ALT))&&(view.getProjectionPolicy()==View.PARALLEL_PROJECTION)){
camera.moveRelative(0,0,(double)(newY-mouseY)*zoom/50);
return;
}
}
/****************************************************************
*KeyboardListenerMethods*
*****************************************************************/
/**
*Hastheusertypedakey?
*
*@returnTrueiftheuserhastypedakey,falseotherwise.
*/
publicstaticbooleanhasNextKeyTyped(){
synchronized(keyLock){
return!keysTyped.isEmpty();
}
}
/**
*Whatisthenextkeythatwastypedbytheuser?
*
*@returnThenextkeytyped.
*/
publicstaticcharnextKeyTyped(){
synchronized(keyLock){
returnkeysTyped.removeLast();
}
}
/**
*Isthegivenkeycurrentlypresseddown?Thekeyscorrenspond
*tophysicalkeys,notcharacters.Forletters,usethe
*uppercasecharactertorefertothekey.Forarrowkeysand
*modifierssuchasshiftandctrl,refertotheKeyEvent
*constants,suchasKeyEvent.VK_SHIFT.
*
*@paramkeyThegivenkey
*@returnTrueifthegivencharacterispressed.
*/
publicstaticbooleanisKeyPressed(intkey){
synchronized(keyLock){
returnkeysDown.contains(key);
}
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidkeyTyped(KeyEvente){
synchronized(keyLock){
charc=e.getKeyChar();
keysTyped.addFirst(c);
if(c=='`')setCameraMode((getCameraMode()+1)%5);
}
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidkeyPressed(KeyEvente){
synchronized(keyLock){
keysDown.add(e.getKeyCode());
//System.out.println((int)e.getKeyCode()+"pressed");
}
}
/**
*Thismethodcannotbecalleddirectly.
*@deprecated
*/
publicvoidkeyReleased(KeyEvente){
synchronized(keyLock){
keysDown.remove(e.getKeyCode());
//System.out.println((int)e.getKeyCode()+"released");
}
}
/**
*Processesoneframeofkeyboardevents.
*
*@paramtimeTheamountoftimeforthisframe.
*/
privatestaticvoidmoveEvents(inttime){
infoDisplay();
if(isKeyPressed(KeyEvent.VK_CONTROL))return;
if(cameraMode==FPS_MODE){
doublemove=0.00015*time*(zoom);
if(isKeyPressed('W')||isKeyPressed(KeyEvent.VK_UP))camera.moveRelative(0,0,move*3);
if(isKeyPressed('S')||isKeyPressed(KeyEvent.VK_DOWN))camera.moveRelative(0,0,-move*3);
if(isKeyPressed('A')||isKeyPressed(KeyEvent.VK_LEFT))camera.moveRelative(-move,0,0);
if(isKeyPressed('D')||isKeyPressed(KeyEvent.VK_RIGHT))camera.moveRelative(move,0,0);
if(isKeyPressed('Q')||isKeyPressed(KeyEvent.VK_PAGE_UP))camera.moveRelative(0,move,0);
if(isKeyPressed('E')||isKeyPressed(KeyEvent.VK_PAGE_DOWN))camera.moveRelative(0,-move,0);
}
if(cameraMode==AIRPLANE_MODE){
doublemove=0.00015*time*(zoom);
if(isKeyPressed('W')||isKeyPressed(KeyEvent.VK_UP))camera.moveRelative(0,0,move*3);
if(isKeyPressed('S')||isKeyPressed(KeyEvent.VK_DOWN))camera.moveRelative(0,0,-move*3);
if(isKeyPressed('A')||isKeyPressed(KeyEvent.VK_LEFT))camera.moveRelative(-move,0,0);
if(isKeyPressed('D')||isKeyPressed(KeyEvent.VK_RIGHT))camera.moveRelative(move,0,0);
if(isKeyPressed('Q')||isKeyPressed(KeyEvent.VK_PAGE_UP))camera.rotateRelative(0,0,move*250/zoom);
if(isKeyPressed('E')||isKeyPressed(KeyEvent.VK_PAGE_DOWN))camera.rotateRelative(0,0,-move*250/zoom);
}
}
/****************************************************************
*ActionListenerMethods*
*****************************************************************/
privatestaticvoidsave3DAction(){
FileDialogchooser=newFileDialog(StdDraw3D.frame,"Saveasa3Dfileforloadinglater.",FileDialog.SAVE);
chooser.setVisible(true);
Stringfilename=chooser.getFile();
if(filename!=null){
StdDraw3D.saveScene3D(chooser.getDirectory()+File.separator+chooser.getFile());
}
keysDown.remove(KeyEvent.VK_META);
keysDown.remove(KeyEvent.VK_CONTROL);
keysDown.remove(KeyEvent.VK_E);
}
privatestaticvoidloadAction(){
FileDialogchooser=newFileDialog(frame,"Picka.objor.plyfiletoload.",FileDialog.LOAD);
chooser.setVisible(true);
Stringfilename=chooser.getDirectory()+chooser.getFile();
model(filename);
keysDown.remove(KeyEvent.VK_META);
keysDown.remove(KeyEvent.VK_CONTROL);
keysDown.remove(KeyEvent.VK_L);
}
privatestaticvoidsaveAction(){
FileDialogchooser=newFileDialog(frame,"Usea.pngor.jpgextension.",FileDialog.SAVE);
chooser.setVisible(true);
Stringfilename=chooser.getFile();
if(filename!=null){
StdDraw3D.save(chooser.getDirectory()+File.separator+chooser.getFile());
}
keysDown.remove(KeyEvent.VK_META);
keysDown.remove(KeyEvent.VK_CONTROL);
keysDown.remove(KeyEvent.VK_S);
}
privatestaticvoidquitAction(){
WindowEventwev=newWindowEvent(frame,WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
keysDown.remove(KeyEvent.VK_META);
keysDown.remove(KeyEvent.VK_CONTROL);
keysDown.remove(KeyEvent.VK_Q);
}
/****************************************************************
*LightandBackgroundMethods*
*****************************************************************/
/**
*Setsthebackgroundcolortothegivencolor.
*
*@paramcolorThecolortosetthebackgroundas.
*/
publicstaticvoidsetBackground(Colorcolor){
if(!color.equals(bgColor)){
bgColor=color;
rootGroup.removeChild(bgGroup);
bgGroup.removeChild(background);
background=createBackground();
background.setColor(newColor3f(bgColor));
bgGroup.addChild(background);
rootGroup.addChild(bgGroup);
}
}
/**
*Setsthebackgroundimagetothegivenfilename,scaledtofitthewindow.
*
*@paramimageURLThefilenameforthebackgroundimage.
*/
publicstaticvoidsetBackground(StringimageURL){
rootGroup.removeChild(bgGroup);
bgGroup.removeChild(background);
background=createBackground();
BufferedImagebi=null;
try{bi=ImageIO.read(newFile(imageURL));}
catch(IOExceptionioe){ioe.printStackTrace();}
if(bi==null){
try{ImageIO.read(newURL(imageURL));}
catch(Exceptione){e.printStackTrace();}
}
ImageComponent2DimageComp=newImageComponent2D(ImageComponent.FORMAT_RGB,bi);
background.setImage(imageComp);
background.setImageScaleMode(Background.SCALE_FIT_ALL);
bgGroup.addChild(background);
rootGroup.addChild(bgGroup);
}
/**
*Setsthebackgroundtothegivenimagefile.Thefilegets
*wrappedaroundasasphericalskybox.
*
*@paramimageURLThebackgroundimagetouse.
*/
publicstaticvoidsetBackgroundSphere(StringimageURL){
Spheresphere=newSphere(1.1f,Sphere.GENERATE_NORMALS
|Sphere.GENERATE_NORMALS_INWARD
|Sphere.GENERATE_TEXTURE_COORDS,numDivisions);
Appearanceap=sphere.getAppearance();
Texturetexture=createTexture(imageURL);
TextureAttributestexAttr=newTextureAttributes();
texAttr.setTextureMode(TextureAttributes.REPLACE);
ap.setTexture(texture);
ap.setTextureAttributes(texAttr);
sphere.setAppearance(ap);
BranchGroupbackGeoBranch=createBranchGroup();
backGeoBranch.addChild(sphere);
rootGroup.removeChild(bgGroup);
bgGroup.removeChild(background);
background=createBackground();
background.setGeometry(backGeoBranch);
bgGroup.addChild(background);
rootGroup.addChild(bgGroup);
}
//*********************************************************************************************
publicstaticvoidclearSound(){
soundGroup.removeAllChildren();
}
publicstaticvoidplayAmbientSound(Stringfilename){
playAmbientSound(filename,1.0,false);
}
publicstaticvoidplayAmbientSound(Stringfilename,booleanloop){
playAmbientSound(filename,1.0,loop);
}
privatestaticvoidplayAmbientSound(Stringfilename,doublevolume,booleanloop){
MediaContainermc=newMediaContainer("file:"+filename);
mc.setCacheEnable(true);
BackgroundSoundsound=newBackgroundSound();
sound.setInitialGain((float)volume);
sound.setSoundData(mc);
sound.setBounds(INFINITE_BOUNDS);
sound.setSchedulingBounds(INFINITE_BOUNDS);
if(loop==true)sound.setLoop(Sound.INFINITE_LOOPS);
sound.setEnable(true);
BranchGroupbg=createBranchGroup();
bg.addChild(sound);
soundGroup.addChild(bg);
}
//publicstaticvoidplayPointSound(Stringfilename,Vector3Dposition,doublevolume,booleanloop){
//
//MediaContainermc=newMediaContainer("file:"+filename);
//mc.setCacheEnable(true);
//
//PointSoundsound=newPointSound();
//sound.setInitialGain((float)volume);
//sound.setSoundData(mc);
//sound.setBounds(INFINITE_BOUNDS);
//sound.setSchedulingBounds(INFINITE_BOUNDS);
//if(loop==true)sound.setLoop(Sound.INFINITE_LOOPS);
//sound.setPosition(createPoint3f(position));
//Point2f[]distanceGain=newPoint2f[2];
//distanceGain[0]=newPoint2f(0,1);
//distanceGain[1]=newPoint2f(20,0);
//sound.setDistanceGain(distanceGain);
//sound.setEnable(true);
//
//BranchGroupbg=createBranchGroup();
//bg.addChild(sound);
//soundGroup.addChild(bg);
//}
//*********************************************************************************************
publicstaticvoidclearFog(){
fogGroup.removeAllChildren();
}
publicstaticvoidaddFog(Colorcol,doublefrontDistance,doublebackDistance){
LinearFogfog=newLinearFog(newColor3f(col),frontDistance,backDistance);
fog.setInfluencingBounds(INFINITE_BOUNDS);
BranchGroupbg=createBranchGroup();
bg.addChild(fog);
fogGroup.addChild(bg);
}
//*********************************************************************************************
/**
*Removesallcurrentlightingfromthescene.
*/
publicstaticvoidclearLight(){
lightGroup.removeAllChildren();
}
/**
*Addsthedefaultlightingtothescene,calledautomaticallyatstartup.
*/
publicstaticvoidsetDefaultLight(){
clearLight();
directionalLight(-4f,7f,12f,LIGHT_GRAY);
directionalLight(4f,-7f,-12f,WHITE);
ambientLight(newColor(0.1f,0.1f,0.1f));
}
/**
*Addsadirectionallightofcolorcolwhichappearstocomefrom(x,y,z).
*/
publicstaticLightdirectionalLight(Vector3Ddir,Colorcol){
returndirectionalLight(dir.x,dir.y,dir.z,col);
}
/**
*Addsadirectionallightofcolorcolwhichshinesinthedirectionvector(x,y,z)
*/
publicstaticLightdirectionalLight(doublex,doubley,doublez,Colorcol){
DirectionalLightlight=newDirectionalLight();
light.setColor(newColor3f(col));
light.setInfluencingBounds(INFINITE_BOUNDS);
light.setCapability(DirectionalLight.ALLOW_STATE_WRITE);
light.setCapability(DirectionalLight.ALLOW_COLOR_WRITE);
light.setEnable(true);
BranchGroupbg=createBranchGroup();
TransformGrouptg=createTransformGroup();
tg.addChild(light);
bg.addChild(tg);
lightGroup.addChild(bg);
Lightl=newLight(bg,tg,light);
l.setDirection(newVector3D(x,y,z));
returnl;
}
/**
*Addsambientlightofcolorcol.
*/
publicstaticLightambientLight(Colorcol){
Color3flightColor=newColor3f(col);
AmbientLightlight=newAmbientLight(lightColor);
light.setInfluencingBounds(INFINITE_BOUNDS);
light.setCapability(AmbientLight.ALLOW_STATE_WRITE);
light.setCapability(AmbientLight.ALLOW_COLOR_WRITE);
BranchGroupbg=createBranchGroup();
TransformGrouptg=createTransformGroup();
tg.addChild(light);
bg.addChild(tg);
lightGroup.addChild(bg);
returnnewLight(bg,tg,light);
}
publicstaticLightpointLight(Vector3Dorigin,Colorcol){
returnpointLight(origin.x,origin.y,origin.z,col,1.0);
}
publicstaticLightpointLight(doublex,doubley,doublez,Colorcol){
returnpointLight(x,y,z,col,1.0);
}
publicstaticLightpointLight(Vector3Dorigin,Colorcol,doublepower){
returnpointLight(origin.x,origin.y,origin.z,col,power);
}
publicstaticLightpointLight(doublex,doubley,doublez,Colorcol,doublepower){
PointLightlight=newPointLight();
light.setColor(newColor3f(col));
light.setInfluencingBounds(INFINITE_BOUNDS);
light.setCapability(PointLight.ALLOW_STATE_WRITE);
light.setCapability(PointLight.ALLOW_COLOR_WRITE);
light.setCapability(PointLight.ALLOW_ATTENUATION_WRITE);
floatscale=(float)zoom;
floatlinearFade=0.03f;
floatquadraticFade=0.03f;
light.setAttenuation(1.0f,linearFade/scale,quadraticFade/(scale*scale));
BranchGroupbg=createBranchGroup();
TransformGrouptg=createTransformGroup();
tg.addChild(light);
bg.addChild(tg);
lightGroup.addChild(bg);
Lightl=newLight(bg,tg,light);
l.setPosition(x,y,z);
l.scalePower(power);
returnl;
}
/**
*Returnsarandomlygeneratedcolor.
*/
publicstaticColorrandomColor(){
returnnewColor(newRandom().nextInt());
}
/**
*Returnsarandomlygeneratedcolorontherainbow.
*/
publicstaticColorrandomRainbowColor(){
returnColor.getHSBColor((float)Math.random(),1.0f,1.0f);
}
/**
*ReturnsarandomlygeneratednormalizedVector3D.
*/
publicstaticVector3DrandomDirection(){
doubletheta=Math.random()*Math.PI*2;
doublephi=Math.random()*Math.PI;
returnnewVector3D(Math.cos(theta)*Math.sin(phi),Math.sin(theta)*Math.sin(phi),Math.cos(phi));
}
/****************************************************************
*AnimationFrameMethods*
*****************************************************************/
/**
*Clearstheentireonthenextcallofshow().
*/
publicstaticvoidclear(){
clear3D();
clearOverlay();
}
publicstaticvoidclear(Colorcolor){
setBackground(color);
clear();
}
/**
*Clearsthe3Dworldonthescreenforthenextcallofshow();
*/
publicstaticvoidclear3D(){
clear3D=true;
offscreenGroup=createBranchGroup();
}
/**
*Clearsthe2Doverlayforthenextcallofshow();
*/
publicstaticvoidclearOverlay(){
clearOverlay=true;
offscreenImage=createBufferedImage();
}
/**
*Pausesforagivenamountofmilliseconds.
*
*@paramtimeThenumberofmillisecondstopausefor.
*/
publicstaticvoidpause(inttime){
intt=time;
intdt=15;
while(t>dt){
moveEvents(dt);
Toolkit.getDefaultToolkit().sync();
try{Thread.currentThread().sleep(dt);}
catch(InterruptedExceptione){System.out.println("Errorsleeping");}
t-=dt;
}
moveEvents(t);
if(t==0)return;
try{Thread.currentThread().sleep(t);}
catch(InterruptedExceptione){System.out.println("Errorsleeping");}
//while(!renderedOnce){
//try{Thread.currentThread().sleep(1);}
//catch(InterruptedExceptione){System.out.println("Errorsleeping");}
//
//renderedOnce=false;
//showedOnce=true;
}
/**
*Allowsforcameranavigationofascenewithoutredrawing.Usefulwhen
*drawingacomplicatedsceneonceandthenexploringwithoutredrawing.
*Callonlyasthelastlineofaprogram.
*/
publicstaticvoidfinished(){
show(1000000000);
}
/**
*Renderstothescreen,butdoesnotpause.
*/
publicstaticvoidshow(){show(0);}
/**
*Rendersdrawn3Dobjectstothescreenanddrawsthe
*2Doverlay,thenpausesforthegiventime.
*
*@paramtimeThenumberofmillisecondstopausefor.
*/
publicstaticvoidshow(inttime){
renderOverlay();
render3D();
pause(time);
}
publicstaticvoidshowOverlay(){showOverlay(0);}
/**
*Displaysthedrawnoverlayontothescreen.
*/
publicstaticvoidshowOverlay(inttime){
renderOverlay();
pause(time);
}
privatestaticvoidrenderOverlay(){
if(clearOverlay){
clearOverlay=false;
onscreenImage=offscreenImage;
}else{
Graphics2Dgraphics=(Graphics2D)onscreenImage.getGraphics();
graphics.drawRenderedImage(offscreenImage,newAffineTransform());
}
offscreenImage=createBufferedImage();
}
publicstaticvoidshow3D(){show3D(0);}
/**
*Rendersthedrawn3Dobjectstothescreen,butnottheoverlay.
*/
publicstaticvoidshow3D(inttime){
render3D();
pause(time);
}
privatestaticvoidrender3D(){
rootGroup.addChild(offscreenGroup);
if(clear3D){
clear3D=false;
rootGroup.removeChild(onscreenGroup);
onscreenGroup=offscreenGroup;
}else{
Enumerationchildren=offscreenGroup.getAllChildren();
while(children.hasMoreElements()){
Nodechild=(Node)children.nextElement();
offscreenGroup.removeChild(child);
onscreenGroup.addChild(child);
}
}
offscreenGroup=createBranchGroup();
//System.out.println("off="+offscreenGroup.numChildren());
//System.out.println("on="+onscreenGroup.numChildren());
rootGroup.removeChild(offscreenGroup);
//StdOut.println("showedonce=true");
}
/****************************************************************
*Primitive3DDrawingMethods*
*****************************************************************/
/**
*Drawsasphereat(x,y,z)withradiusr.
*/
publicstaticShapesphere(doublex,doubley,doublez,doubler){
returnsphere(x,y,z,r,0,0,0,null);
}
/**
*Drawsasphereat(x,y,z)withradiusrandaxialrotations(xA,yA,zA).
*/
publicstaticShapesphere(doublex,doubley,doublez,doubler,doublexA,doubleyA,doublezA){
returnsphere(x,y,z,r,xA,yA,zA,null);
}
/**
*Drawsasphereat(x,y,z)withradiusrandatexturefromimageURL.
*/
publicstaticShapesphere(doublex,doubley,doublez,doubler,StringimageURL){
returnsphere(x,y,z,r,0,0,0,imageURL);
}
/**
*Drawsasphereat(x,y,z)withradiusr,axialrotations(xA,yA,zA),andatexturefromimageURL.
*/
publicstaticShapesphere(doublex,doubley,doublez,doubler,doublexA,doubleyA,doublezA,StringimageURL){
Vector3fdimensions=createVector3f(0,0,r);
Spheresphere=newSphere(dimensions.z,PRIMFLAGS,numDivisions);
sphere.setAppearance(createAppearance(imageURL,true));
returnprimitive(sphere,x,y,z,newVector3d(xA,yA,zA),null);
}
/**
*Drawsawireframesphereat(x,y,z)withradiusr.
*/
publicstaticShapewireSphere(doublex,doubley,doublez,doubler){
returnwireSphere(x,y,z,r,0,0,0);
}
/**
*Drawsawireframesphereat(x,y,z)withradiusrandaxialrotations(xA,yA,zA).
*/
publicstaticShapewireSphere(doublex,doubley,doublez,doubler,doublexA,doubleyA,doublezA){
Vector3fdimensions=createVector3f(0,0,r);
Spheresphere=newSphere(dimensions.z,PRIMFLAGS,numDivisions);
sphere.setAppearance(createAppearance(null,false));
returnprimitive(sphere,x,y,z,newVector3d(xA,yA,zA),null);
}
//*********************************************************************************************
/**
*Drawsanellipsoidat(x,y,z)withdimensions(w,h,d).
*/
publicstaticShapeellipsoid(doublex,doubley,doublez,doublew,doubleh,doubled){
returnellipsoid(x,y,z,w,h,d,0,0,0,null);
}
/**
*Drawsanellipsoidat(x,y,z)withdimensions(w,h,d)andaxialrotations(xA,yA,zA).
*/
publicstaticShapeellipsoid(doublex,doubley,doublez,doublew,doubleh,doubled,doublexA,doubleyA,doublezA){
returnellipsoid(x,y,z,w,h,d,xA,yA,zA,null);
}
/**
*Drawsanellipsoidat(x,y,z)withdimensions(w,h,d)andatexturefromimageURL.
*/
publicstaticShapeellipsoid(doublex,doubley,doublez,doublew,doubleh,doubled,StringimageURL){
returnellipsoid(x,y,z,w,h,d,0,0,0,imageURL);
}
/**
*Drawsanellipsoidat(x,y,z)withdimensions(w,h,d),axialrotations(xA,yA,zA),andatexturefromimageURL.
*/
publicstaticShapeellipsoid(doublex,doubley,doublez,doublew,doubleh,doubled,doublexA,doubleyA,doublezA,StringimageURL){
Spheresphere=newSphere(1,PRIMFLAGS,numDivisions);
sphere.setAppearance(createAppearance(imageURL,true));
returnprimitive(sphere,x,y,z,newVector3d(xA,yA,zA),newVector3d(w,h,d));
}
/**
*Drawsawireframeellipsoidat(x,y,z)withdimensions(w,h,d).
*/
publicstaticShapewireEllipsoid(doublex,doubley,doublez,doublew,doubleh,doubled){
returnwireEllipsoid(x,y,z,w,h,d,0,0,0);
}
/**
*Drawsawireframeellipsoidat(x,y,z)withdimensions(w,h,d)andaxialrotations(xA,yA,zA).
*/
publicstaticShapewireEllipsoid(doublex,doubley,doublez,doublew,doubleh,doubled,doublexA,doubleyA,doublezA){
Spheresphere=newSphere(1,PRIMFLAGS,numDivisions);
sphere.setAppearance(createAppearance(null,false));
returnprimitive(sphere,x,y,z,newVector3d(xA,yA,zA),newVector3d(w,h,d));
}
//*********************************************************************************************
/**
*Drawsacubeat(x,y,z)withradiusr.
*/
publicstaticShapecube(doublex,doubley,doublez,doubler){
returncube(x,y,z,r,0,0,0,null);
}
/**
*Drawsacubeat(x,y,z)withradiusrandaxialrotations(xA,yA,zA).
*/
publicstaticShapecube(doublex,doubley,doublez,doubler,doublexA,doubleyA,doublezA){
returncube(x,y,z,r,xA,yA,zA,null);
}
/**
*Drawsacubeat(x,y,z)withradiusrandatexturefromimageURL.
*/
publicstaticShapecube(doublex,doubley,doublez,doubler,StringimageURL){
returncube(x,y,z,r,0,0,0,imageURL);
}
/**
*Drawsacubeat(x,y,z)withradiusr,axialrotations(xA,yA,zA),andatexturefromimageURL.
*/
publicstaticShapecube(doublex,doubley,doublez,doubler,doublexA,doubleyA,doublezA,StringimageURL){
returnbox(x,y,z,r,r,r,xA,yA,zA,imageURL);
}
/**
*Drawsawireframecubeat(x,y,z)withradiusrandaxialrotations(xA,yA,zA).
*/
publicstaticShapewireCube(doublex,doubley,doublez,doubler,doublexA,doubleyA,doublezA){
returnwireBox(x,y,z,r,r,r,0,0,0);
}
/**
*Drawsawireframecubeat(x,y,z)withradiusr.
*/
publicstaticShapewireCube(doublex,doubley,doublez,doubler){
double[]xC=newdouble[]
{x+r,x+r,x-r,x-r,x+r,x+r,x+r,x-r,x-r,x+r,x+r,x+r,x-r,x-r,x-r,x-r};
double[]yC=newdouble[]
{y+r,y-r,y-r,y+r,y+r,y+r,y-r,y-r,y+r,y+r,y-r,y-r,y-r,y-r,y+r,y+r};
double[]zC=newdouble[]
{z+r,z+r,z+r,z+r,z+r,z-r,z-r,z-r,z-r,z-r,z-r,z+r,z+r,z-r,z-r,z+r};
returnlines(xC,yC,zC);
}
//*********************************************************************************************
/**
*Drawsaboxat(x,y,z)withdimensions(w,h,d).
*/
publicstaticShapebox(doublex,doubley,doublez,doublew,doubleh,doubled){
returnbox(x,y,z,w,h,d,0,0,0,null);
}
/**
*Drawsaboxat(x,y,z)withdimensions(w,h,d)andaxialrotations(xA,yA,zA).
*/
publicstaticShapebox(doublex,doubley,doublez,doublew,doubleh,doubled,doublexA,doubleyA,doublezA){
returnbox(x,y,z,w,h,d,xA,yA,zA,null);
}
/**
*Drawsaboxat(x,y,z)withdimensions(w,h,d)andatexturefromimageURL.
*/
publicstaticShapebox(doublex,doubley,doublez,doublew,doubleh,doubled,StringimageURL){
returnbox(x,y,z,w,h,d,0,0,0,imageURL);
}
/**
*Drawsaboxat(x,y,z)withdimensions(w,h,d),axialrotations(xA,yA,zA),andatexturefromimageURL.
*/
publicstaticShapebox(doublex,doubley,doublez,doublew,doubleh,doubled,doublexA,doubleyA,doublezA,StringimageURL){
Appearanceap=createAppearance(imageURL,true);
Vector3fdimensions=createVector3f(w,h,d);
com.sun.j3d.utils.geometry.Boxbox=new
com.sun.j3d.utils.geometry.Box(dimensions.x,dimensions.y,dimensions.z,PRIMFLAGS,ap,numDivisions);
returnprimitive(box,x,y,z,newVector3d(xA,yA,zA),null);
}
/**
*Drawsawireframeboxat(x,y,z)withdimensions(w,h,d).
*/
publicstaticShapewireBox(doublex,doubley,doublez,doublew,doubleh,doubled){
returnwireBox(x,y,z,w,h,d,0,0,0);
}
/**
*Drawsawireframeboxat(x,y,z)withdimensions(w,h,d)andaxialrotations(xA,yA,zA).
*/
publicstaticShapewireBox(doublex,doubley,doublez,doublew,doubleh,doubled,doublexA,doubleyA,doublezA){
Appearanceap=createAppearance(null,false);
Vector3fdimensions=createVector3f(w,h,d);
com.sun.j3d.utils.geometry.Boxbox=new
com.sun.j3d.utils.geometry.Box(dimensions.x,dimensions.y,dimensions.z,PRIMFLAGS,ap,numDivisions);
returnprimitive(box,x,y,z,newVector3d(xA,yA,zA),null);
}
//*********************************************************************************************
/**
*Drawsacylinderat(x,y,z)withradiusrandheighth.
*/
publicstaticShapecylinder(doublex,doubley,doublez,doubler,doubleh){
returncylinder(x,y,z,r,h,0,0,0,null);
}
/**
*Drawsacylinderat(x,y,z)withradiusr,heighth,andaxialrotations(xA,yA,zA).
*/
publicstaticShapecylinder(doublex,doubley,doublez,doubler,doubleh,doublexA,doubleyA,doublezA){
returncylinder(x,y,z,r,h,xA,yA,zA,null);
}
/**
*Drawsacylinderat(x,y,z)withradiusr,heighth,andatexturefromimageURL.
*/
publicstaticShapecylinder(doublex,doubley,doublez,doubler,doubleh,StringimageURL){
returncylinder(x,y,z,r,h,0,0,0,imageURL);
}
/**
*Drawsacylinderat(x,y,z)withradiusr,heighth,axialrotations(xA,yA,zA),andatexturefromimageURL.
*/
publicstaticShapecylinder(doublex,doubley,doublez,doubler,doubleh,doublexA,doubleyA,doublezA,StringimageURL){
Appearanceap=createAppearance(imageURL,true);
Vector3fdimensions=createVector3f(r,h,0);
Cylindercyl=newCylinder(dimensions.x,dimensions.y,PRIMFLAGS,numDivisions,numDivisions,ap);
returnprimitive(cyl,x,y,z,newVector3d(xA,yA,zA),null);
}
/**
*Drawsawireframecylinderat(x,y,z)withradiusrandheighth.
*/
publicstaticShapewireCylinder(doublex,doubley,doublez,doubler,doubleh){
returnwireCylinder(x,y,z,r,h,0,0,0);
}
/**
*Drawsawireframecylinderat(x,y,z)withradiusr,heighth,andaxialrotations(xA,yA,zA).
*/
publicstaticShapewireCylinder(doublex,doubley,doublez,doubler,doubleh,doublexA,doubleyA,doublezA){
Appearanceap=createAppearance(null,false);
Vector3fdimensions=createVector3f(r,h,0);
Cylindercyl=newCylinder(dimensions.x,dimensions.y,PRIMFLAGS,numDivisions,numDivisions,ap);
returnprimitive(cyl,x,y,z,newVector3d(xA,yA,zA),null);
}
//*********************************************************************************************
/**
*Drawsaconeat(x,y,z)withradiusrandheighth.
*/
publicstaticShapecone(doublex,doubley,doublez,doubler,doubleh){
returncone(x,y,z,r,h,0,0,0,null);
}
/**
*Drawsaconeat(x,y,z)withradiusr,heighth,andaxialrotations(xA,yA,zA).
*/
publicstaticShapecone(doublex,doubley,doublez,doubler,doubleh,doublexA,doubleyA,doublezA){
returncone(x,y,z,r,h,xA,yA,zA,null);
}
/**
*Drawsaconeat(x,y,z)withradiusr,heighth,andatexturefromimageURL.
*/
publicstaticShapecone(doublex,doubley,doublez,doubler,doubleh,StringimageURL){
returncone(x,y,z,r,h,0,0,0,imageURL);
}
/**
*Drawsaconeat(x,y,z)withradiusr,heighth,axialrotations(xA,yA,zA),andatexturefromimageURL.
*/
publicstaticShapecone(doublex,doubley,doublez,doubler,doubleh,doublexA,doubleyA,doublezA,StringimageURL){
Appearanceap=createAppearance(imageURL,true);
Vector3fdimensions=createVector3f(r,h,0);
Conecone=newCone(dimensions.x,dimensions.y,PRIMFLAGS,numDivisions,numDivisions,ap);
returnprimitive(cone,x,y,z,newVector3d(xA,yA,zA),null);
}
/**
*Drawsawireframeconeat(x,y,z)withradiusrandheighth.
*/
publicstaticShapewireCone(doublex,doubley,doublez,doubler,doubleh){
returnwireCone(x,y,z,r,h,0,0,0);
}
/**
*Drawsawireframeconeat(x,y,z)withradiusr,heighth,andaxialrotations(xA,yA,zA).
*/
publicstaticShapewireCone(doublex,doubley,doublez,doubler,doubleh,doublexA,doubleyA,doublezA){
Appearanceap=createAppearance(null,false);
Vector3fdimensions=createVector3f(r,h,0);
Conecone=newCone(dimensions.x,dimensions.y,PRIMFLAGS,numDivisions,numDivisions,ap);
returnprimitive(cone,x,y,z,newVector3d(xA,yA,zA),null);
}
//*********************************************************************************************
/**
*DrawsaJava3DPrimitiveobjectat(x,y,z)withaxialrotations(xA,yA,zA).
*/
privatestaticShapeprimitive(Primitiveshape,doublex,doubley,doublez,Vector3dangles,Vector3dscales){
shape.setCapability(Primitive.ENABLE_APPEARANCE_MODIFY);
shape.setPickable(false);
shape.setCollidable(false);
TransformGrouptgScale=createTransformGroup();
Transform3DscaleTransform=newTransform3D();
if(scales!=null)
scaleTransform.setScale(scales);
tgScale.setTransform(scaleTransform);
tgScale.addChild(shape);
TransformGrouptgShape=createTransformGroup();
Transform3Dtransform=newTransform3D();
if(angles!=null){
angles.scale(Math.PI/180);
transform.setEuler(angles);
}
Vector3fvector=createVector3f(x,y,z);
transform.setTranslation(vector);
tgShape.setTransform(transform);
tgShape.addChild(tgScale);
BranchGroupbg=createBranchGroup();
bg.addChild(tgShape);
offscreenGroup.addChild(bg);
returnnewShape(bg,tgShape);
}
/****************************************************************
*Non-PrimitiveDrawingMethods*
*****************************************************************/
/**
*Drawsasinglepointat(x,y,z).
*/
publicstaticShapepoint(doublex,doubley,doublez){
returnpoints(newdouble[]{x},newdouble[]{y},newdouble[]{z});
}
/**
*Drawsasetofpointsatthegivencoordinates.Forexample,
*thefirstpointisat(x[0],y[0],z[0]).
*Muchmoreefficientthandrawingindividualpoints.
*/
publicstaticShapepoints(double[]x,double[]y,double[]z){
Point3f[]coords=constructPoint3f(x,y,z);
GeometryArraygeom=newPointArray(coords.length,PointArray.COORDINATES);
geom.setCoordinates(0,coords);
Shape3Dshape=createShape3D(geom);
returnshape(shape);
}
/**
*Drawsasetofpointsatthegivencoordinateswiththegivencolors.
*Forexample,thefirstpointisat(x[0],y[0],z[0])withcolorcolors[0].
*Muchmoreefficientthandrawingindividualpoints.
*/
publicstaticShapepoints(double[]x,double[]y,double[]z,Color[]colors){
Point3f[]coords=constructPoint3f(x,y,z);
GeometryArraygeom=newPointArray(coords.length,PointArray.COORDINATES|PointArray.COLOR_4);
geom.setCoordinates(0,coords);
for(inti=0;i<x.length;i++)
geom.setColor(i,colors[i].getComponents(null));
Shape3Dshape=createShape3D(geom);
returncustomShape(shape);
}
//*********************************************************************************************
/**
*Drawsasinglelinefrom(x1,y1,z1)to(x2,y2,z2).
*/
publicstaticShapeline(doublex1,doubley1,doublez1,doublex2,doubley2,doublez2){
returnlines(newdouble[]{x1,x2},newdouble[]{y1,y2},newdouble[]{z1,z2});
}
/**
*Drawsasetofconnectedlines.Forexample,thefirstlineisfrom(x[0],y[0],z[0])to
*(x[1],y[1],z[1]),andthesecondlineisfrom(x[1],y[1],z[1])to(x[2],y[2],z[2]).
*Muchmoreefficientthandrawingindividuallines.
*/
publicstaticShapelines(double[]x,double[]y,double[]z){
Point3f[]coords=constructPoint3f(x,y,z);
GeometryArraygeom=newLineStripArray
(coords.length,LineArray.COORDINATES,newint[]{coords.length});
geom.setCoordinates(0,coords);
Shape3Dshape=createShape3D(geom);
returnshape(shape);
}
/**
*Drawsasetofconnectedlines.Forexample,thefirstlineisfrom(x[0],y[0],z[0])to
*(x[1],y[1],z[1]),andthesecondlineisfrom(x[1],y[1],z[1])to(x[2],y[2],z[2]).
*Muchmoreefficientthandrawingindividuallines.Vertexcolorsarespecifiedbythegiven
*array,andlinecolorsareblendsofitstwovertexcolors.
*/
publicstaticShapelines(double[]x,double[]y,double[]z,Color[]colors){
Point3f[]coords=constructPoint3f(x,y,z);
GeometryArraygeom=newLineStripArray
(coords.length,LineArray.COORDINATES|LineArray.COLOR_4,newint[]{coords.length});
geom.setCoordinates(0,coords);
for(inti=0;i<x.length;i++)
geom.setColor(i,colors[i].getComponents(null));
Shape3Dshape=createShape3D(geom);
returncustomShape(shape);
}
/**
*Drawsacylindricaltubeofradiusrfromvertex(x1,y1,z1)tovertex(x2,y2,z2).
*/
publicstaticShapetube(doublex1,doubley1,doublez1,doublex2,doubley2,doublez2,doubler){
Vector3Dmid=newVector3D(x1+x2,y1+y2,z1+z2).times(0.5);
Vector3Dline=newVector3D(x2-x1,y2-y1,z2-z1);
Shapes=cylinder(mid.x,mid.y,mid.z,r,line.mag());
Vector3DyAxis=newVector3D(0,1,0);
Vector3Dcross=line.cross(yAxis);
doubleangle=line.angle(yAxis);
s.rotateAxis(cross,-angle);
returncombine(s);
}
/**
*Drawsaseriesofcylindricaltubesofradiusr,withvertices(x,y,z).
*/
publicstaticShapetubes(double[]x,double[]y,double[]z,doubler){
StdDraw3D.Shape[]shapes=newStdDraw3D.Shape[(x.length-1)*2];
for(inti=0;i<x.length-1;i++){
shapes[i]=tube(x[i],y[i],z[i],x[i+1],y[i+1],z[i+1],r);
shapes[i+x.length-1]=sphere(x[i+1],y[i+1],z[i+1],r);
}
returncombine(shapes);
}
/**
*Drawsaseriesofcylindricaltubesofradiusr,withvertices(x,y,z)andthegivencolors.
*Nomoreefficientthandrawingindividualtubes.
*/
publicstaticShapetubes(double[]x,double[]y,double[]z,doubler,Color[]colors){
StdDraw3D.Shape[]shapes=newStdDraw3D.Shape[(x.length-1)*2];
for(inti=0;i<x.length-1;i++){
StdDraw3D.setPenColor(colors[i]);
shapes[i]=tube(x[i],y[i],z[i],x[i+1],y[i+1],z[i+1],r);
shapes[i+x.length-1]=sphere(x[i+1],y[i+1],z[i+1],r);
}
returncombine(shapes);
}
//*********************************************************************************************
/**
*Drawsafilledpolygonwiththegivenvertices.Theverticesshouldbeplanarfora
*proper2Dpolygontobedrawn.
*/
publicstaticShapepolygon(double[]x,double[]y,double[]z){
returnpolygon(x,y,z,true);
}
/**
*Drawsthetriangulatedoutlineofapolygonwiththegivenvertices.
*/
publicstaticShapewirePolygon(double[]x,double[]y,double[]z){
returnpolygon(x,y,z,false);
}
/**
*Drawsapolygonwiththegivenvertices,whichisfilledoroutlinedbasedontheargument.
*
*@paramfilledIsthepolygonfilled?
*/
privatestaticShapepolygon(double[]x,double[]y,double[]z,booleanfilled){
Point3f[]coords=constructPoint3f(x,y,z);
GeometryArraygeom=newTriangleFanArray(coords.length,LineArray.COORDINATES,newint[]{coords.length});
geom.setCoordinates(0,coords);
GeometryInfogeoinfo=newGeometryInfo((GeometryArray)geom);
NormalGeneratornormalGenerator=newNormalGenerator();
normalGenerator.generateNormals(geoinfo);
Shape3Dshape=createShape3D(geoinfo.getIndexedGeometryArray());
if(filled)
returnshape(shape);
else
returnwireShape(shape);
}
//*********************************************************************************************
/**
*Drawstriangleswhicharedefinedbyx1=points[i][0],y1=points[i][1],z1=points[i][2],x2=points[i][3],etc.
*AllofthepointswillbethewidthandcolorspecifiedbythesetPenColorandsetPenWidthmethods.
*@parampointsanarrayofthepointstobeconnected.Thefirstdimensionis
*unspecified,buttheseconddimensionshouldbe9(the3-spacecoordinatesofeachvertex)
*/
publicstaticShapetriangles(double[][]points){
returntriangles(points,true);
}
publicstaticShapewireTriangles(double[][]points){
returntriangles(points,false);
}
privatestaticShapetriangles(double[][]points,booleanfilled){
intsize=points.length;
Point3f[]coords=newPoint3f[size*3];
for(inti=0;i<size;i++){
coords[3*i]=newPoint3f(createVector3f(points[i][0],points[i][1],points[i][2]));
coords[3*i+1]=newPoint3f(createVector3f(points[i][3],points[i][4],points[i][5]));
coords[3*i+2]=newPoint3f(createVector3f(points[i][6],points[i][7],points[i][8]));
}
GeometryArraygeom=newTriangleArray(size*3,TriangleArray.COORDINATES);
geom.setCoordinates(0,coords);
GeometryInfogeoinfo=newGeometryInfo(geom);
NormalGeneratornormalGenerator=newNormalGenerator();
normalGenerator.generateNormals(geoinfo);
Shape3Dshape=createShape3D(geoinfo.getIndexedGeometryArray());
if(filled)
returnshape(shape);
else
returnwireShape(shape);
}
/**
*Drawsasetoftriangles,eachwiththespecifiedcolor.Thereshouldbeone
*colorforeachtriangle.Thisismuchmoreefficientthandrawingindividual
*triangles.
*/
publicstaticShapetriangles(double[][]points,Color[]colors){
returntriangles(points,colors,true);
}
/**
*Drawsasetofwireframetriangles,eachwiththespecifiedcolor.Thereshouldbeone
*colorforeachtriangle.Thisismuchmoreefficientthandrawingindividual
*triangles.
*/
publicstaticShapewireTriangles(double[][]points,Color[]colors){
returntriangles(points,colors,false);
}
privatestaticShapetriangles(double[][]points,Color[]colors,booleanfilled){
intsize=points.length;
Point3f[]coords=newPoint3f[size*3];
for(inti=0;i<size;i++){
coords[3*i]=newPoint3f(createVector3f(points[i][0],points[i][1],points[i][2]));
coords[3*i+1]=newPoint3f(createVector3f(points[i][3],points[i][4],points[i][5]));
coords[3*i+2]=newPoint3f(createVector3f(points[i][6],points[i][7],points[i][8]));
}
GeometryArraygeom=newTriangleArray(size*3,TriangleArray.COORDINATES|TriangleArray.COLOR_4);
geom.setCoordinates(0,coords);
for(inti=0;i<colors.length;i++){
geom.setColor(3*i+0,colors[i].getComponents(null));
geom.setColor(3*i+1,colors[i].getComponents(null));
geom.setColor(3*i+2,colors[i].getComponents(null));
}
GeometryInfogeoinfo=newGeometryInfo(geom);
NormalGeneratornormalGenerator=newNormalGenerator();
normalGenerator.generateNormals(geoinfo);
Shape3Dshape=createShape3D(geoinfo.getIndexedGeometryArray());
if(filled)
returnshape(shape);
else
returnwireShape(shape);
}
//*********************************************************************************************
/**
*Drawsa3Dtextobjectat(x,y,z).Usesthepenfont,color,andtransparency.
*/
publicstaticShapetext3D(doublex,doubley,doublez,Stringtext){
returntext3D(x,y,z,text,0,0,0);
}
/**
*Drawsa3Dtextobjectat(x,y,z)withEulerrotationangles(xA,yA,zA).
*Usesthepenfont,color,andtransparency.
*/
publicstaticShapetext3D(doublex,doubley,doublez,Stringtext,doublexA,doubleyA,doublezA){
Line2D.Doubleline=newLine2D.Double(0,0,TEXT3D_DEPTH,0);
FontExtrusionextrudePath=newFontExtrusion(line);
Font3Dfont3D=newFont3D(font,extrudePath);
Point3dpos=newPoint3d(x,y,z);
javax.media.j3d.Text3Dt=newjavax.media.j3d.Text3D(font3D,text,createPoint3f(x,y,z));
//FIXTHISTONOTHAVESCALEINCLUDED
Transform3Dshrinker=newTransform3D();
shrinker.setEuler(newVector3d(xA,yA,zA));
shrinker.setTranslation(newVector3d(x,y,z));
shrinker.setScale(TEXT3D_SHRINK_FACTOR);
Shape3Dshape=createShape3D((Geometry)t);
returnshape(shape,true,shrinker,false);
}
//*************************************************************************
/**
*ConstructsaPoint3farrayfromthegivencoordinatearrays.
*/
privatestaticPoint3f[]constructPoint3f(double[]x,double[]y,double[]z){
intsize=x.length;
Point3f[]coords=newPoint3f[size];
for(inti=0;i<size;i++)
coords[i]=newPoint3f(createVector3f(x[i],y[i],z[i]));
returncoords;
}
/**
*Drawsa.plyfilefromafilenameorwebsitename.
*/
privatestaticShapedrawPLY(Stringfilename,booleancolored){
Scannerscanner=createScanner(filename);
intvertices=-1;
inttriangles=-1;
intproperties=-1;
while(true){
Strings=scanner.next();
if(s.equals("vertex"))
vertices=scanner.nextInt();
elseif(s.equals("face"))
triangles=scanner.nextInt();
elseif(s.equals("property")){
properties++;
scanner.next();
scanner.next();
}
elseif(s.equals("end_header"))
break;
}
System.out.println(vertices+""+triangles+""+properties);
if((vertices==-1)||(triangles==-1)||(properties==-1))
thrownewRuntimeException("Cannotreadformatof.plyfile!");
double[][]parameters=newdouble[properties][vertices];
for(inti=0;i<vertices;i++){
if((i%10000)==0)
System.out.println("vertex"+i);
for(intj=0;j<properties;j++){
parameters[j][i]=scanner.nextDouble();
}
}
double[][]points=newdouble[triangles][9];
for(inti=0;i<triangles;i++){
intedges=scanner.nextInt();
if(edges!=3)
thrownewRuntimeException("Onlytriangularfacessupported!");
if((i%10000)==0)
System.out.println("face"+i);
intindex=scanner.nextInt();
points[i][0]=parameters[0][index];
points[i][1]=parameters[1][index];
points[i][2]=parameters[2][index];
index=scanner.nextInt();
points[i][3]=parameters[0][index];
points[i][4]=parameters[1][index];
points[i][5]=parameters[2][index];
index=scanner.nextInt();
points[i][6]=parameters[0][index];
points[i][7]=parameters[1][index];
points[i][8]=parameters[2][index];
}
returntriangles(points);
}
privatestaticShapedrawLWS(Stringfilename){
Lw3dLoaderloader=newLw3dLoader();
try{
BranchGroupbg=loader.load(filename).getSceneGroup();
bg.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
bg.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
bg.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
bg.setCapability(BranchGroup.ALLOW_DETACH);
TransformGrouptransGroup=newTransformGroup();
transGroup.addChild(bg);
BranchGroupbg2=createBranchGroup();
bg2.addChild(transGroup);
offscreenGroup.addChild(bg2);
returnnewShape(bg2,transGroup);
}catch(FileNotFoundExceptionfnfe){fnfe.printStackTrace();}
returnnull;
}
privatestaticShapedrawOBJ(Stringfilename,booleancolored,booleanresize){
intparams=0;
if(resize)params=ObjectFile.RESIZE|Loader.LOAD_ALL;
ObjectFileloader=newObjectFile(params);
try{
BranchGroupbg=loader.load(filename).getSceneGroup();
bg.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
bg.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
bg.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
bg.setCapability(BranchGroup.ALLOW_DETACH);
//System.out.println("Children:"+bg.numChildren());
for(inti=0;i<bg.numChildren();i++){
Nodechild=bg.getChild(i);
if(childinstanceofShape3D){
Shape3Dshape=(Shape3D)child;
//System.out.println("shape3d");
//Appearanceap=shape.getAppearance();
//PolygonAttributespa=ap.getPolygonAttributes();
//if(pa==null)pa=newPolygonAttributes();
//pa.setCullFace(PolygonAttributes.CULL_NONE);
//ap.setPolygonAttributes(pa);
//Materialm=ap.getMaterial();
//m.setSpecularColor(newColor3f(GRAY));
//m.setShininess(64);
if(colored)
shape.setAppearance(createAppearance(null,true));
else{
Appearanceap=shape.getAppearance();
PolygonAttributespa=ap.getPolygonAttributes();
if(pa==null)pa=newPolygonAttributes();
pa.setCullFace(PolygonAttributes.CULL_NONE);
ap.setPolygonAttributes(pa);
}
//for(intj=0;j<shape.numGeometries();j++){
//Geometryg=shape.getGeometry(j);
//if(ginstanceofGeometryArray){
//GeometryArrayga=(GeometryArray)g;
//System.out.println("GeometryArray");
//System.out.println("format:"+ga.getVertexFormat());
//float[]colors=ga.getInterleavedVertices();
//for(intk=0;k<colors.length;k++)
//System.out.println(colors[k]);
//}
//}
}
}
TransformGrouptransGroup=newTransformGroup();
transGroup.addChild(bg);
BranchGroupbg2=createBranchGroup();
bg2.addChild(transGroup);
offscreenGroup.addChild(bg2);
returnnewShape(bg2,transGroup);
}catch(FileNotFoundExceptionfnfe){fnfe.printStackTrace();}
returnnull;
}
publicstaticShapemodel(Stringfilename){
returnmodel(filename,false);
}
publicstaticShapemodel(Stringfilename,booleanresize){
returnmodel(filename,false,resize);
}
publicstaticShapecoloredModel(Stringfilename){
returnmodel(filename,true,true);
}
publicstaticShapecoloredModel(Stringfilename,booleanresize){
returnmodel(filename,true,resize);
}
privatestaticShapemodel(Stringfilename,booleancolored,booleanresize){
if(filename==null)returnnull;
Stringsuffix=filename.substring(filename.lastIndexOf('.')+1);
Stringextension=suffix.toLowerCase();
if(suffix.equals("ply"))
returndrawPLY(filename,colored);
elseif(suffix.equals("obj"))
returndrawOBJ(filename,colored,resize);
//elseif(suffix.equals("lws"))
//returndrawLWS(filename);
else
thrownewRuntimeException("Formatnotsupported!");
}
/**
*DrawsaJava3DShape3Dobjectandfillsitin.
*
*@paramshapeTheShape3Dobjecttobedrawn.
*/
privatestaticShapeshape(Shape3Dshape){
returnshape(shape,true,null,false);
}
/**
*DrawsawireframeJava3DShape3Dobjectandfillsitin.
*
*@paramshapeTheShape3Dobjecttobedrawn.
*/
privatestaticShapewireShape(Shape3Dshape){
returnshape(shape,false,null,false);
}
privatestaticShapecustomShape(Shape3Dshape){
returnshape(shape,true,null,true);
}
privatestaticShapecustomWireShape(Shape3Dshape){
returnshape(shape,false,null,true);
}
/**
*DrawsaJava3DShape3Dobjectwiththegivenproperties.
*
*@parampolygonFillPolygonfillproperties,specifiedbyJava3D.
*/
privatestaticShapeshape(Shape3Dshape,booleanfill,Transform3Dtransform,booleancustom){
Appearanceap;
if(custom)ap=createCustomAppearance(fill);
elseap=createAppearance(null,fill);
shape.setAppearance(ap);
TransformGrouptransGroup=newTransformGroup();
if(transform!=null)
transGroup.setTransform(transform);
transGroup.addChild(shape);
BranchGroupbg=createBranchGroup();
bg.addChild(transGroup);
offscreenGroup.addChild(bg);
returnnewShape(bg,transGroup);
}
/****************************************************************
*2DOverlayDrawingMethods*
*****************************************************************/
/**
*Drawsonepixelat(x,y).
*/
publicstaticvoidoverlayPixel(doublex,doubley){
getGraphics2D(offscreenImage).fillRect((int)Math.round(scaleX(x)),(int)Math.round(scaleY(y)),1,1);
}
/**
*Drawsapointat(x,y).
*/
publicstaticvoidoverlayPoint(doublex,doubley){
floatr=penRadius;
if(r<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).fill(newEllipse2D.Double(scaleX(x)-r/2,scaleY(y)-r/2,r,r));
}
/**
*Drawsalinefrom(x0,y0)to(x1,y1).
*/
publicstaticvoidoverlayLine(doublex0,doubley0,doublex1,doubley1){
getGraphics2D(offscreenImage).draw(newLine2D.Double(scaleX(x0),scaleY(y0),scaleX(x1),scaleY(y1)));
}
/**
*Drawsacircleofradiusr,centeredon(x,y).
*/
publicstaticvoidoverlayCircle(doublex,doubley,doubler){
if(r<0)thrownewRuntimeException("circleradiuscan'tbenegative");
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(2*r);
doublehs=factorY(2*r);
if(ws<=1&&hs<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).draw(newEllipse2D.Double(xs-ws/2,ys-hs/2,ws,hs));
}
/**
*Drawsafilledcircleofradiusr,centeredon(x,y).
*/
publicstaticvoidoverlayFilledCircle(doublex,doubley,doubler){
if(r<0)thrownewRuntimeException("circleradiuscan'tbenegative");
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(2*r);
doublehs=factorY(2*r);
if(ws<=1&&hs<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).fill(newEllipse2D.Double(xs-ws/2,ys-hs/2,ws,hs));
}
/**
*Drawsanellipsewithgivensemimajorandsemiminoraxes,centeredon(x,y).
*/
publicstaticvoidoverlayEllipse(doublex,doubley,doublesemiMajorAxis,doublesemiMinorAxis){
if(semiMajorAxis<0)thrownewRuntimeException("ellipsesemimajoraxiscan'tbenegative");
if(semiMinorAxis<0)thrownewRuntimeException("ellipsesemiminoraxiscan'tbenegative");
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(2*semiMajorAxis);
doublehs=factorY(2*semiMinorAxis);
if(ws<=1&&hs<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).draw(newEllipse2D.Double(xs-ws/2,ys-hs/2,ws,hs));
}
/**
*Drawsafilledellipsewithgivensemimajorandsemiminoraxes,centeredon(x,y).
*/
publicstaticvoidoverlayFilledEllipse(doublex,doubley,doublesemiMajorAxis,doublesemiMinorAxis){
if(semiMajorAxis<0)thrownewRuntimeException("ellipsesemimajoraxiscan'tbenegative");
if(semiMinorAxis<0)thrownewRuntimeException("ellipsesemiminoraxiscan'tbenegative");
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(2*semiMajorAxis);
doublehs=factorY(2*semiMinorAxis);
if(ws<=1&&hs<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).fill(newEllipse2D.Double(xs-ws/2,ys-hs/2,ws,hs));
}
/**
*Drawsanarcofradiusr,centeredon(x,y),fromangle1toangle2(indegrees).
*/
publicstaticvoidoverlayArc(doublex,doubley,doubler,doubleangle1,doubleangle2){
if(r<0)thrownewRuntimeException("arcradiuscan'tbenegative");
while(angle2<angle1)angle2+=360;
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(2*r);
doublehs=factorY(2*r);
if(ws<=1&&hs<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).draw(newArc2D.Double(xs-ws/2,ys-hs/2,ws,hs,angle1,angle2-angle1,Arc2D.OPEN));
}
/**
*Drawsasquareofsidelength2r,centeredon(x,y).
*/
publicstaticvoidoverlaySquare(doublex,doubley,doubler){
if(r<0)thrownewRuntimeException("squaresidelengthcan'tbenegative");
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(2*r);
doublehs=factorY(2*r);
if(ws<=1&&hs<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).draw(newRectangle2D.Double(xs-ws/2,ys-hs/2,ws,hs));
}
/**
*Drawsafilledsquareofsidelength2r,centeredon(x,y).
*/
publicstaticvoidoverlayFilledSquare(doublex,doubley,doubler){
if(r<0)thrownewRuntimeException("squaresidelengthcan'tbenegative");
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(2*r);
doublehs=factorY(2*r);
if(ws<=1&&hs<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).fill(newRectangle2D.Double(xs-ws/2,ys-hs/2,ws,hs));
}
/**
*Drawsarectangleofgivenhalfwidthandhalfheight,centeredon(x,y).
*/
publicstaticvoidoverlayRectangle(doublex,doubley,doublehalfWidth,doublehalfHeight){
if(halfWidth<0)thrownewRuntimeException("halfwidthcan'tbenegative");
if(halfHeight<0)thrownewRuntimeException("halfheightcan'tbenegative");
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(2*halfWidth);
doublehs=factorY(2*halfHeight);
if(ws<=1&&hs<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).draw(newRectangle2D.Double(xs-ws/2,ys-hs/2,ws,hs));
}
/**
*Drawsafilledrectangleofgivenhalfwidthandhalfheight,centeredon(x,y).
*/
publicstaticvoidoverlayFilledRectangle(doublex,doubley,doublehalfWidth,doublehalfHeight){
if(halfWidth<0)thrownewRuntimeException("halfwidthcan'tbenegative");
if(halfHeight<0)thrownewRuntimeException("halfheightcan'tbenegative");
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(2*halfWidth);
doublehs=factorY(2*halfHeight);
if(ws<=1&&hs<=1)overlayPixel(x,y);
elsegetGraphics2D(offscreenImage).fill(newRectangle2D.Double(xs-ws/2,ys-hs/2,ws,hs));
}
/**
*Drawsapolygonwiththegiven(x[i],y[i])coordinates.
*/
publicstaticvoidoverlayPolygon(double[]x,double[]y){
intN=x.length;
GeneralPathpath=newGeneralPath();
path.moveTo((float)scaleX(x[0]),(float)scaleY(y[0]));
for(inti=0;i<N;i++)
path.lineTo((float)scaleX(x[i]),(float)scaleY(y[i]));
path.closePath();
getGraphics2D(offscreenImage).draw(path);
}
/**
*Drawsafilledpolygonwiththegiven(x[i],y[i])coordinates.
*/
publicstaticvoidoverlayFilledPolygon(double[]x,double[]y){
intN=x.length;
GeneralPathpath=newGeneralPath();
path.moveTo((float)scaleX(x[0]),(float)scaleY(y[0]));
for(inti=0;i<N;i++)
path.lineTo((float)scaleX(x[i]),(float)scaleY(y[i]));
path.closePath();
getGraphics2D(offscreenImage).fill(path);
}
/**
*Drawsthegiventextasstationaryonthewindowat(x,y).
*ThisisusefulfortitlesandHUD-styletext.
*/
publicstaticvoidoverlayText(doublex,doubley,Stringtext){
Graphics2Dgraphics=getGraphics2D(offscreenImage);
FontMetricsmetrics=graphics.getFontMetrics();
doublexs=scaleX(x);
doubleys=scaleY(y);
intws=metrics.stringWidth(text);
inths=metrics.getDescent();
graphics.drawString(text,(float)(xs-ws/2.0),(float)(ys+hs));
}
/**
*Writesthegiventextstringinthecurrentfont,centeredon(x,y)and
*rotatedbythespecifiednumberofdegrees.
*/
publicstaticvoidoverlayText(doublex,doubley,Stringtext,doubledegrees){
Graphics2Dgraphics=getGraphics2D(offscreenImage);
FontMetricsmetrics=graphics.getFontMetrics();
doublexs=scaleX(x);
doubleys=scaleY(y);
intws=metrics.stringWidth(text);
inths=metrics.getDescent();
graphics.rotate(Math.toRadians(-degrees),xs,ys);
graphics.drawString(text,(float)(xs-ws/2.0),(float)(ys+hs));
graphics.rotate(Math.toRadians(+degrees),xs,ys);
}
/**
*Writethegiventextstringinthecurrentfont,left-alignedat(x,y).
*/
publicstaticvoidoverlayTextLeft(doublex,doubley,Stringtext){
Graphics2Dgraphics=getGraphics2D(offscreenImage);
FontMetricsmetrics=graphics.getFontMetrics();
doublexs=scaleX(x);
doubleys=scaleY(y);
intws=metrics.stringWidth(text);
inths=metrics.getDescent();
graphics.drawString(text,(float)(xs),(float)(ys+hs));
}
/**
*Writethegiventextstringinthecurrentfont,right-alignedat(x,y).
*/
publicstaticvoidoverlayTextRight(doublex,doubley,Stringtext){
Graphics2Dgraphics=getGraphics2D(offscreenImage);
FontMetricsmetrics=graphics.getFontMetrics();
doublexs=scaleX(x);
doubleys=scaleY(y);
intws=metrics.stringWidth(text);
inths=metrics.getDescent();
graphics.drawString(text,(float)(xs-ws),(float)(ys+hs));
}
/**
*Drawsapicture(gif,jpg,orpng)centeredon(x,y).
*/
publicstaticvoidoverlayPicture(doublex,doubley,Strings){
Imageimage=getImage(s);
doublexs=scaleX(x);
doubleys=scaleY(y);
intws=image.getWidth(null);
inths=image.getHeight(null);
if(ws<0||hs<0)thrownewRuntimeException("image"+s+"iscorrupt");
getGraphics2D(offscreenImage).drawImage(image,(int)Math.round(xs-ws/2.0),(int)Math.round(ys-hs/2.0),null);
}
/**
*Drawsapicture(gif,jpg,orpng)centeredon(x,y),
*rotatedgivennumberofdegrees.
*/
publicstaticvoidoverlayPicture(doublex,doubley,Strings,doubledegrees){
Imageimage=getImage(s);
doublexs=scaleX(x);
doubleys=scaleY(y);
intws=image.getWidth(null);
inths=image.getHeight(null);
if(ws<0||hs<0)thrownewRuntimeException("image"+s+"iscorrupt");
Graphics2Dgraphics=getGraphics2D(offscreenImage);
graphics.rotate(Math.toRadians(-degrees),xs,ys);
graphics.drawImage(image,(int)Math.round(xs-ws/2.0),(int)Math.round(ys-hs/2.0),null);
graphics.rotate(Math.toRadians(+degrees),xs,ys);
}
/**
*Drawpicture(gif,jpg,orpng)centeredon(x,y),rescaledtow-by-h.
*/
publicstaticvoidoverlayPicture(doublex,doubley,Strings,doublew,doubleh){
Imageimage=getImage(s);
doublexs=scaleX(x);
doubleys=scaleY(y);
if(w<0)thrownewRuntimeException("widthisnegative:"+w);
if(h<0)thrownewRuntimeException("heightisnegative:"+h);
doublews=factorX(w);
doublehs=factorY(h);
if(ws<0||hs<0)thrownewRuntimeException("image"+s+"iscorrupt");
if(ws<=1&&hs<=1)overlayPixel(x,y);
else{
getGraphics2D(offscreenImage).drawImage(image,(int)Math.round(xs-ws/2.0),
(int)Math.round(ys-hs/2.0),
(int)Math.round(ws),
(int)Math.round(hs),null);
}
}
/**
*Drawpicture(gif,jpg,orpng)centeredon(x,y),rotated
*givennumberofdegrees,rescaledtow-by-h.
*/
publicstaticvoidoverlayPicture(doublex,doubley,Strings,doublew,doubleh,doubledegrees){
Imageimage=getImage(s);
doublexs=scaleX(x);
doubleys=scaleY(y);
doublews=factorX(w);
doublehs=factorY(h);
if(ws<0||hs<0)thrownewRuntimeException("image"+s+"iscorrupt");
if(ws<=1&&hs<=1)overlayPixel(x,y);
Graphics2Dgraphics=getGraphics2D(offscreenImage);
graphics.rotate(Math.toRadians(-degrees),xs,ys);
graphics.drawImage(image,(int)Math.round(xs-ws/2.0),
(int)Math.round(ys-hs/2.0),
(int)Math.round(ws),
(int)Math.round(hs),null);
graphics.rotate(Math.toRadians(+degrees),xs,ys);
}
/**
*Getsanimagefromthegivenfilename.
*/
privatestaticImagegetImage(Stringfilename){
//toreadfromfile
ImageIconicon=newImageIcon(filename);
//trytoreadfromURL
if((icon==null)||(icon.getImageLoadStatus()!=MediaTracker.COMPLETE)){
try{
URLurl=newURL(filename);
icon=newImageIcon(url);
}catch(Exceptione){/*notaurl*/}
}
//incasefileisinsidea.jar
if((icon==null)||(icon.getImageLoadStatus()!=MediaTracker.COMPLETE)){
URLurl=StdDraw3D.class.getResource(filename);
if(url==null)thrownewRuntimeException("image"+filename+"notfound");
icon=newImageIcon(url);
}
returnicon.getImage();
}
privatestaticGraphics2DgetGraphics2D(BufferedImageimage){
Graphics2Dgraphics=(Graphics2D)image.getGraphics();
graphics.setColor(penColor);
graphics.setFont(font);
BasicStrokestroke=newBasicStroke(penRadius,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
graphics.setStroke(stroke);
//if(getAntiAliasing())
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
returngraphics;
}
privatestaticvoidinfoDisplay(){
if(!infoDisplay){
infoImage=createBufferedImage();
return;
}
BufferedImagebi=createBufferedImage();
Graphics2Dg=(Graphics2D)bi.getGraphics();
g.setFont(newFont("Courier",Font.PLAIN,11));
g.setStroke(newBasicStroke(
1.0f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
doublecenter=(min+max)/2;
doubler=zoom;
doubleb=zoom*0.1f;
DecimalFormatdf=newDecimalFormat("0.000;-0.000");
Vector3Dpos=camera.getPosition();
Strings="("+df.format(pos.x)+","+df.format(pos.y)+","+df.format(pos.z)+")";
g.setColor(BLACK);
g.drawString("Position:"+s,21,26);
g.setColor(LIGHT_GRAY);
g.drawString("Position:"+s,20,25);
Vector3Drot=camera.getOrientation();
Strings2="("+df.format(rot.x)+","+df.format(rot.y)+","+df.format(rot.z)+")";
g.setColor(BLACK);
g.drawString("Rotation:"+s2,21,41);
g.setColor(LIGHT_GRAY);
g.drawString("Rotation:"+s2,20,40);
Stringmode;
if(cameraMode==ORBIT_MODE)mode="Camera:ORBIT_MODE";
elseif(cameraMode==FPS_MODE)mode="Camera:FPS_MODE";
elseif(cameraMode==AIRPLANE_MODE)mode="Camera:AIRPLANE_MODE";
elseif(cameraMode==LOOK_MODE)mode="Camera:LOOK_MODE";
elseif(cameraMode==FIXED_MODE)mode="Camera:FIXED_MODE";
elsethrownewRuntimeException("Unknowncameramode!");
g.setColor(BLACK);
g.drawString(mode,21,56);
g.setColor(LIGHT_GRAY);
g.drawString(mode,20,55);
doubled=b/4;
g.draw(newLine2D.Double(scaleX(d+center),scaleY(0+center),scaleX(-d+center),scaleY(0+center)));
g.draw(newLine2D.Double(scaleX(0+center),scaleY(d+center),scaleX(0+center),scaleY(-d+center)));
infoImage=bi;
}
/****************************************************************
*Saving/LoadingMethods*
*****************************************************************/
/**
*Savestofile-suffixmustbepng,jpg,orgif.gif??
*
*@paramfilenameThenameofthefilewithoneoftherequiredsuffixes.
*/
publicstaticvoidsave(Stringfilename){
//canvas.setVisible(false);
intoldCameraMode=getCameraMode();
setCameraMode(FIXED_MODE);
GraphicsContext3Dcontext=canvas.getGraphicsContext3D();
BufferedImagebuf=createBufferedImage();
ImageComponent2DimageComp=newImageComponent2D(ImageComponent.FORMAT_RGB,buf);
javax.media.j3d.Rasterras=newjavax.media.j3d.Raster(
newPoint3f(-1.0f,-1.0f,-1.0f),
javax.media.j3d.Raster.RASTER_COLOR,
0,0,
width,height,
imageComp,null);
context.readRaster(ras);
BufferedImageimage=(ras.getImage()).getImage();
Filefile=newFile(filename);
Stringsuffix=filename.substring(filename.lastIndexOf('.')+1);
Stringextension=suffix.toLowerCase();
//pngfiles
if(extension.equals("png")){
try{ImageIO.write(image,suffix,file);}
catch(IOExceptione){e.printStackTrace();}
}
//needtochangefromARGBtoRGBforjpeg
//reference:http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727
elseif(extension.equals("jpg")){
WritableRasterraster=image.getRaster();
WritableRasternewRaster;
newRaster=raster.createWritableChild(0,0,width,height,0,0,newint[]{0,1,2});
BufferedImagergbBuffer=newBufferedImage(image.getColorModel(),newRaster,false,null);
try{ImageIO.write(rgbBuffer,suffix,file);}
catch(IOExceptione){e.printStackTrace();}
}
else{
System.out.println("Invalidimagefiletype:"+suffix);
}
setCameraMode(oldCameraMode);
//canvas.setVisible(true);
}
publicstaticvoidsaveScene3D(Stringfilename){
Filefile=newFile(filename);
//System.out.println("on:"+onscreenGroup.numChildren()+"off:"+offscreenGroup.numChildren());
try{
SceneGraphFileWriterwriter=newSceneGraphFileWriter(file,universe,false,"3DscenesavedfromStdDraw3D.",null);
writer.writeBranchGraph(offscreenGroup);
writer.close();
System.out.println("Scenesuccessfullywrittento"+filename+"!");
}
catch(IOExceptionioe){ioe.printStackTrace();}
catch(UnsupportedUniverseExceptionuue){uue.printStackTrace();}
//catch(NamedObjectExceptionnoe){noe.printStackTrace();}
}
publicstaticvoidloadScene3D(Stringfilename){
Filefile=newFile(filename);
try{
SceneGraphFileReaderreader=newSceneGraphFileReader(file);
System.out.println("Branchgraphcount="+reader.getBranchGraphCount());
//BranchGroup[]bgs=reader.readAllBranchGraphs();
//BranchGroupbg=(BranchGroup)reader.getNamedObject("rendered");
BranchGroupbg=reader.readBranchGraph(0)[0];
offscreenGroup=bg;
//reader.dereferenceBranchGraph(offscreenGroup);
System.out.println("Scenesuccessfullyloadedfrom"+filename+"!");
}
catch(IOExceptionioe){ioe.printStackTrace();}
//catch(ObjectNotLoadedExceptiononle){onle.printStackTrace();}
//catch(NamedObjectExceptionnoe){noe.printStackTrace();}
}
/****************************************************************
*ShapeMethods*
*****************************************************************/
/**
*Combinesanynumberofshapesintooneshapeandreturnsit.
*/
publicstaticShapecombine(Shape...shapes){
BranchGroupcombinedGroup=createBranchGroup();
TransformGroupcombinedTransform=newTransformGroup();
for(inti=0;i<shapes.length;i++){
BranchGroupbg=shapes[i].bg;
TransformGrouptg=shapes[i].tg;
offscreenGroup.removeChild(bg);
onscreenGroup.removeChild(bg);
bg.removeChild(tg);
combinedTransform.addChild(shapes[i].tg);
}
combinedGroup.addChild(combinedTransform);
offscreenGroup.addChild(combinedGroup);
returnnewShape(combinedGroup,combinedTransform);
}
/**
*ReturnsanidenticalcopyofaShapethatcanbecontrolledindependently.
*Muchmoreefficientthanredrawingaspecificshapeormodel.
*/
publicstaticShapecopy(Shapeshape){
TransformGrouptg=shape.tg;
BranchGroupbg=shape.bg;
TransformGrouptg2=(TransformGroup)tg.cloneTree();
BranchGroupbg2=createBranchGroup();
bg2.addChild(tg2);
offscreenGroup.addChild(bg2);
returnnewShape(bg2,tg2);
}
/**
*Privateclassthatrepresentsanythingthatcanbemovedandrotated.
*/
privatestaticclassTransformable{
privateTransformGrouptg;
privateTransformable(TransformGrouptg0){
this.tg=tg0;
}
privateTransform3DgetTransform(){
Transform3Dt=newTransform3D();
tg.getTransform(t);
returnt;
}
privatevoidsetTransform(Transform3Dt){
tg.setTransform(t);
}
privateVector3DrelToAbs(Vector3Dr){
Transform3Dt=getTransform();
Matrix3dm=newMatrix3d();
t.get(m);
Vector3dzero=newVector3d(0,0,0);
Transform3Drotation=newTransform3D(m,zero,1.0);
Vector3fvec=createVector3f(r);
rotation.transform(vec);
returnnewVector3D(vec);
}
privateVector3DabsToRel(Vector3Dr){
Transform3Dt=getTransform();
Matrix3dm=newMatrix3d();
t.get(m);
Vector3dzero=newVector3d(0,0,0);
Transform3Drotation=newTransform3D(m,zero,1.0);
Vector3fvec=createVector3f(r);
rotation.invert();
rotation.transform(vec);
returnnewVector3D(vec);
}
privatevoidrotateQuat(doublex,doubley,doublez,doublew){
rotateQuat(newQuat4d(x,y,z,w));
}
privatevoidrotateQuat(Quat4dquat){
Transform3Dt=getTransform();
Transform3Dt1=newTransform3D();
t1.setRotation(quat);
t.mul(t1);
setTransform(t);
}
privatevoidsetQuaternion(doublex,doubley,doublez,doublew){
setQuaternion(newQuat4d(x,y,z,w));
}
privatevoidsetQuaternion(Quat4dquat){
Transform3Dt=getTransform();
t.setRotation(quat);
setTransform(t);
}
privateQuat4dgetQuaternion(){
Transform3Dt=getTransform();
Matrix3dm=newMatrix3d();
t.get(m);
doublew=Math.sqrt(Math.max(0,1+m.m00+m.m11+m.m22))/2;
doublex=Math.sqrt(Math.max(0,1+m.m00-m.m11-m.m22))/2;
doubley=Math.sqrt(Math.max(0,1-m.m00+m.m11-m.m22))/2;
doublez=Math.sqrt(Math.max(0,1-m.m00-m.m11+m.m22))/2;
if(m.m21-m.m12<0)x=-x;
if(m.m02-m.m20<0)y=-y;
if(m.m10-m.m01<0)z=-z;
returnnewQuat4d(x,y,z,w);
}
privatevoidorientAxis(Vector3Daxis,doubleangle){
Transform3Dt=getTransform();
AxisAngle4daa=newAxisAngle4d(axis.x,axis.y,axis.z,Math.toRadians(angle));
t.setRotation(aa);
setTransform(t);
}
publicvoidrotateAxis(Vector3Daxis,doubleangle){
if(angle==0)return;
Transform3Dt=getTransform();
Vector3DaRel=absToRel(axis);
AxisAngle4daa=newAxisAngle4d(aRel.x,aRel.y,aRel.z,Math.toRadians(angle));
Transform3Dt1=newTransform3D();
t1.setRotation(aa);
t.mul(t1);
setTransform(t);
}
publicvoidmove(doublex,doubley,doublez){
move(newVector3D(x,y,z));
}
publicvoidmove(Vector3Dmove){
Transform3Dt=getTransform();
Vector3fr=newVector3f();
t.get(r);
r.add(createVector3f(move));
t.setTranslation(r);
setTransform(t);
}
publicvoidmoveRelative(doubleright,doubleup,doubleforward){
moveRelative(newVector3D(right,up,forward));
}
publicvoidmoveRelative(Vector3Dmove){
move(relToAbs(move.times(1,1,-1)));
}
publicvoidsetPosition(doublex,doubley,doublez){
setPosition(newVector3D(x,y,z));
}
publicvoidsetPosition(Vector3Dpos){
Transform3Dt=getTransform();
t.setTranslation(createVector3f(pos));
setTransform(t);
}
publicVector3DgetPosition(){
Transform3Dt=getTransform();
Vector3dr=newVector3d();
t.get(r);
returnnewVector3D(r);
}
publicvoidrotate(doublexAngle,doubleyAngle,doublezAngle){
rotate(newVector3D(xAngle,yAngle,zAngle));
}
publicvoidrotate(Vector3Dangles){
Transform3Dt=getTransform();
Transform3DtX=newTransform3D();
Transform3DtY=newTransform3D();
Transform3DtZ=newTransform3D();
Vector3DxR=absToRel(xAxis);
Vector3DyR=absToRel(yAxis);
Vector3DzR=absToRel(zAxis);
Vector3Dradians=angles.times(Math.PI/180.);
tX.setRotation(newAxisAngle4d(xR.x,xR.y,xR.z,radians.x));
tY.setRotation(newAxisAngle4d(yR.x,yR.y,yR.z,radians.y));
tZ.setRotation(newAxisAngle4d(zR.x,zR.y,zR.z,radians.z));
t.mul(tX);
t.mul(tY);
t.mul(tZ);
setTransform(t);
}
publicvoidrotateRelative(doublepitch,doubleyaw,doubleroll){
rotateRelative(newVector3D(pitch,yaw,roll));
}
publicvoidrotateRelative(Vector3Dangles){
Transform3Dt=getTransform();
Transform3DtX=newTransform3D();
Transform3DtY=newTransform3D();
Transform3DtZ=newTransform3D();
Vector3Dradians=angles.times(Math.PI/180.);
tX.setRotation(newAxisAngle4d(1,0,0,radians.x));
tY.setRotation(newAxisAngle4d(0,1,0,radians.y));
tZ.setRotation(newAxisAngle4d(0,0,1,radians.z));
t.mul(tX);
t.mul(tY);
t.mul(tZ);
setTransform(t);
}
publicvoidsetOrientation(doublexAngle,doubleyAngle,doublezAngle){
setOrientation(newVector3D(xAngle,yAngle,zAngle));
}
publicvoidsetOrientation(Vector3Dangles){
if(Math.abs(angles.y)==90)
System.err.println("Gimballockwhenthey-angleisvertical!");
Transform3Dt=getTransform();
Vector3Dradians=angles.times(Math.PI/180.);
Transform3Dt1=newTransform3D();
t1.setEuler(createVector3d(radians));
Vector3dr=newVector3d();
t.get(r);
t1.setTranslation(r);
t1.setScale(t.getScale());
setTransform(t1);
}
publicVector3DgetOrientation(){
Transform3Dt=getTransform();
Matrix3dmat=newMatrix3d();
t.get(mat);
doublexA,yA,zA;
yA=-Math.asin(mat.m20);
doubleC=Math.cos(yA);
if(Math.abs(C)>0.005){
xA=-Math.atan2(-mat.m21/C,mat.m22/C);
zA=-Math.atan2(-mat.m10/C,mat.m00/C);
}else{
xA=0;
zA=-Math.atan2(mat.m01,mat.m11);
}
xA=Math.toDegrees(xA);
yA=Math.toDegrees(yA);
zA=Math.toDegrees(zA);
/*returnonlypositiveanglesin[0,360]*/
if(xA<0)xA+=360;
if(yA<0)yA+=360;
if(zA<0)zA+=360;
returnnewVector3D(xA,yA,zA);
}
publicvoidlookAt(Vector3Dcenter){
lookAt(center,yAxis);
}
publicvoidlookAt(Vector3Dcenter,Vector3Dup){
Transform3Dt=getTransform();
Transform3Dt2=newTransform3D(t);
Vector3ftranslation=newVector3f();
t2.get(translation);
Vector3dscales=newVector3d();
t2.getScale(scales);
Point3dtrans=newPoint3d(translation);
Point3dc=newPoint3d(center.x,center.y,center.z);
Vector3du=createVector3d(up);
t2.lookAt(trans,c,u);
try{
t2.invert();
t2.setScale(scales);
setTransform(t2);
}catch(SingularMatrixExceptionsme){System.out.println("Singularmatrix,badlookAt()!");}
}
publicvoidsetDirection(Vector3Ddirection){
setDirection(direction,yAxis);
}
publicvoidsetDirection(Vector3Ddirection,Vector3Dup){
Vector3Dcenter=getPosition().plus(direction);
lookAt(center,up);
}
publicVector3DgetDirection(){
returnrelToAbs(zAxis.times(-1)).direction();
}
privatevoidmatch(Transformables){
setOrientation(s.getOrientation());
setPosition(s.getPosition());
}
}
publicstaticVector3DgetCameraPosition(){
returncamera.getPosition();
}
publicstaticVector3DgetCameraOrientation(){
returncamera.getOrientation();
}
publicstaticVector3DgetCameraDirection(){
returncamera.getDirection();
}
publicstaticvoidsetCameraPosition(doublex,doubley,doublez){
setCameraPosition(newVector3D(x,y,z));
}
publicstaticvoidsetCameraPosition(Vector3Dposition){
camera.setPosition(position);
}
publicstaticvoidsetCameraOrientation(doublexAngle,doubleyAngle,doublezAngle){
setCameraOrientation(newVector3D(xAngle,yAngle,zAngle));
}
publicstaticvoidsetCameraOrientation(Vector3Dangles){
camera.setOrientation(angles);
}
publicstaticvoidsetCameraDirection(doublex,doubley,doublez){
setCameraDirection(newVector3D(x,y,z));
}
publicstaticvoidsetCameraDirection(Vector3Ddirection){
camera.setDirection(direction);
}
publicstaticvoidsetCamera(doublex,doubley,doublez,doublexAngle,doubleyAngle,doublezAngle){
camera.setPosition(x,y,z);
camera.setOrientation(xAngle,yAngle,zAngle);
}
publicstaticvoidsetCamera(Vector3Dposition,Vector3Dangles){
camera.setPosition(position);
camera.setOrientation(angles);
}
/**
*ReturnstheCameraobject.
*/
publicstaticCameracamera(){
returncamera;
}
/**
*Thecameracanbecontrolledwiththestaticfunctionsalreadylistedin
*thisreference.However,muchmoreadvancedcontrolofthecameracanbe
*obtainedbymanipulatingtheCameraobject.TheCameraisbasically
*equivalenttoaShapewithacoupleofextrafunctions,soitcanbemoved
*androtatedjustlikeaShape.Thisfunctionalityworkswellwith
*point-of-viewsimulationsandgames.
*/
publicstaticclassCameraextendsTransformable{
privateTransformGrouptg;
privateShapepair;
privateCamera(TransformGrouptg){
super(tg);
this.tg=tg;
}
publicvoidmatch(Shapes){
super.match(s);
}
publicvoidpair(Shapes){
pair=s;
}
publicvoidunpair(){
pair=null;
}
publicvoidmoveRelative(Vector3Dmove){
if((view.getProjectionPolicy()==View.PARALLEL_PROJECTION)){
setScreenScale(view.getScreenScale()*(1+move.z/zoom));
super.move(super.relToAbs(move.times(1,1,0)));
}elsesuper.move(super.relToAbs(move.times(1,1,-1)));
}
publicvoidrotateFPS(Vector3Dangles){
rotateFPS(angles.x,angles.y,angles.z);
}
publicvoidrotateFPS(doublexAngle,doubleyAngle,doublezAngle){
doublexA=Math.toRadians(xAngle);
doubleyA=Math.toRadians(yAngle);
doublezA=Math.toRadians(zAngle);
Vector3Dshift=super.relToAbs(newVector3D(-yA,xA,zA));
Vector3Ddir=super.getDirection().plus(shift);
doubleangle=dir.angle(yAxis);
if(angle>90)angle=180-angle;
if(angle<5)return;
super.setDirection(super.getDirection().plus(shift));
}
}
/**
*Everythingthree-dimensionalyoudrawinyourscenefromspheresto
*pointsto3DtextisactuallyaShapeobject.Whenyoucalladrawing
*function,italwaysreturnsaShapeobject.Ifyoukeepareferenceto
*thisobject,youcanmanipulatethealreadydrawnShapeinsteadof
*clearingandredrawingit,whichisamuchmorepowerfulandmore
*efficientmethodofanimation.
*/
publicstaticclassShapeextendsTransformable{
privateBranchGroupbg;
privateTransformGrouptg;
privateShape(BranchGroupbg,TransformGrouptg){
super(tg);
this.bg=bg;
this.tg=tg;
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
}
publicvoidscale(doublescale){
Transform3Dt=super.getTransform();
t.setScale(t.getScale()*scale);
super.setTransform(t);
}
//publicvoidscale(doublexScale,doubleyScale,doublezScale){
//scale(newVector3D(xScale,yScale,zScale));
//}
//
//publicvoidscale(Vector3Dscales){
//Transform3Dt=getTransform();
//thrownewUnsupportedOperationException("Doesn'tworkwithrotation!");
//setTransform(t);
//}
publicvoidhide(){
offscreenGroup.removeChild(bg);
onscreenGroup.removeChild(bg);
}
publicvoidunhide(){
hide();
offscreenGroup.addChild(bg);
}
publicvoidmatch(Shapes){
super.match(s);
}
publicvoidmatch(Camerac){
super.match(c);
}
publicvoidsetColor(Colorc){
setColor(tg,c);
}
publicvoidsetColor(Colorc,intalpha){
setColor(newColor(c.getRed(),c.getGreen(),c.getBlue(),alpha));
}
privatevoidsetColor(Groupg,Colorc){
for(inti=0;i<g.numChildren();i++){
Nodechild=g.getChild(i);
if(childinstanceofShape3D){
Shape3Dshape=(Shape3D)child;
Appearanceap=shape.getAppearance();
setColor(ap,c);
}elseif(childinstanceofPrimitive){
Primitiveprimitive=(Primitive)child;
Appearanceap=primitive.getAppearance();
setColor(ap,c);
}elseif(childinstanceofGroup){
setColor((Group)child,c);
}
}
}
privatevoidsetColor(Appearanceap,Colorc){
Materialm=ap.getMaterial();
m.setAmbientColor(newColor3f(c));
m.setDiffuseColor(newColor3f(c));
floatalpha=((float)c.getAlpha())/255;
if(alpha<1.0){
TransparencyAttributest=newTransparencyAttributes();
t.setTransparencyMode(TransparencyAttributes.BLENDED);
t.setTransparency(1-alpha);
ap.setTransparencyAttributes(t);
}elseap.setTransparencyAttributes(null);
}
}
/**
*WhenyoucreatealightinStdDraw3D,itreturnsaLightobject.Light
*objectscanbemanipulatedjustlikeShapes,andareusefulifyouwant
*movinglightsorlightsthatchangecolorandbrightness.
*/
publicstaticclassLightextendsTransformable{
javax.media.j3d.Lightlight;
BranchGroupbg;
privateLight(BranchGroupbg,TransformGrouptg,javax.media.j3d.Lightlight){
super(tg);
this.light=light;
this.bg=bg;
}
publicvoidhide(){
light.setEnable(false);
}
publicvoidunhide(){
light.setEnable(true);
}
publicvoidmatch(Shapes){
super.match(s);
}
publicvoidmatch(Camerac){
super.match(c);
}
publicvoidsetColor(Colorcol){
light.setColor(newColor3f(col));
}
publicvoidscalePower(doublepower){
if(lightinstanceofPointLight){
doubleattenuationScale=1.0/(0.999*power+0.001);
PointLightpl=(PointLight)light;
Point3fattenuation=newPoint3f();
pl.getAttenuation(attenuation);
attenuation.y*=attenuationScale;
attenuation.z*=attenuationScale*attenuationScale;
pl.setAttenuation(attenuation);
}else{
System.err.println("Canonlyscalepowerforpointlights!");
}
}
}
/******************************************************************************
*Animmutablethree-dimensionalvectorclasswithusefulvectoroperations.
*
*@authorHaykMartirosyan<hmartiro@princeton.edu>
*@since2011.0310
*@version1.0
****************************************************************************/
publicstaticclassVector3D{
/**X-coordinate-immutablebutdirectlyaccessible.*/
publicfinaldoublex;
/**Y-coordinate-immutablebutdirectlyaccessible.*/
publicfinaldoubley;
/**Z-coordinate-immutablebutdirectlyaccessible.*/
publicfinaldoublez;
//--------------------------------------------------------------------------
/**
*Initializestozerovector.
*/
publicVector3D(){
this.x=0;
this.y=0;
this.z=0;
}
//--------------------------------------------------------------------------
/**
*Initializestothegivencoordinates.
*
*@paramxX-coordinate
*@paramyY-coordinate
*@paramzZ-coordinate
*/
publicVector3D(doublex,doubley,doublez){
this.x=x;
this.y=y;
this.z=z;
}
/**
*Initializestothegivencoordinates.
*
*@paramcArraylength3ofcoordinates(x,y,z,).
*/
//--------------------------------------------------------------------------
publicVector3D(double[]c){
if(c.length!=3)
thrownewRuntimeException("Incorrectnumberofdimensions!");
this.x=c[0];
this.y=c[1];
this.z=c[2];
}
//--------------------------------------------------------------------------
privateVector3D(Vector3dv){
this.x=v.x;
this.y=v.y;
this.z=v.z;
}
//--------------------------------------------------------------------------
privateVector3D(Vector3fv){
this.x=v.x;
this.y=v.y;
this.z=v.z;
}
//--------------------------------------------------------------------------
privateVector3D(Point3dp){
this.x=p.x;
this.y=p.y;
this.z=p.z;
}
//--------------------------------------------------------------------------
privateVector3D(Point3fp){
this.x=p.x;
this.y=p.y;
this.z=p.z;
}
//--------------------------------------------------------------------------
/*
publicVector3D(doublemin,doublemax){
this.x=min+Math.random()*(max-min);
this.y=min+Math.random()*(max-min);
this.z=min+Math.random()*(max-min);
}
*/
//--------------------------------------------------------------------------
/**
*Returnsthedotproductofthisandthat.
*
*@paramthatVectortodotwith
*@returnThisdotthat
*/
publicdoubledot(Vector3Dthat){
return(this.x*that.x+this.y*that.y+this.z*that.z);
}
//--------------------------------------------------------------------------
/**
*Returnsthemagnitudeofthisvector.
*
*@returnMagnitudeofvector
*/
publicdoublemag(){
returnMath.sqrt(this.dot(this));
}
//--------------------------------------------------------------------------
/**
*Returnsthesmallestanglebetweenthisandthatvector,inDEGREES.
*
*@returnAnglebetweenthevectors,inDEGREES
*/
publicdoubleangle(Vector3Dthat){
returnMath.toDegrees(Math.acos(this.dot(that)/(this.mag()*that.mag())));
}
//--------------------------------------------------------------------------
/**
*ReturnstheEuclidiandistancebetweenthisandthat.
*
*@paramthatVectortocomputedistancebetween
*@returnDistancebetweenthisandthat
*/
publicdoubledistanceTo(Vector3Dthat){
returnthis.minus(that).mag();
}
//--------------------------------------------------------------------------
/**
*Returnsthesumofthisandthatvector.
*
*@paramthatVectortocomputesumwith
*@returnThisplusthat
*/
publicVector3Dplus(Vector3Dthat){
doublecx=this.x+that.x;
doublecy=this.y+that.y;
doublecz=this.z+that.z;
Vector3Dc=newVector3D(cx,cy,cz);
returnc;
}
publicVector3Dplus(doublex,doubley,doublez){
doublecx=this.x+x;
doublecy=this.y+y;
doublecz=this.z+z;
returnnewVector3D(cx,cy,cz);
}
//--------------------------------------------------------------------------
/**
*Returnsthedifferenceofthisandthatvector.
*
*@paramthatVectortocomputedifferencewith
*@returnThisminusthat
*/
publicVector3Dminus(Vector3Dthat){
doublecx=this.x-that.x;
doublecy=this.y-that.y;
doublecz=this.z-that.z;
Vector3Dc=newVector3D(cx,cy,cz);
returnc;
}
publicVector3Dminus(doublex,doubley,doublez){
doublecx=this.x-x;
doublecy=this.y-y;
doublecz=this.z-z;
returnnewVector3D(cx,cy,cz);
}
//--------------------------------------------------------------------------
/**
*Returnstheproductofthisvectorandthescalark.
*
*@paramkScalartomultiplyby
*@return(this.x*k,this.y*k,this.z*k)
*/
publicVector3Dtimes(doublek){
returntimes(k,k,k);
}
//--------------------------------------------------------------------------
/**
*Returnstheresult(this.x*a,this.y*b,this.z*c).
*
*@paramaScalartomultiplyxby
*@parambScalartomultiplyyby
*@paramcScalartomultiplyzby
*@return(this.x*a,this.y*b,this.z*c)
*/
publicVector3Dtimes(doublea,doubleb,doublec){
doublevx=this.x*a;
doublevy=this.y*b;
doublevz=this.z*c;
Vector3Dv=newVector3D(vx,vy,vz);
returnv;
}
//--------------------------------------------------------------------------
/**
*Returnstheunitvectorinthedirectionofthisvector.
*
*@returnUnitvectorwithdirectionofthisvector
*/
publicVector3Ddirection(){
if(this.mag()==0.0)thrownewRuntimeException("Zero-vectorhasnodirection");
returnthis.times(1.0/this.mag());
}
//--------------------------------------------------------------------------
/**
*Returnstheprojectionofthisontothegivenline.
*
*@paramlineDirectiontoprojectthisvectoronto
*@returnThisprojectedontoline
*/
publicVector3Dproj(Vector3Dline){
Vector3Dnormal=line.direction();
returnnormal.times(this.dot(normal));
}
//--------------------------------------------------------------------------
/**
*Returnsthecrossproductofthisvectorwiththatvector.
*
*@returnThiscrossthat
*/
publicVector3Dcross(Vector3Dthat){
Vector3Da=this;
Vector3Db=that;
returnnewVector3D(a.y*b.z-a.z*b.y,a.z*b.x-a.x*b.z,a.x*b.y-a.y*b.x);
}
//--------------------------------------------------------------------------
/**
*Reflectsthisvectoracrossthedirectiongivenbyline.
*
*@paramlineDirectiontoreflectthisvectorover
*@returnThisreflectedoverline
*/
publicVector3Dreflect(Vector3Dline){
returnthis.proj(line).times(2).minus(this);
}
//--------------------------------------------------------------------------
/**
*Returnsastringrepresentationofthisvector.
*
*@return"(this.x,this.y,this.z)"
*/
publicStringtoString(){
DecimalFormatdf=newDecimalFormat("0.000000");
return("("+df.format(this.x)+","+df.format(this.y)+","+df.format(this.z)+")");
}
//--------------------------------------------------------------------------
/**
*DrawsthisvectorasapointfromtheorigintoStdDraw3D.
*/
publicvoiddraw(){
StdDraw3D.sphere(this.x,this.y,this.z,0.01);
}
//--------------------------------------------------------------------------
/**
*Drawsalinerepresentationofthisvector,fromthegivenorigin.
*
*@paramoriginOriginpointtodrawfrom
*/
/*
publicvoiddrawLine(Vector3Dorigin){
Vector3Dend=this.plus(origin);
StdDraw3D.line(origin.x,origin.y,origin.z,end.x,end.y,end.z);
}
*/
}
publicstaticvoidmain(String[]args){
//Setsthescale
StdDraw3D.setScale(-1,1);
//TurnsoffthedefaultinfoHUDdisplay.
StdDraw3D.setInfoDisplay(false);
//Drawsthewhitesquareborder.
StdDraw3D.setPenColor(StdDraw3D.WHITE);
StdDraw3D.overlaySquare(0,0,0.98);
//Drawsthetworedcircles.
StdDraw3D.setPenRadius(0.06);
StdDraw3D.setPenColor(StdDraw3D.RED,220);
StdDraw3D.overlayCircle(0,0,0.8);
StdDraw3D.setPenColor(StdDraw3D.RED,220);
StdDraw3D.overlayCircle(0,0,0.6);
//Drawstheinformationtext.
StdDraw3D.setPenColor(StdDraw3D.WHITE);
StdDraw3D.overlayText(0,0.91,"StandardDraw3D-TestProgram");
StdDraw3D.overlayText(0,-0.95,"Youshouldseerotatingtext.Dragthemousetoorbit.");
//Createsthe3Dtextobjectandcentersit.
StdDraw3D.setPenColor(StdDraw3D.YELLOW);
StdDraw3D.setFont(newFont("Arial",Font.BOLD,16));
StdDraw3D.Shapetext=StdDraw3D.text3D(0,0,0,"StdDraw3D");
text.scale(3.5);
text.move(-0.7,-0.1,0);
text=StdDraw3D.combine(text);
while(true){
//Rotatesthe3Dtextby1.2degreesalongthey-axis.
text.rotate(0,1.2,0);
//Showstheframefor20milliseconds.
StdDraw3D.show(20);
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
*@(#)Transparency.java1.2105/11/17
*
*Copyright2006SunMicrosystems,Inc.Allrightsreserved.
*SUNPROPRIETARY/CONFIDENTIAL.Useissubjecttolicenseterms.
*/
packagejava.awt;
/**
*The<code>Transparency</code>interfacedefinesthecommontransparency
*modesforimplementingclasses.
*@version1.21,11/17/05
*/
publicinterfaceTransparency{
/**
*Representsimagedatathatisguaranteedtobecompletelyopaque,
*meaningthatallpixelshaveanalphavalueof1.0.
*/
publicfinalstaticintOPAQUE=1;
/**
*Representsimagedatathatisguaranteedtobeeithercompletely
*opaque,withanalphavalueof1.0,orcompletelytransparent,
*withanalphavalueof0.0.
*/
publicfinalstaticintBITMASK=2;
/**
*Representsimagedatathatcontainsormightcontainarbitrary
*alphavaluesbetweenandincluding0.0and1.0.
*/
publicfinalstaticintTRANSLUCENT=3;
/**
*Returnsthetypeofthis<code>Transparency</code>.
*@returnthefieldtypeofthis<code>Transparency</code>,whichis
*eitherOPAQUE,BITMASKorTRANSLUCENT.
*/
publicintgetTransparency();
}
/*
*@(#)Paint.java1.2805/11/17
*
*Copyright2006SunMicrosystems,Inc.Allrightsreserved.
*SUNPROPRIETARY/CONFIDENTIAL.Useissubjecttolicenseterms.
*/
packagejava.awt;
importjava.awt.image.ColorModel;
importjava.awt.geom.AffineTransform;
importjava.awt.geom.Point2D;
importjava.awt.geom.Rectangle2D;
/**
*This<code>Paint</code>interfacedefineshowcolorpatterns
*canbegeneratedfor{@linkGraphics2D}operations.Aclass
*implementingthe<code>Paint</code>interfaceisaddedtothe
*<code>Graphics2D</code>contextinordertodefinethecolor
*patternusedbythe<code>draw</code>and<code>fill</code>methods.
*<p>
*Instancesofclassesimplementing<code>Paint</code>mustbe
*read-onlybecausethe<code>Graphics2D</code>doesnotclone
*theseobjectswhentheyaresetasanattributewiththe
*<code>setPaint</code>methodorwhenthe<code>Graphics2D</code>
*objectisitselfcloned.
*@seePaintContext
*@seeColor
*@seeGradientPaint
*@seeTexturePaint
*@seeGraphics2D#setPaint
*@version1.28,11/17/05
*/
publicinterfacePaintextendsTransparency{
/**
*Createsandreturnsa{@linkPaintContext}usedto
*generatethecolorpattern.
*SincetheColorModelargumenttocreateContextisonlya
*hint,implementationsofPaintshouldacceptanullargument
*forColorModel.Notethatiftheapplicationdoesnot
*preferaspecificColorModel,thenullColorModelargument
*willgivethePaintimplementationfullleewayinusingthe
*mostefficientColorModelitprefersforitsrasterprocessing.
*<p>
*SincetheAPIdocumentationwasnotspecificaboutthisin
*releasesbefore1.4,theremaybeimplementationsof
*<code>Paint</code>thatdonotacceptanull
*<code>ColorModel</code>argument.
*Ifadeveloperiswritingcodewhichpassesanull
*<code>ColorModel</code>argumenttothe
*<code>createContext</code>methodof<code>Paint</code>
*objectsfromarbitrarysourcesitwouldbewisetocodedefensively
*bymanufacturinganon-null<code>ColorModel</code>forthose
*objectswhichthrowa<code>NullPointerException</code>.
*@paramcmthe{@linkColorModel}thatreceivesthe
*<code>Paint</code>data.Thisisusedonlyasahint.
*@paramdeviceBoundsthedevicespaceboundingbox
*ofthegraphicsprimitivebeingrendered
*@paramuserBoundstheuserspaceboundingbox
*ofthegraphicsprimitivebeingrendered
*@paramxformthe{@linkAffineTransform}fromuser
*spaceintodevicespace
*@paramhintsthehintthatthecontextobjectusesto
*choosebetweenrenderingalternatives
*@returnthe<code>PaintContext</code>for
*generatingcolorpatterns
*@seePaintContext
*/
publicPaintContextcreateContext(ColorModelcm,
RectangledeviceBounds,
Rectangle2DuserBounds,
AffineTransformxform,
RenderingHintshints);
}
/*
*@(#)Color.java1.8008/05/29
*
*Copyright2006SunMicrosystems,Inc.Allrightsreserved.
*SUNPROPRIETARY/CONFIDENTIAL.Useissubjecttolicenseterms.
*/
packagejava.awt;
importjava.io.*;
importjava.lang.*;
importjava.awt.image.ColorModel;
importjava.awt.geom.AffineTransform;
importjava.awt.geom.Rectangle2D;
importjava.awt.color.ColorSpace;
/**
*The<code>Color</code>classisusedtoencapsulatecolorsinthedefault
*sRGBcolorspaceorcolorsinarbitrarycolorspacesidentifiedbya
*{@linkColorSpace}.Everycolorhasanimplicitalphavalueof1.0or
*anexplicitoneprovidedintheconstructor.Thealphavalue
*definesthetransparencyofacolorandcanberepresentedby
*afloatvalueintherange0.0-1.0or0-255.
*Analphavalueof1.0or255meansthatthecoloriscompletely
*opaqueandanalphavalueof0or0.0meansthatthecoloris
*completelytransparent.
*Whenconstructinga<code>Color</code>withanexplicitalphaor
*gettingthecolor/alphacomponentsofa<code>Color</code>,thecolor
*componentsareneverpremultipliedbythealphacomponent.
*<p>
*ThedefaultcolorspacefortheJava2D(tm)APIissRGB,aproposed
*standardRGBcolorspace.ForfurtherinformationonsRGB,
*see<Ahref="http://www.w3.org/pub/WWW/Graphics/Color/sRGB.html">
*http://www.w3.org/pub/WWW/Graphics/Color/sRGB.html
*</A>.
*<p>
*@version10Feb1997
*@authorSamiShaio
*@authorArthurvanHoff
*@seeColorSpace
*@seeAlphaComposite
*/
publicclassColorimplementsPaint,java.io.Serializable{
/**
*Thecolorwhite.InthedefaultsRGBspace.
*/
publicfinalstaticColorwhite=newColor(255,255,255);
/**
*Thecolorwhite.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorWHITE=white;
/**
*Thecolorlightgray.InthedefaultsRGBspace.
*/
publicfinalstaticColorlightGray=newColor(192,192,192);
/**
*Thecolorlightgray.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorLIGHT_GRAY=lightGray;
/**
*Thecolorgray.InthedefaultsRGBspace.
*/
publicfinalstaticColorgray=newColor(128,128,128);
/**
*Thecolorgray.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorGRAY=gray;
/**
*Thecolordarkgray.InthedefaultsRGBspace.
*/
publicfinalstaticColordarkGray=newColor(64,64,64);
/**
*Thecolordarkgray.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorDARK_GRAY=darkGray;
/**
*Thecolorblack.InthedefaultsRGBspace.
*/
publicfinalstaticColorblack=newColor(0,0,0);
/**
*Thecolorblack.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorBLACK=black;
/**
*Thecolorred.InthedefaultsRGBspace.
*/
publicfinalstaticColorred=newColor(255,0,0);
/**
*Thecolorred.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorRED=red;
/**
*Thecolorpink.InthedefaultsRGBspace.
*/
publicfinalstaticColorpink=newColor(255,175,175);
/**
*Thecolorpink.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorPINK=pink;
/**
*Thecolororange.InthedefaultsRGBspace.
*/
publicfinalstaticColororange=newColor(255,200,0);
/**
*Thecolororange.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorORANGE=orange;
/**
*Thecoloryellow.InthedefaultsRGBspace.
*/
publicfinalstaticColoryellow=newColor(255,255,0);
/**
*Thecoloryellow.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorYELLOW=yellow;
/**
*Thecolorgreen.InthedefaultsRGBspace.
*/
publicfinalstaticColorgreen=newColor(0,255,0);
/**
*Thecolorgreen.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorGREEN=green;
/**
*Thecolormagenta.InthedefaultsRGBspace.
*/
publicfinalstaticColormagenta=newColor(255,0,255);
/**
*Thecolormagenta.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorMAGENTA=magenta;
/**
*Thecolorcyan.InthedefaultsRGBspace.
*/
publicfinalstaticColorcyan=newColor(0,255,255);
/**
*Thecolorcyan.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorCYAN=cyan;
/**
*Thecolorblue.InthedefaultsRGBspace.
*/
publicfinalstaticColorblue=newColor(0,0,255);
/**
*Thecolorblue.InthedefaultsRGBspace.
*@since1.4
*/
publicfinalstaticColorBLUE=blue;
/**
*Privatedata.
*/
transientprivatelongpData;
/**
*Thecolorvalue.
*@serial
*@see#getRGB
*/
intvalue;
/**
*ThecolorvalueinthedefaultsRGB<code>ColorSpace</code>as
*<code>float</code>components(noalpha).
*If<code>null</code>afterobjectconstruction,thismustbean
*sRGBcolorconstructedwith8-bitprecision,socomputefromthe
*<code>int</code>colorvalue.
*@serial
*@see#getRGBColorComponents
*@see#getRGBComponents
*/
privatefloatfrgbvalue[]=null;
/**
*Thecolorvalueinthenative<code>ColorSpace</code>as
*<code>float</code>components(noalpha).
*If<code>null</code>afterobjectconstruction,thismustbean
*sRGBcolorconstructedwith8-bitprecision,socomputefromthe
*<code>int</code>colorvalue.
*@serial
*@see#getRGBColorComponents
*@see#getRGBComponents
*/
privatefloatfvalue[]=null;
/**
*Thealphavalueasa<code>float</code>component.
*If<code>frgbvalue</code>is<code>null</code>,thisisnotvalid
*data,socomputefromthe<code>int</code>colorvalue.
*@serial
*@see#getRGBComponents
*@see#getComponents
*/
privatefloatfalpha=0.0f;
/**
*The<code>ColorSpace</code>.If<code>null</code>,thenit's
*defaultissRGB.
*@serial
*@see#getColor
*@see#getColorSpace
*@see#getColorComponents
*/
privateColorSpacecs=null;
/*
*JDK1.1serialVersionUID
*/
privatestaticfinallongserialVersionUID=118526816881161077L;
/**
*InitializeJNIfieldandmethodIDs
*/
privatestaticnativevoidinitIDs();
static{
/**4112352-CallinggetDefaultToolkit()
**herecancausethisclasstobeaccessedbeforeitisfully
**initialized.DON'TDOIT!!!
**
**Toolkit.getDefaultToolkit();
**/
/*ensurethatthenecessarynativelibrariesareloaded*/
Toolkit.loadLibraries();
if(!GraphicsEnvironment.isHeadless()){
initIDs();
}
}
/**
*Checksthecolorintegercomponentssuppliedforvalidity.
*Throwsan{@linkIllegalArgumentException}ifthevalueisoutof
*range.
*@paramrtheRedcomponent
*@paramgtheGreencomponent
*@parambtheBluecomponent
**/
privatestaticvoidtestColorValueRange(intr,intg,intb,inta){
booleanrangeError=false;
StringbadComponentString="";
if(a<0||a>255){
rangeError=true;
badComponentString=badComponentString+"Alpha";
}
if(r<0||r>255){
rangeError=true;
badComponentString=badComponentString+"Red";
}
if(g<0||g>255){
rangeError=true;
badComponentString=badComponentString+"Green";
}
if(b<0||b>255){
rangeError=true;
badComponentString=badComponentString+"Blue";
}
if(rangeError==true){
thrownewIllegalArgumentException("Colorparameteroutsideofexpectedrange:"
+badComponentString);
}
}
/**
*Checksthecolor<code>float</code>componentssuppliedfor
*validity.
*Throwsan<code>IllegalArgumentException</code>ifthevalueisout
*ofrange.
*@paramrtheRedcomponent
*@paramgtheGreencomponent
*@parambtheBluecomponent
**/
privatestaticvoidtestColorValueRange(floatr,floatg,floatb,floata){
booleanrangeError=false;
StringbadComponentString="";
if(a<0.0||a>1.0){
rangeError=true;
badComponentString=badComponentString+"Alpha";
}
if(r<0.0||r>1.0){
rangeError=true;
badComponentString=badComponentString+"Red";
}
if(g<0.0||g>1.0){
rangeError=true;
badComponentString=badComponentString+"Green";
}
if(b<0.0||b>1.0){
rangeError=true;
badComponentString=badComponentString+"Blue";
}
if(rangeError==true){
thrownewIllegalArgumentException("Colorparameteroutsideofexpectedrange:"
+badComponentString);
}
}
/**
*CreatesanopaquesRGBcolorwiththespecifiedred,green,
*andbluevaluesintherange(0-255).
*Theactualcolorusedinrenderingdepends
*onfindingthebestmatchgiventhecolorspace
*availableforagivenoutputdevice.
*Alphaisdefaultedto255.
*
*@throwsIllegalArgumentExceptionif<code>r</code>,<code>g</code>
*or<code>b</code>areoutsideoftherange
*0to255,inclusive
*@paramrtheredcomponent
*@paramgthegreencomponent
*@parambthebluecomponent
*@see#getRed
*@see#getGreen
*@see#getBlue
*@see#getRGB
*/
publicColor(intr,intg,intb){
this(r,g,b,255);
}
/**
*CreatesansRGBcolorwiththespecifiedred,green,blue,andalpha
*valuesintherange(0-255).
*
*@throwsIllegalArgumentExceptionif<code>r</code>,<code>g</code>,
*<code>b</code>or<code>a</code>areoutsideoftherange
*0to255,inclusive
*@paramrtheredcomponent
*@paramgthegreencomponent
*@parambthebluecomponent
*@paramathealphacomponent
*@see#getRed
*@see#getGreen
*@see#getBlue
*@see#getAlpha
*@see#getRGB
*/
publicColor(intr,intg,intb,inta){
value=((a&0xFF)<<24)|
((r&0xFF)<<16)|
((g&0xFF)<<8)|
((b&0xFF)<<0);
testColorValueRange(r,g,b,a);
}
/**
*CreatesanopaquesRGBcolorwiththespecifiedcombinedRGBvalue
*consistingoftheredcomponentinbits16-23,thegreencomponent
*inbits8-15,andthebluecomponentinbits0-7.Theactualcolor
*usedinrenderingdependsonfindingthebestmatchgiventhe
*colorspaceavailableforaparticularoutputdevice.Alphais
*defaultedto255.
*
*@paramrgbthecombinedRGBcomponents
*@seejava.awt.image.ColorModel#getRGBdefault
*@see#getRed
*@see#getGreen
*@see#getBlue
*@see#getRGB
*/
publicColor(intrgb){
value=0xff000000|rgb;
}
/**
*CreatesansRGBcolorwiththespecifiedcombinedRGBAvalueconsisting
*ofthealphacomponentinbits24-31,theredcomponentinbits16-23,
*thegreencomponentinbits8-15,andthebluecomponentinbits0-7.
*Ifthe<code>hasalpha</code>argumentis<code>false</code>,alpha
*isdefaultedto255.
*
*@paramrgbathecombinedRGBAcomponents
*@paramhasalpha<code>true</code>ifthealphabitsarevalid;
*<code>false</code>otherwise
*@seejava.awt.image.ColorModel#getRGBdefault
*@see#getRed
*@see#getGreen
*@see#getBlue
*@see#getAlpha
*@see#getRGB
*/
publicColor(intrgba,booleanhasalpha){
if(hasalpha){
value=rgba;
}else{
value=0xff000000|rgba;
}
}
/**
*CreatesanopaquesRGBcolorwiththespecifiedred,green,andblue
*valuesintherange(0.0-1.0).Alphaisdefaultedto1.0.The
*actualcolorusedinrenderingdependsonfindingthebest
*matchgiventhecolorspaceavailableforaparticularoutput
*device.
*
*@throwsIllegalArgumentExceptionif<code>r</code>,<code>g</code>
*or<code>b</code>areoutsideoftherange
*0.0to1.0,inclusive
*@paramrtheredcomponent
*@paramgthegreencomponent
*@parambthebluecomponent
*@see#getRed
*@see#getGreen
*@see#getBlue
*@see#getRGB
*/
publicColor(floatr,floatg,floatb){
this((int)(r*255+0.5),(int)(g*255+0.5),(int)(b*255+0.5));
testColorValueRange(r,g,b,1.0f);
frgbvalue=newfloat[3];
frgbvalue[0]=r;
frgbvalue[1]=g;
frgbvalue[2]=b;
falpha=1.0f;
fvalue=frgbvalue;
}
/**
*CreatesansRGBcolorwiththespecifiedred,green,blue,and
*alphavaluesintherange(0.0-1.0).Theactualcolor
*usedinrenderingdependsonfindingthebestmatchgiventhe
*colorspaceavailableforaparticularoutputdevice.
*@throwsIllegalArgumentExceptionif<code>r</code>,<code>g</code>
*<code>b</code>or<code>a</code>areoutsideoftherange
*0.0to1.0,inclusive
*@paramrtheredcomponent
*@paramgthegreencomponent
*@parambthebluecomponent
*@paramathealphacomponent
*@see#getRed
*@see#getGreen
*@see#getBlue
*@see#getAlpha
*@see#getRGB
*/
publicColor(floatr,floatg,floatb,floata){
this((int)(r*255+0.5),(int)(g*255+0.5),(int)(b*255+0.5),(int)(a*255+0.5));
frgbvalue=newfloat[3];
frgbvalue[0]=r;
frgbvalue[1]=g;
frgbvalue[2]=b;
falpha=a;
fvalue=frgbvalue;
}
/**
*Createsacolorinthespecified<code>ColorSpace</code>
*withthecolorcomponentsspecifiedinthe<code>float</code>
*arrayandthespecifiedalpha.Thenumberofcomponentsis
*determinedbythetypeofthe<code>ColorSpace</code>.For
*example,RGBrequires3components,butCMYKrequires4
*components.
*@paramcspacethe<code>ColorSpace</code>tobeusedto
*interpretthecomponents
*@paramcomponentsanarbitrarynumberofcolorcomponents
*thatiscompatiblewiththe<code>ColorSpace</code>
*@paramalphaalphavalue
*@throwsIllegalArgumentExceptionifanyofthevaluesinthe
*<code>components</code>arrayor<code>alpha</code>is
*outsideoftherange0.0to1.0
*@see#getComponents
*@see#getColorComponents
*/
publicColor(ColorSpacecspace,floatcomponents[],floatalpha){
booleanrangeError=false;
StringbadComponentString="";
intn=cspace.getNumComponents();
fvalue=newfloat[n];
for(inti=0;i<n;i++){
if(components[i]<0.0||components[i]>1.0){
rangeError=true;
badComponentString=badComponentString+"Component"+i
+"";
}else{
fvalue[i]=components[i];
}
}
if(alpha<0.0||alpha>1.0){
rangeError=true;
badComponentString=badComponentString+"Alpha";
}else{
falpha=alpha;
}
if(rangeError){
thrownewIllegalArgumentException(
"Colorparameteroutsideofexpectedrange:"+
badComponentString);
}
frgbvalue=cspace.toRGB(fvalue);
cs=cspace;
value=((((int)(falpha*255))&0xFF)<<24)|
((((int)(frgbvalue[0]*255))&0xFF)<<16)|
((((int)(frgbvalue[1]*255))&0xFF)<<8)|
((((int)(frgbvalue[2]*255))&0xFF)<<0);
}
/**
*Returnstheredcomponentintherange0-255inthedefaultsRGB
*space.
*@returntheredcomponent.
*@see#getRGB
*/
publicintgetRed(){
return(getRGB()>>16)&0xFF;
}
/**
*Returnsthegreencomponentintherange0-255inthedefaultsRGB
*space.
*@returnthegreencomponent.
*@see#getRGB
*/
publicintgetGreen(){
return(getRGB()>>8)&0xFF;
}
/**
*Returnsthebluecomponentintherange0-255inthedefaultsRGB
*space.
*@returnthebluecomponent.
*@see#getRGB
*/
publicintgetBlue(){
return(getRGB()>>0)&0xFF;
}
/**
*Returnsthealphacomponentintherange0-255.
*@returnthealphacomponent.
*@see#getRGB
*/
publicintgetAlpha(){
return(getRGB()>>24)&0xff;
}
/**
*ReturnstheRGBvaluerepresentingthecolorinthedefaultsRGB
*{@linkColorModel}.
*(Bits24-31arealpha,16-23arered,8-15aregreen,0-7are
*blue).
*@returntheRGBvalueofthecolorinthedefaultsRGB
*<code>ColorModel</code>.
*@seejava.awt.image.ColorModel#getRGBdefault
*@see#getRed
*@see#getGreen
*@see#getBlue
*@sinceJDK1.0
*/
publicintgetRGB(){
returnvalue;
}
privatestaticfinaldoubleFACTOR=0.7;
/**
*Createsanew<code>Color</code>thatisabrighterversionofthis
*<code>Color</code>.
*<p>
*ThismethodappliesanarbitraryscalefactortoeachofthethreeRGB
*componentsofthis<code>Color</code>tocreateabrighterversion
*ofthis<code>Color</code>.Although<code>brighter</code>and
*<code>darker</code>areinverseoperations,theresultsofa
*seriesofinvocationsofthesetwomethodsmightbeinconsistent
*becauseofroundingerrors.
*@returnanew<code>Color</code>objectthatis
*abrighterversionofthis<code>Color</code>.
*@seejava.awt.Color#darker
*@sinceJDK1.0
*/
publicColorbrighter(){
intr=getRed();
intg=getGreen();
intb=getBlue();
/*From2Dgroup:
*1.black.brighter()shouldreturngrey
*2.applyingbrightertobluewillalwaysreturnblue,brighter
*3.nonpurecolor(nonzerorgb)willeventuallyreturnwhite
*/
inti=(int)(1.0/(1.0-FACTOR));
if(r==0&&g==0&&b==0){
returnnewColor(i,i,i);
}
if(r>0&&r<i)r=i;
if(g>0&&g<i)g=i;
if(b>0&&b<i)b=i;
returnnewColor(Math.min((int)(r/FACTOR),255),
Math.min((int)(g/FACTOR),255),
Math.min((int)(b/FACTOR),255));
}
/**
*Createsanew<code>Color</code>thatisadarkerversionofthis
*<code>Color</code>.
*<p>
*ThismethodappliesanarbitraryscalefactortoeachofthethreeRGB
*componentsofthis<code>Color</code>tocreateadarkerversionof
*this<code>Color</code>.Although<code>brighter</code>and
*<code>darker</code>areinverseoperations,theresultsofaseries
*ofinvocationsofthesetwomethodsmightbeinconsistentbecause
*ofroundingerrors.
*@returnanew<code>Color</code>objectthatis
*adarkerversionofthis<code>Color</code>.
*@seejava.awt.Color#brighter
*@sinceJDK1.0
*/
publicColordarker(){
returnnewColor(Math.max((int)(getRed()*FACTOR),0),
Math.max((int)(getGreen()*FACTOR),0),
Math.max((int)(getBlue()*FACTOR),0));
}
/**
*Computesthehashcodeforthis<code>Color</code>.
*@returnahashcodevalueforthisobject.
*@sinceJDK1.0
*/
publicinthashCode(){
returnvalue;
}
/**
*Determineswhetheranotherobjectisequaltothis
*<code>Color</code>.
*<p>
*Theresultis<code>true</code>ifandonlyiftheargumentisnot
*<code>null</code>andisa<code>Color</code>objectthathasthesame
*red,green,blue,andalphavaluesasthisobject.
*@paramobjtheobjecttotestforequalitywiththis
*<code>Color</code>
*@return<code>true</code>iftheobjectsarethesame;
*<code>false</code>otherwise.
*@sinceJDK1.0
*/
publicbooleanequals(Objectobj){
returnobjinstanceofColor&&((Color)obj).getRGB()==this.getRGB();
}
/**
*Returnsastringrepresentationofthis<code>Color</code>.This
*methodisintendedtobeusedonlyfordebuggingpurposes.The
*contentandformatofthereturnedstringmightvarybetween
*implementations.Thereturnedstringmightbeemptybutcannot
*be<code>null</code>.
*
*@returnastringrepresentationofthis<code>Color</code>.
*/
publicStringtoString(){
returngetClass().getName()+"[r="+getRed()+",g="+getGreen()+",b="+getBlue()+"]";
}
/**
*Convertsa<code>String</code>toanintegerandreturnsthe
*specifiedopaque<code>Color</code>.Thismethodhandlesstring
*formatsthatareusedtorepresentoctalandhexidecimalnumbers.
*@paramnma<code>String</code>thatrepresents
*anopaquecolorasa24-bitinteger
*@returnthenew<code>Color</code>object.
*@seejava.lang.Integer#decode
*@exceptionNumberFormatExceptionifthespecifiedstringcannot
*beinterpretedasadecimal,
*octal,orhexidecimalinteger.
*@sinceJDK1.1
*/
publicstaticColordecode(Stringnm)throwsNumberFormatException{
Integerintval=Integer.decode(nm);
inti=intval.intValue();
returnnewColor((i>>16)&0xFF,(i>>8)&0xFF,i&0xFF);
}
/**
*Findsacolorinthesystemproperties.
*<p>
*Theargumentistreatedasthenameofasystempropertyto
*beobtained.Thestringvalueofthispropertyistheninterpreted
*asanintegerwhichisthenconvertedtoa<code>Color</code>
*object.
*<p>
*Ifthespecifiedpropertyisnotfoundorcouldnotbeparsedas
*anintegerthen<code>null</code>isreturned.
*@paramnmthenameofthecolorproperty
*@returnthe<code>Color</code>convertedfromthesystem
*property.
*@seejava.lang.System#getProperty(java.lang.String)
*@seejava.lang.Integer#getInteger(java.lang.String)
*@seejava.awt.Color#Color(int)
*@sinceJDK1.0
*/
publicstaticColorgetColor(Stringnm){
returngetColor(nm,null);
}
/**
*Findsacolorinthesystemproperties.
*<p>
*Thefirstargumentistreatedasthenameofasystempropertyto
*beobtained.Thestringvalueofthispropertyistheninterpreted
*asanintegerwhichisthenconvertedtoa<code>Color</code>
*object.
*<p>
*Ifthespecifiedpropertyisnotfoundorcannotbeparsedas
*anintegerthenthe<code>Color</code>specifiedbythesecond
*argumentisreturnedinstead.
*@paramnmthenameofthecolorproperty
*@paramvthedefault<code>Color</code>
*@returnthe<code>Color</code>convertedfromthesystem
*property,orthespecified<code>Color</code>.
*@seejava.lang.System#getProperty(java.lang.String)
*@seejava.lang.Integer#getInteger(java.lang.String)
*@seejava.awt.Color#Color(int)
*@sinceJDK1.0
*/
publicstaticColorgetColor(Stringnm,Colorv){
Integerintval=Integer.getInteger(nm);
if(intval==null){
returnv;
}
inti=intval.intValue();
returnnewColor((i>>16)&0xFF,(i>>8)&0xFF,i&0xFF);
}
/**
*Findsacolorinthesystemproperties.
*<p>
*Thefirstargumentistreatedasthenameofasystempropertyto
*beobtained.Thestringvalueofthispropertyistheninterpreted
*asanintegerwhichisthenconvertedtoa<code>Color</code>
*object.
*<p>
*Ifthespecifiedpropertyisnotfoundorcouldnotbeparsedas
*anintegerthentheintegervalue<code>v</code>isusedinstead,
*andisconvertedtoa<code>Color</code>object.
*@paramnmthenameofthecolorproperty
*@paramvthedefaultcolorvalue,asaninteger
*@returnthe<code>Color</code>convertedfromthesystem
*propertyorthe<code>Color</code>convertedfrom
*thespecifiedinteger.
*@seejava.lang.System#getProperty(java.lang.String)
*@seejava.lang.Integer#getInteger(java.lang.String)
*@seejava.awt.Color#Color(int)
*@sinceJDK1.0
*/
publicstaticColorgetColor(Stringnm,intv){
Integerintval=Integer.getInteger(nm);
inti=(intval!=null)?intval.intValue():v;
returnnewColor((i>>16)&0xFF,(i>>8)&0xFF,(i>>0)&0xFF);
}
/**
*Convertsthecomponentsofacolor,asspecifiedbytheHSB
*model,toanequivalentsetofvaluesforthedefaultRGBmodel.
*<p>
*The<code>saturation</code>and<code>brightness</code>components
*shouldbefloating-pointvaluesbetweenzeroandone
*(numbersintherange0.0-1.0).The<code>hue</code>component
*canbeanyfloating-pointnumber.Thefloorofthisnumberis
*subtractedfromittocreateafractionbetween0and1.This
*fractionalnumberisthenmultipliedby360toproducethehue
*angleintheHSBcolormodel.
*<p>
*Theintegerthatisreturnedby<code>HSBtoRGB</code>encodesthe
*valueofacolorinbits0-23ofanintegervaluethatisthesame
*formatusedbythemethod{@link#getRGB()<code>getRGB</code>}.
*Thisintegercanbesuppliedasanargumenttothe
*<code>Color</code>constructorthattakesasingleintegerargument.
*@paramhuethehuecomponentofthecolor
*@paramsaturationthesaturationofthecolor
*@parambrightnessthebrightnessofthecolor
*@returntheRGBvalueofthecolorwiththeindicatedhue,
*saturation,andbrightness.
*@seejava.awt.Color#getRGB()
*@seejava.awt.Color#Color(int)
*@seejava.awt.image.ColorModel#getRGBdefault()
*@sinceJDK1.0
*/
publicstaticintHSBtoRGB(floathue,floatsaturation,floatbrightness){
intr=0,g=0,b=0;
if(saturation==0){
r=g=b=(int)(brightness*255.0f+0.5f);
}else{
floath=(hue-(float)Math.floor(hue))*6.0f;
floatf=h-(float)java.lang.Math.floor(h);
floatp=brightness*(1.0f-saturation);
floatq=brightness*(1.0f-saturation*f);
floatt=brightness*(1.0f-(saturation*(1.0f-f)));
switch((int)h){
case0:
r=(int)(brightness*255.0f+0.5f);
g=(int)(t*255.0f+0.5f);
b=(int)(p*255.0f+0.5f);
break;
case1:
r=(int)(q*255.0f+0.5f);
g=(int)(brightness*255.0f+0.5f);
b=(int)(p*255.0f+0.5f);
break;
case2:
r=(int)(p*255.0f+0.5f);
g=(int)(brightness*255.0f+0.5f);
b=(int)(t*255.0f+0.5f);
break;
case3:
r=(int)(p*255.0f+0.5f);
g=(int)(q*255.0f+0.5f);
b=(int)(brightness*255.0f+0.5f);
break;
case4:
r=(int)(t*255.0f+0.5f);
g=(int)(p*255.0f+0.5f);
b=(int)(brightness*255.0f+0.5f);
break;
case5:
r=(int)(brightness*255.0f+0.5f);
g=(int)(p*255.0f+0.5f);
b=(int)(q*255.0f+0.5f);
break;
}
}
return0xff000000|(r<<16)|(g<<8)|(b<<0);
}
/**
*Convertsthecomponentsofacolor,asspecifiedbythedefaultRGB
*model,toanequivalentsetofvaluesforhue,saturation,and
*brightnessthatarethethreecomponentsoftheHSBmodel.
*<p>
*Ifthe<code>hsbvals</code>argumentis<code>null</code>,thena
*newarrayisallocatedtoreturntheresult.Otherwise,themethod
*returnsthearray<code>hsbvals</code>,withthevaluesputinto
*thatarray.
*@paramrtheredcomponentofthecolor
*@paramgthegreencomponentofthecolor
*@parambthebluecomponentofthecolor
*@paramhsbvalsthearrayusedtoreturnthe
*threeHSBvalues,or<code>null</code>
*@returnanarrayofthreeelementscontainingthehue,saturation,
*andbrightness(inthatorder),ofthecolorwith
*theindicatedred,green,andbluecomponents.
*@seejava.awt.Color#getRGB()
*@seejava.awt.Color#Color(int)
*@seejava.awt.image.ColorModel#getRGBdefault()
*@sinceJDK1.0
*/
publicstaticfloat[]RGBtoHSB(intr,intg,intb,float[]hsbvals){
floathue,saturation,brightness;
if(hsbvals==null){
hsbvals=newfloat[3];
}
intcmax=(r>g)?r:g;
if(b>cmax)cmax=b;
intcmin=(r<g)?r:g;
if(b<cmin)cmin=b;
brightness=((float)cmax)/255.0f;
if(cmax!=0)
saturation=((float)(cmax-cmin))/((float)cmax);
else
saturation=0;
if(saturation==0)
hue=0;
else{
floatredc=((float)(cmax-r))/((float)(cmax-cmin));
floatgreenc=((float)(cmax-g))/((float)(cmax-cmin));
floatbluec=((float)(cmax-b))/((float)(cmax-cmin));
if(r==cmax)
hue=bluec-greenc;
elseif(g==cmax)
hue=2.0f+redc-bluec;
else
hue=4.0f+greenc-redc;
hue=hue/6.0f;
if(hue<0)
hue=hue+1.0f;
}
hsbvals[0]=hue;
hsbvals[1]=saturation;
hsbvals[2]=brightness;
returnhsbvals;
}
/**
*Createsa<code>Color</code>objectbasedonthespecifiedvalues
*fortheHSBcolormodel.
*<p>
*The<code>s</code>and<code>b</code>componentsshouldbe
*floating-pointvaluesbetweenzeroandone
*(numbersintherange0.0-1.0).The<code>h</code>component
*canbeanyfloating-pointnumber.Thefloorofthisnumberis
*subtractedfromittocreateafractionbetween0and1.This
*fractionalnumberisthenmultipliedby360toproducethehue
*angleintheHSBcolormodel.
*@paramhthehuecomponent
*@paramsthesaturationofthecolor
*@parambthebrightnessofthecolor
*@returna<code>Color</code>objectwiththespecifiedhue,
*saturation,andbrightness.
*@sinceJDK1.0
*/
publicstaticColorgetHSBColor(floath,floats,floatb){
returnnewColor(HSBtoRGB(h,s,b));
}
/**
*Returnsa<code>float</code>arraycontainingthecolorandalpha
*componentsofthe<code>Color</code>,asrepresentedinthedefault
*sRGBcolorspace.
*If<code>compArray</code>is<code>null</code>,anarrayoflength
*4iscreatedforthereturnvalue.Otherwise,
*<code>compArray</code>musthavelength4orgreater,
*anditisfilledinwiththecomponentsandreturned.
*@paramcompArrayanarraythatthismethodfillswith
*colorandalphacomponentsandreturns
*@returntheRGBAcomponentsina<code>float</code>array.
*/
publicfloat[]getRGBComponents(float[]compArray){
float[]f;
if(compArray==null){
f=newfloat[4];
}else{
f=compArray;
}
if(frgbvalue==null){
f[0]=((float)getRed())/255f;
f[1]=((float)getGreen())/255f;
f[2]=((float)getBlue())/255f;
f[3]=((float)getAlpha())/255f;
}else{
f[0]=frgbvalue[0];
f[1]=frgbvalue[1];
f[2]=frgbvalue[2];
f[3]=falpha;
}
returnf;
}
/**
*Returnsa<code>float</code>arraycontainingonlythecolor
*componentsofthe<code>Color</code>,inthedefaultsRGBcolor
*space.If<code>compArray</code>is<code>null</code>,anarrayof
*length3iscreatedforthereturnvalue.Otherwise,
*<code>compArray</code>musthavelength3orgreater,anditis
*filledinwiththecomponentsandreturned.
*@paramcompArrayanarraythatthismethodfillswithcolor
*componentsandreturns
*@returntheRGBcomponentsina<code>float</code>array.
*/
publicfloat[]getRGBColorComponents(float[]compArray){
float[]f;
if(compArray==null){
f=newfloat[3];
}else{
f=compArray;
}
if(frgbvalue==null){
f[0]=((float)getRed())/255f;
f[1]=((float)getGreen())/255f;
f[2]=((float)getBlue())/255f;
}else{
f[0]=frgbvalue[0];
f[1]=frgbvalue[1];
f[2]=frgbvalue[2];
}
returnf;
}
/**
*Returnsa<code>float</code>arraycontainingthecolorandalpha
*componentsofthe<code>Color</code>,inthe
*<code>ColorSpace</code>ofthe<code>Color</code>.
*If<code>compArray</code>is<code>null</code>,anarraywith
*lengthequaltothenumberofcomponentsintheassociated
*<code>ColorSpace</code>plusoneiscreatedfor
*thereturnvalue.Otherwise,<code>compArray</code>musthaveat
*leastthislengthanditisfilledinwiththecomponentsand
*returned.
*@paramcompArrayanarraythatthismethodfillswiththecolorand
*alphacomponentsofthis<code>Color</code>inits
*<code>ColorSpace</code>andreturns
*@returnthecolorandalphacomponentsina<code>float</code>
*array.
*/
publicfloat[]getComponents(float[]compArray){
if(fvalue==null)
returngetRGBComponents(compArray);
float[]f;
intn=fvalue.length;
if(compArray==null){
f=newfloat[n+1];
}else{
f=compArray;
}
for(inti=0;i<n;i++){
f[i]=fvalue[i];
}
f[n]=falpha;
returnf;
}
/**
*Returnsa<code>float</code>arraycontainingonlythecolor
*componentsofthe<code>Color</code>,inthe
*<code>ColorSpace</code>ofthe<code>Color</code>.
*If<code>compArray</code>is<code>null</code>,anarraywith
*lengthequaltothenumberofcomponentsintheassociated
*<code>ColorSpace</code>iscreatedfor
*thereturnvalue.Otherwise,<code>compArray</code>musthaveat
*leastthislengthanditisfilledinwiththecomponentsand
*returned.
*@paramcompArrayanarraythatthismethodfillswiththecolor
*componentsofthis<code>Color</code>inits
*<code>ColorSpace</code>andreturns
*@returnthecolorcomponentsina<code>float</code>array.
*/
publicfloat[]getColorComponents(float[]compArray){
if(fvalue==null)
returngetRGBColorComponents(compArray);
float[]f;
intn=fvalue.length;
if(compArray==null){
f=newfloat[n];
}else{
f=compArray;
}
for(inti=0;i<n;i++){
f[i]=fvalue[i];
}
returnf;
}
/**
*Returnsa<code>float</code>arraycontainingthecolorandalpha
*componentsofthe<code>Color</code>,inthe
*<code>ColorSpace</code>specifiedbythe<code>cspace</code>
*parameter.If<code>compArray</code>is<code>null</code>,an
*arraywithlengthequaltothenumberofcomponentsin
*<code>cspace</code>plusoneiscreatedforthereturnvalue.
*Otherwise,<code>compArray</code>musthaveatleastthis
*length,anditisfilledinwiththecomponentsandreturned.
*@paramcspaceaspecified<code>ColorSpace</code>
*@paramcompArrayanarraythatthismethodfillswiththe
*colorandalphacomponentsofthis<code>Color</code>in
*thespecified<code>ColorSpace</code>andreturns
*@returnthecolorandalphacomponentsina<code>float</code>
*array.
*/
publicfloat[]getComponents(ColorSpacecspace,float[]compArray){
if(cs==null){
cs=ColorSpace.getInstance(ColorSpace.CS_sRGB);
}
floatf[];
if(fvalue==null){
f=newfloat[3];
f[0]=((float)getRed())/255f;
f[1]=((float)getGreen())/255f;
f[2]=((float)getBlue())/255f;
}else{
f=fvalue;
}
floattmp[]=cs.toCIEXYZ(f);
floattmpout[]=cspace.fromCIEXYZ(tmp);
if(compArray==null){
compArray=newfloat[tmpout.length+1];
}
for(inti=0;i<tmpout.length;i++){
compArray[i]=tmpout[i];
}
if(fvalue==null){
compArray[tmpout.length]=((float)getAlpha())/255f;
}else{
compArray[tmpout.length]=falpha;
}
returncompArray;
}
/**
*Returnsa<code>float</code>arraycontainingonlythecolor
*componentsofthe<code>Color</code>inthe
*<code>ColorSpace</code>specifiedbythe<code>cspace</code>
*parameter.If<code>compArray</code>is<code>null</code>,anarray
*withlengthequaltothenumberofcomponentsin
*<code>cspace</code>iscreatedforthereturnvalue.Otherwise,
*<code>compArray</code>musthaveatleastthislength,anditis
*filledinwiththecomponentsandreturned.
*@paramcspaceaspecified<code>ColorSpace</code>
*@paramcompArrayanarraythatthismethodfillswiththecolor
*componentsofthis<code>Color</code>inthespecified
*<code>ColorSpace</code>
*@returnthecolorcomponentsina<code>float</code>array.
*/
publicfloat[]getColorComponents(ColorSpacecspace,float[]compArray){
if(cs==null){
cs=ColorSpace.getInstance(ColorSpace.CS_sRGB);
}
floatf[];
if(fvalue==null){
f=newfloat[3];
f[0]=((float)getRed())/255f;
f[1]=((float)getGreen())/255f;
f[2]=((float)getBlue())/255f;
}else{
f=fvalue;
}
floattmp[]=cs.toCIEXYZ(f);
floattmpout[]=cspace.fromCIEXYZ(tmp);
if(compArray==null){
returntmpout;
}
for(inti=0;i<tmpout.length;i++){
compArray[i]=tmpout[i];
}
returncompArray;
}
/**
*Returnsthe<code>ColorSpace</code>ofthis<code>Color</code>.
*@returnthis<code>Color</code>object's<code>ColorSpace</code>.
*/
publicColorSpacegetColorSpace(){
if(cs==null){
cs=ColorSpace.getInstance(ColorSpace.CS_sRGB);
}
returncs;
}
//REMIND:thisshouldreallybeaRef!
/**
*Thepaintcontextusedtogenerateasolidcolorpattern.
*@seecreateContext()
*/
transientprivatePaintContexttheContext;
/**
*Createsandreturnsa{@linkPaintContext}usedtogenerateasolid
*colorpattern.Thisenablesa<code>Color</code>objecttobeused
*asanargumenttoanymethodrequiringanobjectimplementingthe
*{@linkPaint}interface.
*Thesame<code>PaintContext</code>isreturned,regardlessof
*whetherornot<code>r</code>,<code>r2d</code>,
*<code>xform</code>,or<code>hints</code>are<code>null</code>.
*@paramcmthespecified<code>ColorModel</code>
*@paramrthespecified{@linkRectangle}
*@paramr2dthespecified{@linkRectangle2D}
*@paramxformthespecified{@linkAffineTransform}
*@paramhintsthespecified{@linkRenderingHints}
*@returna<code>PaintContext</code>thatisusedtogeneratea
*solidcolorpattern.
*@seePaint
*@seePaintContext
*@seeGraphics2D#setPaint
*/
publicsynchronizedPaintContextcreateContext(ColorModelcm,Rectangler,
Rectangle2Dr2d,
AffineTransformxform,
RenderingHintshints){
PaintContextpc=theContext;
if(pc==null||((ColorPaintContext)pc).color!=getRGB()){
pc=newColorPaintContext(getRGB(),cm);
theContext=pc;
}
returnpc;
}
/**
*Returnsthetransparencymodeforthis<code>Color</code>.Thisis
*requiredtoimplementthe<code>Paint</code>interface.
*@returnthis<code>Color</code>object'stransparencymode.
*@seePaint
*@seeTransparency
*@see#createContext
*/
publicintgetTransparency(){
intalpha=getAlpha();
if(alpha==0xff){
returnTransparency.OPAQUE;
}
elseif(alpha==0){
returnTransparency.BITMASK;
}
else{
returnTransparency.TRANSLUCENT;
}
}
}
分享到:
评论

相关推荐

    计算机图形学源代码.zip

    在这个"计算机图形学源代码.zip"压缩包中,我们很显然拥有一系列使用VS2017(Visual Studio 2017)编译环境的源代码,这可能是用于教学、学习或者实践计算机图形学原理的项目。VS2017是一款强大的集成开发环境,支持...

    java画图工具(draw)

    java画图工具(draw) 有源代码 可以画多种图形

    java计算机图形学代码

    在这个Java实现的图形学实验代码中,我们关注的是图形的旋转和平移操作,这些都是在2D或3D图形处理中非常基础且重要的概念。 首先,我们要理解什么是图形的旋转。在计算机图形学中,旋转通常是指围绕一个固定点(也...

    Bezier曲线代码 java

    在Java代码中,你可能会看到如下的伪代码结构: ```java public class BezierCurve { private Point[] controlPoints; public BezierCurve(Point[] points) { this.controlPoints = points; } public Point ...

    draw2d 示例代码

    Eclipse Draw2D 是一个强大的图形用户界面库,主要用于在Java环境中创建和管理2D图形。它作为Eclipse RCP( Rich Client Platform)的一部分,为开发者提供了丰富的图形绘制和交互功能,是开发图形化应用的理想选择...

    Java中如何使用Draw2D和SWT绘图

    在Java编程中,Draw2D库是一个强大的工具,它允许开发者使用SWT(Standard Widget Toolkit)来创建复杂的图形用户界面,特别适用于绘制图形和图表。Draw2D是Eclipse项目的一部分,它提供了一套丰富的API,可以方便地...

    java-source-to-draw.io:从Java源代码生成draw.io图-java source code

    1. 项目源代码:通常包含Java代码,用于读取、解析和转换Java源代码。 2. 工具或脚本:可能有用于自动化转换过程的脚本,如批处理脚本或Makefile。 3. 示例:可能包含示例Java项目或源代码,用于演示如何使用该工具...

    在Java中使用Draw2D和SWT绘图的源码

    Java中的Draw2D和SWT(Standard Widget Toolkit)是两种强大的图形用户界面(GUI)工具,它们被广泛用于创建复杂的2D图形和可视化应用程序。在Java编程中,这两个库为开发者提供了丰富的功能,使得在屏幕上绘制高...

    Java源代码常用图形的绘制.rar

    这个名为"Java源代码常用图形的绘制.rar"的压缩包包含了一系列的Java源代码示例,总计300个例子,旨在帮助学习者理解和掌握在Java中如何绘制各种常见的图形。下面我们将深入探讨这些知识点。 1. **Java AWT和Swing...

    Draw.io用阿里云3D矢量图标库-基础图形

    Draw.io用阿里云3D矢量图标库-基础图形,使用请参考:[draw.io使用阿里云矢量图标库进行流程图、泳道图、UML、BPMN、架构图、部署图、原型图、用户故事图等绘制]...

    Java多线程.drawio

    Java多线程.drawio

    图形学真实感图形代码

    图形学真实感图形代码 图形学是计算机科学中的一门学科,旨在研究如何使用计算机生成图形和图像。该领域包含了许多分支,例如计算机图形、计算机视觉、图形处理和图形渲染等。 从给定的代码可以看出,这是一段使用...

    Draw_3D_matlab_

    本教程"Draw_3D_matlab_"将带你探索如何利用MATLAB来创建和操纵简单的3D图形,以及如何将2D图形转化为3D形态。 首先,MATLAB提供了丰富的图形函数,如`plot3`、`surf`、`mesh`等,用于创建3D坐标系中的点、线和面。...

    java 2d和3d使用例程

    Java 2D与3D图形学是Java编程中用于创建和显示复杂图形的重要部分。这两个技术为开发者提供了丰富的工具和接口,以便在屏幕上绘制出丰富多彩、动态交互的图像。在这个《Java计算机图形学》的例程源码中,我们可以...

    Delphi控件Draw_hss图形图像处理库

    Delphi控件Draw_hss是专门用于图形图像处理的一个强大工具集,它为开发者提供了丰富的功能,以便在Delphi环境中高效地进行图像操作。在本文中,我们将深入探讨这个库的核心概念、主要功能以及如何在实际开发中应用。...

    java代码实现代码雨

    Java代码实现代码雨屏保效果是一种有趣的编程实践,它可以模拟屏幕上的字符持续下落,创造出类似电影中的“黑客帝国”特效。在这个项目中,我们将深入探讨如何使用Java语言来创建这种视觉效果。 首先,我们需要理解...

    基于Java画图源代码

    在Java编程语言中,画图功能是通过Java的图形用户界面(GUI)库来实现的,特别是`java.awt`和`javax.swing`包中的类。本文将深入探讨如何使用Java...通过深入研究这些代码,可以更好地理解和掌握Java图形编程的精髓。

    情人节-3D爱心代码,拿走不谢

    通过以上代码及解析,我们可以了解到如何使用Python结合Matplotlib库绘制3D爱心图形。这不仅是一项有趣的技能,也能帮助我们在数据分析或可视化项目中发挥创意。希望本文能激发你探索更多关于数据可视化的可能性!

    《Programming Role Playing Games with DirectX》第二版chap 2的Draw2D和Draw3D代码

    《Programming Role Playing Games with DirectX》第二版的 chap 2 提供了 Draw2D 和 Draw3D 的源代码,这是深入理解 DirectX 在游戏开发中的应用的关键部分。DirectX 是微软推出的一套 API(应用程序接口),主要...

    java的 图形及图像的绘制处理.

    Java图形和图像的绘制处理是Java编程中的一部分,主要用于创建可视化界面和动态效果。在Java中,图形绘制主要依赖于`java.awt`和`javax.swing`包中的类和接口。 首先,我们来看一下图形环境(Graphics Context)。...

Global site tag (gtag.js) - Google Analytics