jotto

Untitled

Jun 14th, 2014
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.85 KB | None | 0 0
  1. import java.applet.Applet;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import com.sun.j3d.utils.applet.MainFrame;
  5. import com.sun.j3d.utils.behaviors.vp.OrbitBehavior;
  6. import com.sun.j3d.utils.geometry.GeometryInfo;
  7. import com.sun.j3d.utils.geometry.Cylinder;
  8. import com.sun.j3d.utils.geometry.Sphere;
  9. import com.sun.j3d.utils.geometry.NormalGenerator;
  10. import com.sun.j3d.utils.universe.*;
  11. import java.util.Enumeration;
  12. import javax.media.j3d.*;
  13. import javax.vecmath.*;
  14. import java.util.Timer;
  15. import java.util.TimerTask;
  16. import javax.swing.BoxLayout;
  17. import javax.swing.JLabel;
  18. import javax.swing.JPanel;
  19. import javax.swing.JTextField;
  20. import javax.swing.JButton;
  21. import javax.swing.Box;
  22. import javax.swing.JOptionPane;
  23.  
  24. /**
  25.  * Klasa główna 'Main' zawiera deklaracje zmiennych
  26.  * @author
  27.  */
  28.  
  29. public final class Main extends Applet implements KeyListener{
  30.    
  31.     final private static int Width = 900;
  32.     final private static int Height = 600;
  33.     final private OrbitBehavior obserwator;
  34.     final private ViewingPlatform vPlatform;
  35.     private RotationInterpolator punkt1; // arm sweep - baza robota
  36.     private RotationInterpolator punkt2; // shoulder - ramie robota
  37.     private RotationInterpolator punkt3;
  38.     final private Timer zegar = new Timer();
  39.     final private SimpleUniverse universe;
  40.     private double x = 0.0d;
  41.     private double y = 0.65d;
  42.     private double z = 0.5d;
  43.     private double y2;
  44.     private double z2;
  45.     private boolean spacja = false;
  46.     private boolean zatrzask = false;
  47.     private boolean inCollision = false;
  48.     private boolean raz = false;
  49.     private TransformGroup objTrans;
  50.     private TransformGroup objTrans2;
  51.     private TransformGroup objTrans3;
  52.     private TransformGroup objTrans4;
  53.     final private Transform3D trans = new Transform3D();
  54.     final private Transform3D trans2 = new Transform3D();
  55.     final private Transform3D trans3 = new Transform3D();
  56.     final private Transform3D trans4 = new Transform3D();
  57.     final private Transform3D trans5 = new Transform3D();
  58.     final private Transform3D commonRotation = new Transform3D();
  59.     final private Transform3D temp = new Transform3D();
  60.     JLabel label = new JLabel("Ramię Robota:");
  61.     JPanel gui = new JPanel();
  62.     JTextField tf1 = new JTextField(1);
  63.     JTextField tf2 = new JTextField(1);
  64.     JTextField tf3 = new JTextField(1);
  65.     JLabel tf1_label = new JLabel("Położenie wokół osi Z");
  66.     JLabel tf2_label = new JLabel("Położenie w pionie");
  67.     JLabel tf3_label = new JLabel("Położenie w poziomie");
  68.     JButton zapis = new JButton("Ustaw");
  69.    
  70.    
  71.     /**
  72.      * W metodzie tworzymy scenę oraz elementy, które będą w niej zawarte - tj.
  73.      * elementy manipulatora cylindrycznego (cylinder, cylinder2, chwytak i przedmiot),
  74.      * oświetlenie sceny oraz podłoże służące jako punkt odniesienia.
  75.      * @return obiekt 'scena' typu BranchGroup
  76.      */
  77.     public BranchGroup createSceneGraph() {
  78.  
  79.        BranchGroup scena = new BranchGroup(); // scena główna - swiatla, podloga
  80.        BoundingSphere bounds = new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0);
  81.        
  82.              
  83.        objTrans = new TransformGroup();
  84.        objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
  85.        objTrans2 = new TransformGroup();
  86.        objTrans2.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
  87.        
  88.        //statyw
  89.        scena.addChild(objTrans);
  90.        Cylinder cylinder1 = new Cylinder(0.1f, 1.5f);
  91.        objTrans = new TransformGroup();
  92.        objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
  93.        Transform3D pos1 = new Transform3D();
  94.        pos1.setTranslation(new Vector3f(0.0f, 0.25f, 0.0f));
  95.        objTrans.setTransform(pos1);
  96.        objTrans.addChild(cylinder1);
  97.        //scena.addChild(objTrans);
  98.        
  99.        //ramie
  100.        scena.addChild(objTrans2);
  101.        Cylinder cylinder2 = new Cylinder(0.05f, 1.25f);
  102.        objTrans2 = new TransformGroup();
  103.        objTrans2.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
  104.        objTrans2.addChild(cylinder2);
  105.        
  106.        //kulka
  107.        scena.addChild(objTrans3);
  108.        Sphere chwytak = new Sphere(0.08f);
  109.        objTrans3 = new TransformGroup();
  110.        objTrans3.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
  111.        objTrans3.addChild(chwytak);
  112.        scena.addChild(objTrans3);
  113.        
  114.        //kulka
  115.        scena.addChild(objTrans4);      
  116.        Appearance app = new Appearance();
  117.        Material mat = new Material(
  118.                new Color3f(.0f,.0f,.0f),
  119.                new Color3f(.0f,.0f,.0f),
  120.                new Color3f(0.4f,0.4f,0.4f),
  121.                new Color3f(0.7f,0.7f,0.7f),
  122.                64);
  123.        app.setColoringAttributes(new ColoringAttributes(1.0f, 0.0f, 0.0f,ColoringAttributes.ALLOW_COLOR_WRITE|ColoringAttributes.SHADE_GOURAUD));  
  124.        app.setMaterial(mat);
  125.        app.setCapability(app.ALLOW_COLORING_ATTRIBUTES_WRITE);
  126.        app.setCapability(app.ALLOW_MATERIAL_WRITE);
  127.        Sphere przedmiot = new Sphere(0.1f, app);  
  128.        objTrans4 = new TransformGroup();
  129.        objTrans4.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
  130.        Transform3D kulka2 = new Transform3D();
  131.        kulka2.setTranslation(new Vector3f(1.0f, -0.4f, 0.0f));
  132.        objTrans4.setTransform(kulka2);
  133.        objTrans4.addChild(przedmiot);
  134.        scena.addChild(objTrans4);
  135.        
  136.        // podłoże
  137.        Appearance ap = new Appearance();
  138.        ap.setMaterial(new Material(
  139.                new Color3f(0.8f,.8f,.8f),
  140.                new Color3f(.0f,.0f,.0f),
  141.                new Color3f(0.8f,.8f,.8f),
  142.                new Color3f(.0f,.0f,.0f),
  143.                80f
  144.        ));
  145.        podloga ob = new podloga();
  146.        ob.setAppearance(ap);
  147.        scena.addChild(ob);
  148.        
  149.        // światło kierunkowe
  150.        Color3f light1Color = new Color3f(1.0f, 1.0f, 1.0f);
  151.        Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
  152.        DirectionalLight light1 = new DirectionalLight(light1Color, light1Direction);
  153.        light1.setInfluencingBounds(bounds);
  154.        scena.addChild(light1);
  155.        
  156.        // światło
  157.        Color3f ambientColor = new Color3f(1.0f, 1.0f, 1.0f);
  158.        AmbientLight ambientLightNode = new AmbientLight(ambientColor);
  159.        ambientLightNode.setInfluencingBounds(bounds);
  160.        scena.addChild(ambientLightNode);
  161.        
  162.        //objTrans2.addChild(objTrans3);
  163.        objTrans.addChild(objTrans2);
  164.        scena.addChild(objTrans);
  165.      
  166.         // Create a new Behavior object that will perform the collision
  167.         // detection on the specified object, and add it into
  168.         // the scene graph.
  169.         CollisionDetector cd = new CollisionDetector(przedmiot);
  170.         BoundingSphere boundy = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),
  171.             1.0);
  172.         cd.setSchedulingBounds(boundy);      
  173.         objTrans3.addChild(cd);
  174.        
  175.        scena.compile();
  176.        return scena;
  177.     }
  178.    
  179.  
  180.     /**
  181.      * Konstruktor bezparametrowy klasy 'Main'. Ustawia on wygląd okna programu
  182.      * (BorderLayout()), tworzy w nim podstawowe obiekty Java3D (SimpleUniverse).
  183.      * Ustawia pozycję i zachowanie kamery oraz uruchamia zegar.
  184.      */
  185.     public Main() {
  186.         setLayout(new BorderLayout());
  187.        
  188.         GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
  189.         Canvas3D canvas3D = new Canvas3D(config);
  190.         add("Center", canvas3D);
  191.         canvas3D.addKeyListener(this);
  192.         add("South",label);
  193.        
  194.         add("East", gui);
  195.         gui.setLayout(new BoxLayout(gui, BoxLayout.Y_AXIS));
  196.         Box left = Box.createVerticalBox();
  197.         Box right = Box.createVerticalBox();
  198.         Box top = Box.createHorizontalBox();
  199.         tf1.setMaximumSize(new Dimension(150, tf1.getPreferredSize().height));
  200.         tf2.setMaximumSize(new Dimension(150, tf2.getPreferredSize().height));
  201.         tf3.setMaximumSize(new Dimension(150, tf3.getPreferredSize().height));
  202.         zapis.setPreferredSize(new Dimension(150, zapis.getPreferredSize().height));
  203.         left.add(tf1_label);
  204.         left.add(Box.createVerticalStrut(10));
  205.         left.add(tf2_label);
  206.         left.add(Box.createVerticalStrut(10));
  207.         left.add(tf3_label);
  208.         right.add(tf1); tf1.setText("0");
  209.         right.add(Box.createVerticalStrut(10));
  210.         right.add(tf2); tf2.setText("0.65");
  211.         right.add(Box.createVerticalStrut(10));
  212.         right.add(tf3); tf3.setText("0.5");
  213.    
  214.         top.add(left);
  215.         top.add(right);
  216.         gui.add(Box.createVerticalStrut(15));
  217.         gui.add(top, BorderLayout.CENTER);
  218.         gui.add(Box.createVerticalStrut(15));
  219.         gui.add(zapis);
  220.        
  221.         zapis.addActionListener(new ActionListener() {
  222.             @Override
  223.             public void actionPerformed(ActionEvent evt) {
  224.                 double xt, yt, zt;
  225.                
  226.                 //xt = Math.round(Math.toDegrees(Double.parseDouble(tf1.getText())));
  227.                 xt = (Math.PI/180*Double.parseDouble(tf1.getText()));
  228.                 yt = Double.parseDouble(tf2.getText());
  229.                 zt = Double.parseDouble(tf3.getText());
  230.                
  231.                 if(xt>360 || xt<0) {
  232.                     JOptionPane.showMessageDialog(null, "Niepoprawna wartość x\n"
  233.                             + "Musi zawierać się w 0<=x<=360");
  234.                 } else {
  235.                     x = xt;
  236.                 }
  237.                
  238.                 if(yt>0.65 || yt<-0.65) {
  239.                     JOptionPane.showMessageDialog(null, "Niepoprawna wartość y\n"
  240.                             + "Musi zawierać się w -0.65<=y<=0.65");
  241.                 } else {
  242.                     y = yt;
  243.                 }
  244.                 if(zt>0.5 || zt<-0.3) {
  245.                     JOptionPane.showMessageDialog(null, "Niepoprawna wartość z\n"
  246.                             + "Musi zawierać się w -0.3<=z<=0.5");
  247.                 } else {
  248.                     z = zt;
  249.                 }
  250.  
  251.             }
  252.         });
  253.        
  254.         // Create a simple scene and attach it to the virtual universe
  255.         BranchGroup scene = createSceneGraph();
  256.         universe = new SimpleUniverse(canvas3D);
  257.         universe.addBranchGraph(scene);
  258.         obserwator = new OrbitBehavior(canvas3D);
  259.         BoundingSphere bounds = new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0);
  260.         obserwator.setSchedulingBounds(bounds);
  261.         vPlatform = universe.getViewingPlatform();
  262.         Transform3D temp = new Transform3D();
  263.         temp.set(new Vector3f(0f,0f,7.0f));
  264.         vPlatform.getViewPlatformTransform().setTransform(temp);
  265.         vPlatform.setViewPlatformBehavior(obserwator);
  266.         zegar.scheduleAtFixedRate(new Ruch(), 20, 25);
  267.     }
  268.    
  269.     /**
  270.      * Funkcja tworzy okno typu MainFrame o zadanych wymiarach Width i Height.
  271.      * Konstruktor okna wywołuje konstruktor klasy Main().
  272.      * @param args
  273.      */
  274.     public static void main(String[] args) {
  275.        //Main bb = new Main();  
  276.        MainFrame mf = new MainFrame(new Main(),Width, Height);
  277.     }
  278.    
  279. /******************************************************************************/    
  280.    
  281.   class CollisionDetector extends Behavior {
  282.   private final Color3f highlightColor = new Color3f(0.0f, 1.0f, 0.0f);
  283.  
  284.   private final ColoringAttributes highlight = new ColoringAttributes(
  285.       highlightColor, ColoringAttributes.SHADE_GOURAUD);
  286.  
  287.   final private Sphere sferka;
  288.   final private ColoringAttributes shapeColoring;
  289.   final private Appearance shapeAppearance;
  290.   private WakeupOnCollisionEntry wEnter;
  291.   private WakeupOnCollisionExit wExit;
  292.  
  293.   public CollisionDetector(Sphere s) {
  294.     sferka = s;
  295.     shapeAppearance = sferka.getAppearance();
  296.     shapeColoring = shapeAppearance.getColoringAttributes();
  297.     inCollision = false;
  298.   }
  299.  
  300.   @Override
  301.   public void initialize() {
  302.     wEnter = new WakeupOnCollisionEntry(sferka);
  303.     wExit = new WakeupOnCollisionExit(sferka);
  304.     wakeupOn(wEnter);
  305.   }
  306.  
  307.   @Override
  308.   public void processStimulus(Enumeration criteria) {
  309.     inCollision = !inCollision;
  310.  
  311.     if (inCollision) {
  312.       shapeAppearance.setColoringAttributes(highlight);
  313.       wakeupOn(wExit);
  314.     } else {
  315.       shapeAppearance.setColoringAttributes(shapeColoring);
  316.       wakeupOn(wEnter);
  317.     }
  318.   }
  319.   }
  320.  
  321. /******************************************************************************/    
  322.    /**
  323.     *
  324.     * @param f
  325.     * @return
  326.     */
  327.    public static float round (double f)
  328.  
  329.    {  float temp = (float)(f*(Math.pow(10, 0)));
  330.  
  331.           temp = (Math.round(temp));
  332.  
  333.           temp = temp/(int)(Math.pow(10, 0));
  334.  
  335.           return temp;
  336.    }
  337.     /**
  338.      * Funkcja wychwytuje zdarzenie wciśniecią przycisku na klawiaturze.
  339.      * Zawiera obsługę przycisków służących do manipulacji robotem.
  340.      * UP, DOWN     - przesuw ramienia w pionie
  341.      * LEFT, RIGHT  - obrót ramienia wokół jego osi pionowej
  342.      * A, S         - przesuw ramienia w poziomie (wysuwanie, wsuwanie)
  343.      * Z            - standardowe ustawienie kamery
  344.      * @param e (KeyEvent)
  345.      */
  346.     @Override
  347.     public void keyPressed(KeyEvent e) {
  348.         if(e.getKeyCode() == KeyEvent.VK_Z){
  349.             vPlatform.setNominalViewingTransform();
  350.         }
  351.         if (Math.round(Math.toDegrees(x))==360) x=Math.toRadians(0);
  352.         if (Math.toDegrees(x)==0) x=Math.toRadians(359.9999999999974);
  353.         switch(e.getKeyCode()){
  354.             case KeyEvent.VK_UP:
  355.                 if(y < 0.65f) {
  356.                     y += 0.05;
  357.                 }
  358.                 break;
  359.             case KeyEvent.VK_DOWN:
  360.                 if(y > -0.6f) {
  361.                     y -= 0.05;
  362.                 }
  363.                 break;
  364.             case KeyEvent.VK_LEFT:
  365.                 x -= Math.PI/180;
  366.                 break;
  367.             case KeyEvent.VK_RIGHT:
  368.                 x += Math.PI/180;
  369.                 break;
  370.             case KeyEvent.VK_A:
  371.                 if(z > -0.3f) {
  372.                     z -= 0.05;
  373.                 }
  374.                 break;
  375.             case KeyEvent.VK_S:
  376.                 if(z < 0.5f) {
  377.                     z += 0.05;
  378.                 }
  379.                 break;
  380.             case KeyEvent.VK_SPACE:
  381.                 spacja = !spacja;
  382.                 zatrzask = true;
  383.                 break;
  384.         }
  385.     }
  386.  
  387.     /**
  388.      * Funkcja wychwytująca puszczenie przycisku klawiatury - nie używana.
  389.      * @param e
  390.      */
  391.     @Override
  392.     public void keyReleased(KeyEvent e){
  393.         switch(e.getKeyCode()){
  394.             case KeyEvent.VK_SPACE:
  395.                 zatrzask = false;
  396.                 raz=true;
  397.                 break;
  398.             case KeyEvent.VK_UP:
  399.             case KeyEvent.VK_DOWN:
  400.             case KeyEvent.VK_LEFT:
  401.             case KeyEvent.VK_RIGHT:
  402.             case KeyEvent.VK_A:
  403.             case KeyEvent.VK_S:
  404.                 tf1.setText(Math.round(Math.toDegrees(x)) + "");
  405.                 tf2.setText(y + "");
  406.                 tf3.setText(z + "");
  407.                 break;
  408.         }
  409.     }
  410.  
  411.     /**
  412.      * Funkcja wychwytująca sygnał przycisku klawiatury - nie używana.
  413.      * @param e
  414.      */
  415.     @Override
  416.     public void keyTyped(KeyEvent e){
  417.     }
  418.    
  419.  
  420. //    @Override
  421. //    public void mouseMoved(MouseEvent e) {
  422. //       // x = (float)(e.getX())/Width-.5f;
  423. //        //y = -(float)(e.getY())/Height+.5f;
  424. //    }
  425.    
  426.     /**
  427.      * Klasa dziedzicząca po klasie TimerTask.
  428.      * Zawiera funkcję run().
  429.      */
  430.     private class Ruch extends TimerTask{
  431.         /**
  432.          * Zadaniem funkcji jest przekształcanie
  433.          * sceny w zależności od parametrów (zmienne globalne) oraz wyświetlanie
  434.          * informacji o aktualnych wartościach parametrów w dolnym pasku
  435.          * informacyjnym.
  436.          */
  437.         @Override
  438.         public void run() {    
  439.             commonRotation.rotY(x);
  440.            
  441.             trans2.rotX(Math.PI/2);
  442.             trans2.setTranslation(new Vector3d(0.0f, y, z));
  443.             trans2.mul(commonRotation, trans2);
  444.             objTrans2.setTransform(trans2);
  445.            
  446.             trans3.setTranslation(new Vector3d(0.0f,y+0.25,z+0.6));
  447.             trans3.mul(commonRotation, trans3);
  448.             objTrans3.setTransform(trans3);
  449.            
  450.             trans4.setTranslation(new Vector3d(0.0f, y+0.25, z+0.64));
  451.             trans4.mul(commonRotation, trans4);
  452.            
  453.             if(raz&&!spacja&&inCollision){
  454.                 raz=false;
  455.                
  456.                 temp.rotY(x);
  457.                 y2=y;
  458.                 z2=z;
  459.             }
  460.            
  461.             if (y2>-0.3){
  462.                 y2-=0.01;
  463.             }
  464.            
  465.             trans5.setTranslation(new Vector3d(0.0f, y2, z2+0.6f));
  466.             trans5.mul(temp, trans5);
  467.             if (spacja&&inCollision) {
  468.                 objTrans4.setTransform(trans4);
  469.             }
  470.             else {
  471.                 objTrans4.setTransform(trans5);
  472.             }
  473.            
  474.             if (spacja&&inCollision) {
  475.                 objTrans4.setTransform(trans4);
  476.             }
  477.            
  478.             if(spacja) {
  479.                 if(inCollision) {
  480.                     label.setText("Chwytak: aktywny;    Przedmiot: chwycony");
  481.                 } else {
  482.                     label.setText("Chwytak: aktywny;    Przedmiot: swobodny");
  483.                 }
  484.             } else {
  485.                 label.setText("Chwytak: nieaktywny");
  486.             }
  487.         }
  488.     }
  489.  
  490.     /**
  491.      * Klasa 'podloga' dziedzicząca po klasie 'Shape3D'.
  492.      */
  493.     public class podloga extends Shape3D{ // podłoże robota
  494.         final private Point3f A= new Point3f(-5.0f, -0.5f, -5.0f);
  495.         final private Point3f B= new Point3f(-5.0f, -0.5f, 5.0f);
  496.         final private Point3f C= new Point3f(5.0f, -0.5f, 5.0f);
  497.         final private Point3f D= new Point3f(5.0f, -0.5f, -5.0f);
  498.         final private Point3f[] pts = new Point3f[8];
  499.         int[] stripCounts= new int[2];
  500.         int[] contourCount=new int[2];
  501.        
  502.         /**
  503.          * Konstruktor bezparametrowy klasy 'podloga'. Tworzy punkt odniesienia
  504.          * dla manipulatora.
  505.          */
  506.         public podloga(){
  507.             // front
  508.             pts[0]=C;
  509.             pts[1]=D;
  510.             pts[2]=A;
  511.             pts[3]=B;
  512.             //back
  513.             pts[4]=C;
  514.             pts[5]=B;
  515.             pts[6]=A;
  516.             pts[7]=D;
  517.            
  518.             stripCounts[0]=4;
  519.             stripCounts[1]=4;
  520.             contourCount[0]=1;
  521.             contourCount[1]=1;
  522.             GeometryInfo gInf = new GeometryInfo(GeometryInfo.POLYGON_ARRAY);
  523.             gInf.setCoordinates(pts);
  524.             gInf.setStripCounts(stripCounts);
  525.             gInf.setContourCounts(contourCount);
  526.             NormalGenerator ng= new NormalGenerator();
  527.             ng.setCreaseAngle ((float) Math.toRadians(30));
  528.             ng.generateNormals(gInf);
  529.             this.setGeometry(gInf.getGeometryArray());
  530.             }
  531.     }
  532.    
  533. }
Advertisement
Add Comment
Please, Sign In to add comment