• Advertisement
Sign in to follow this  

drag and drop

This topic is 412 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i can´t put the drag and drop work correctly

public class InventoryState_Old extends BaseAppState {

    static Logger log = LoggerFactory.getLogger(InventoryState_Old.class);

    private Container mainWindow;
    private TabbedPanel tabs;

    private final List<Action> sessionActions = new ArrayList<>();
    private Container sessionButtons;
private Node dndRoot;
    public InventoryState_Old(boolean enabled) {
        setEnabled(enabled);
            }

    /**
     * Returns the tabbed panel used in the in-game menu. This lets other states
     * potentially add their own in-game menu tabs.
     *
     * @return
     */
    public TabbedPanel getTabs() {
        return tabs;
    }
     protected Node getRoot() {

        return dndRoot;

    }

        public List<Action> getSessionActions() {
        return sessionActions;
    }

    public void toggleEnabled() {
        setEnabled(!isEnabled());
    }

    @Override
    protected void initialize(Application app) {
        mainWindow = new Container();

        //   tabs = mainWindow.addChild(new TabbedPanel());
        sessionButtons = mainWindow.addChild(new Container());
       mainWindow.setPreferredSize(new Vector3f(200, 320, 0));
        Label o = sessionButtons.addChild(new Label("Inventory", new ElementId("title")));
o.setFontSize(12);

// Button p= sessionButtons.addChild(new Button("X"),1);
        o.setTextHAlignment(HAlignment.Center);
        Label f = sessionButtons.addChild(new Label("Default Cube", new ElementId("title")));
        f.setTextHAlignment(HAlignment.Center);
       f.setFontSize(12);
        Container barra1 = sessionButtons.addChild(new Container(new SpringGridLayout(Axis.X, Axis.Y)));
        // sessionButtons.addChild(new Label("Default Cube",new ElementId("title")));
/* barra1.addChild(new Container());
        barra1.addChild(new Container());
        barra1.addChild(new Container());
        barra1.addChild(new Container());
        barra1.addChild(new Container());
        barra1.addChild(new Container());
        barra1.addChild(new Container());
        barra1.addChild(new Container());
  */
Container barra2 = sessionButtons.addChild(new Container(new SpringGridLayout(Axis.X, Axis.Y)));
      /*  barra2.addChild(new Container());
        barra2.addChild(new Container());
        barra2.addChild(new Container());
        barra2.addChild(new Container());
        barra2.addChild(new Container());
        barra2.addChild(new Container());
        barra2.addChild(new Container());
        barra2.addChild(new Container());
        */
      Container barra3 = sessionButtons.addChild(new Container(new SpringGridLayout(Axis.X, Axis.Y)));
        barra3.addChild(new Container());
        barra3.addChild(new Container());
        barra3.addChild(new Container());
        barra3.addChild(new Container());
        barra3.addChild(new Container());
        barra3.addChild(new Container());
        barra3.addChild(new Container());
        barra3.addChild(new Container());
        Label b = sessionButtons.addChild(new Label("Expanded Cube 1", new ElementId("title")));
        b.setTextHAlignment(HAlignment.Center);
       b.setFontSize(12);
        Container barra4 = sessionButtons.addChild(new Container(new SpringGridLayout(Axis.X, Axis.Y)));
        barra4.addChild(new Container());
        barra4.addChild(new Container());
        barra4.addChild(new Container());
        barra4.addChild(new Container());
        barra4.addChild(new Container());
        barra4.addChild(new Container());
        barra4.addChild(new Container());
        barra4.addChild(new Container());
        Container barra5 = sessionButtons.addChild(new Container(new SpringGridLayout(Axis.X, Axis.Y)));
        barra5.addChild(new Container());
        barra5.addChild(new Container());
        barra5.addChild(new Container());
        barra5.addChild(new Container());
        barra5.addChild(new Container());
        barra5.addChild(new Container());
        barra5.addChild(new Container());
        barra5.addChild(new Container());
        Container barra6 = sessionButtons.addChild(new Container(new SpringGridLayout(Axis.X, Axis.Y)));
        barra6.addChild(new Container());
        barra6.addChild(new Container());
        barra6.addChild(new Container());
        barra6.addChild(new Container());
        barra6.addChild(new Container());
        barra6.addChild(new Container());
        barra6.addChild(new Container());
        barra6.addChild(new Container());
        barra1.setPreferredSize(new Vector3f(50, 25, 0));
        barra2.setPreferredSize(new Vector3f(50, 25, 0));
        barra3.setPreferredSize(new Vector3f(50, 25, 0));
        barra4.setPreferredSize(new Vector3f(50, 25, 0));
        barra5.setPreferredSize(new Vector3f(50, 25, 0));
        barra6.setPreferredSize(new Vector3f(50, 25, 0));
         dndRoot = new Node("dndRoot");

 

        DirectionalLight sun = new DirectionalLight(new Vector3f(1, -2, -5).normalizeLocal(),

                                                    ColorRGBA.White);

        dndRoot.addLight(sun);

        

        AmbientLight ambient = new AmbientLight(ColorRGBA.Gray);

        dndRoot.addLight(ambient);            

 

        // Setup a stack-based container       

      //  barra1 = new Container("container1");

        barra1.setLocalTranslation(0, 0, 0); 

        

        barra1.addControl(new DragAndDropControl(new StackContainerListener( barra1)));

        barra1.addControl(new StackControl());        

        MouseEventControl.addListenersToSpatial( barra1 

                                              );

       dndRoot.attachChild( barra1);

 

        // Setup a grid based container       

     //   barra2 = new Container("container2");

       // container2.setSize(3, 3, 1);

      //  barra2.setLocalTranslation(0f, 0.0f,0);

        MouseEventControl.addListenersToSpatial( barra2);

         barra2.addControl(new GridControl(8));

         barra2.addControl(new DragAndDropControl(new GridContainerListener( barra2)));

       dndRoot.attachChild( barra2);

        

        // Add some random items to our MVC stack 'model' control

       barra1.getControl(StackControl.class).addChild(createItem());

       // container1.getControl(StackControl.class).addChild(createItem());

       // container1.getControl(StackControl.class).addChild(createItem());

        

        // Add some random items to our MVC grid 'model' control

       barra2.getControl(GridControl.class).setCell(1,0, createItem());  

     //   container2.getControl(Skills.GridControl.class).setCell(2, 1, createItem());  
        /*  for (Action a : getSessionActions()) {
            sessionButtons.addChild(new ActionButton(a));
        }
         */
        // Calculate a standard scale and position from the app's camera
        // height
        int height = app.getCamera().getHeight();
        Vector3f pref = mainWindow.getPreferredSize().clone();

        float standardScale = getState(MainMenuState.class).getStandardScale();
        pref.multLocal(1.5f * standardScale);

        // With a slight bias toward the top        
        float y = height * 0.6f + pref.y * 0.0f;

        mainWindow.setLocalTranslation(250 * standardScale, y, 0);
        //  mainWindow.setLocalScale(1.5f * standardScale);

        InputMapper inputMapper = GuiGlobals.getInstance().getInputMapper();
        inputMapper.addDelegate(MainGameFunctions.F_IN_GAME_INVENTORY, this, "toggleEnabled");
    }
private Spatial createItem() {

        Sphere sphere = new Sphere(3, 2, 1);

        Geometry geom = new Geometry("item", sphere);

        

        // Create a random color

        float r = (float)(Math.random() * 0.4 + 0.2);

        float g = (float)(Math.random() * 0.6 + 0.2);

        float b = (float)(Math.random() * 0.6 + 0.2);

        ColorRGBA color = new ColorRGBA(r, g, b, 1);

        

        Material mat = GuiGlobals.getInstance().createMaterial(color, true).getMaterial();

        //mat.getAdditionalRenderState().setWireframe(true);

        mat.setColor("Ambient", color);

        geom.setMaterial(mat);

        return geom;

    }
    @Override
    protected void cleanup(Application app) {

        InputMapper inputMapper = GuiGlobals.getInstance().getInputMapper();
        inputMapper.removeDelegate(MainGameFunctions.F_IN_GAME_INVENTORY, this, "toggleEnabled");
    }

    @Override
    protected void onEnable() {
        Node gui = ((Main) getApplication()).getGuiNode();
        gui.attachChild(mainWindow);
     ((Main)getApplication()).getRootNode().attachChild(dndRoot);
    }

    @Override
    protected void onDisable() {
        mainWindow.removeFromParent();
          dndRoot.removeFromParent();
    }
    public void update( float tpf ) {

        //System.out.println("-------- update -----");

    }
     private class StackControl extends AbstractControl {

    

        private Container node;

        private List<Spatial> model = new ArrayList<>();

 

        public StackControl() {

        }

 

        @Override       

        public void setSpatial( Spatial s ) {

            super.setSpatial(s);

            this.node = (Container)s;

            updateLayout();

        }

    

        public void addChild( Spatial child ) {

            model.add(child);

            node.attachChild(child);

            updateLayout();

        }



        public void addChild( int slot, Spatial child ) {

            model.add(slot, child);

            node.attachChild(child);

            updateLayout();

        }

        

        public void removeChild( Spatial child ) {

            model.remove(child);

            if( child.getParent() == node ) {

                node.detachChild(child);

            }            

            updateLayout();

        }



        public Spatial removeChild( int index ) {

            Spatial result = model.remove(index);

            updateLayout();

            return result;

        }

 

        protected void updateLayout() {

            int count = Math.max(1, model.size());

            node.setPreferredSize(new Vector3f(1, count, 1));

            float yStart = -(count - 1);

            for( Spatial s : model ) {

                s.setLocalTranslation(0, yStart, 0);

                yStart += 2;

            }   

        }

    

        @Override

        protected void controlUpdate( float tpf ) {

        }

    

        @Override

        protected void controlRender( RenderManager rm, ViewPort vp ) {

        }

    }



    private class GridControl extends AbstractControl {

 

        private Container node;

        private int gridSize;

        private Spatial[][] grid;

    

        public GridControl( int gridSize ) {

            this.gridSize = gridSize;

            this.grid = new Spatial[gridSize][gridSize];

        }

    

        @Override       

        public void setSpatial( Spatial s ) {

            super.setSpatial(s);

            this.node = (Container)s;

            updateLayout();

        }

        

        public Spatial getCell( int x, int y ) {

            return grid[x][y];

        }

        

        public void setCell( int x, int y, Spatial child ) {

            if( grid[x][y] != null ) {

                grid[x][y].removeFromParent();

            }

            grid[x][y] = child;

            if( child != null ) {

                node.attachChild(child);

            }

            updateLayout();

        }

 

        public Spatial removeCell( int x, int y ) {

            Spatial result = grid[x][y];

            grid[x][y] = null;

            if( result != null ) {

                updateLayout();

            }

            return result;

        }

        

        public void addChild( Spatial child ) {

            // Find the first valid cell

            for( int x = 0; x < gridSize; x++ ) {

                for( int y = 0; y < gridSize; y++ ) {

                    // just in case the child is already in the grid 

                    if( grid[x][y] == child ) {

                        return; 

                    }

                    if( grid[x][y] == null ) {

                        setCell(x, y, child);

                        return;

                    }

                }

            }            

        }

        

        public void removeChild( Spatial child ) {

            for( int x = 0; x < gridSize; x++ ) {

                for( int y = 0; y < gridSize; y++ ) {

                    if( child == grid[x][y] ) {

                        if( child.getParent() == node ) {

                            child.removeFromParent();

                        }

                        grid[x][y] = null;

                    }

                }

            }

            updateLayout();

        }



        protected void updateLayout() {

            node.setPreferredSize(new Vector3f(gridSize, gridSize, 1));

            for( int x = 0; x < gridSize; x++ ) {

                for( int y = 0; y < gridSize; y++ ) {

                    Spatial child = grid[x][y];

                    if( child != null ) {

                        child.setLocalTranslation(-(gridSize - 1) + x * 2, (gridSize - 1) - y * 2, 0);

                    }

                }

            }

        }    

        

        @Override

        protected void controlUpdate( float tpf ) {

        }

    

        @Override

        protected void controlRender( RenderManager rm, ViewPort vp ) {

        }

    }

    

    /**

     *  Listens for enter/exit events and changes the color of

     *  the geometry accordingly.

     */   

    private class HighlightListener extends DefaultMouseListener {

        private GuiMaterial material;

        private ColorRGBA enterColor;

        private ColorRGBA exitColor;

        

        public HighlightListener( GuiMaterial material, ColorRGBA enterColor, ColorRGBA exitColor ) {

            this.material = material;

            this.enterColor = enterColor;

            this.exitColor = exitColor;

        }

        

        public void mouseEntered( MouseMotionEvent event, Spatial target, Spatial capture ) {

            material.setColor(enterColor);

        }



        public void mouseExited( MouseMotionEvent event, Spatial target, Spatial capture ) {

            material.setColor(exitColor);

        }        

    }



    private class StackContainerListener implements DragAndDropListener {    



        private Spatial container;



        public StackContainerListener( Spatial container ) {

            this.container = container;            

        }



        /**

         *  Returns the container 'model' (in the MVC sense) for this

         *  container listener.

         */

        public StackControl getModel() {

            return container.getControl(StackControl.class); 

        }



        private int getIndex( Vector3f world ) {

            Vector3f local = container.worldToLocal(world, null);

            

            // Calculate the index for that location

            float y = (getModel().model.size() + local.y) / 2;

            

            return (int)y;

        }

        

        public Draggable onDragDetected( DragEvent event ) {

        

            System.out.println("Stack.onDragDetected(" + event + ")");

 

            // Find the child we collided with

            StackControl control = getModel();

            

            // For now just use the first one

            if( control.model.isEmpty() ) {

                return null;

            }

            

            int index = getIndex(event.getCollision().getContactPoint());

 

            // The item is being dragged out of the container so remove it.

            Spatial item = control.removeChild(index);

            

            // Note: the item is still a child to the container so that we

            // can get its world translation and such below.  One of the slightly

            // strange things about using Spatials instead of some game object

            // as our container items.

            

            // We'll trust that the drag session won't lose it if we need

            // to put it back.                       

            event.getSession().set(DragSession.ITEM, item);

            

            // We'll keep track of the slot we took it from so we can stick

            // it back again if the drag is canceled. 

            event.getSession().set("stackIndex", index);

 

            // Clone the dragged item to use in our draggable and stick the

            // clone in the root at the same world location.

            Spatial drag = item.clone();

            drag.setLocalTranslation(item.getWorldTranslation());

            drag.setLocalRotation(item.getWorldRotation());

            getRoot().attachChild(drag);

                   

            // Now that we've got the world location of the item we can remove

            // it from the parent spatial since it is not really a child anymore.

            // We only left it so we could easily get its world location/rotation.

            item.removeFromParent();

             

            return new ColoredDraggable(event.getViewPort(), drag, event.getLocation());

        } 

    

        public void onDragEnter( DragEvent event ) {

            System.out.println("++++++++ Stack.onDragEnter(" + event + ")");

        }

          

        public void onDragExit( DragEvent event ) {

            System.out.println("-------- Stack.onDragExit(" + event + ")");

        }

        

        public void onDragOver( DragEvent event ) {

            System.out.println("Stack.onDragOver(" + event + ")");

            

            // Any location is valid on the stack

            event.getSession().setDragStatus(DragStatus.ValidTarget);

        }  

    

        // Target specific

        public void onDrop( DragEvent event ) {

            System.out.println("Stack.onDrop(" + event + ")");

 

            // Grab the payload we stored during drag start

            Spatial draggedItem = event.getSession().get(DragSession.ITEM, null);

 

            // Add the item to this stack

            getModel().addChild(draggedItem);

        }

    

        // Source specific  

        public void onDragDone( DragEvent event ) {

            System.out.println("Stack.onDragDone(" + event + ")");            

            

            // Check to see if drop target was null as this indicates

            // that the drag operation didn't finish and we need to 

            // put the item back.           

            if( event.getSession().getDropTarget() == null ) {

                                           

                // Grab the payload we stored during drag start

                Spatial draggedItem = event.getSession().get(DragSession.ITEM, null);

            

                // Grab the original slot of the item.  We tucked this away

                // during drag start just for this case.                

                int slot = event.getSession().get("stackIndex", 0);

                

                getModel().addChild(slot, draggedItem);

            } 

        }

    }  

    

    private class GridContainerListener implements DragAndDropListener {    



        private Spatial container;



        public GridContainerListener( Spatial container ) {

            this.container = container;            

        }



        /**

         *  Returns the container 'model' (in the MVC sense) for this

         *  container listener.

         */

        public GridControl getModel() {

            return container.getControl(GridControl.class); 

        }



        private Vector2f getCellLocation( Vector3f world ) {

            Vector3f local = container.worldToLocal(world, null);

            

            // Calculate the cell location

            float x = (3 + local.x) / 2;

            float y = (3 - local.y) / 2;

            

            // This will look a little off to the user towards the right edge because

            // clicking on the surface of the box in the center cell will actually project

            // into the sphere in the last column.  But it works for a demo.  We could

            // also have made a ray and done collideWith() on the childre but I wanted

            // to show model-cell interaction instead of picking.

            int xCell = (int)x;

            int yCell = (int)y; 

 

            return new Vector2f(xCell, yCell);

        }



        public Draggable onDragDetected( DragEvent event ) {

        

            System.out.println("Grid.onDragDetected(" + event + ")");

 

            // Find the child we collided with

            GridControl control = getModel();

 

            // See where we hit

            Vector2f hit = getCellLocation(event.getCollision().getContactPoint());

 

            // Remove the item from the grid if it exists.

            Spatial item = control.removeCell((int)hit.x, (int)hit.y);

            if( item != null ) {

                // Save the item in the session so the other containers (and ourselves)

                // know what we are dragging.

                event.getSession().set(DragSession.ITEM, item);

                

                // We'll keep track of the grid cell in case the drag is

                // canceled and we have to put it back. 

                event.getSession().set("gridLocation", hit);

                

                // Clone the dragged item to use in our draggable and stick the

                // clone in the root at the same world location.

                Spatial drag = item.clone();

                drag.setLocalTranslation(item.getWorldTranslation());

                drag.setLocalRotation(item.getWorldRotation());

                getRoot().attachChild(drag);

                

                // Now that we've got the world location of the item we can remove

                // it from the parent spatial since it is not really a child anymore.

                // We only left it so we could easily get its world location/rotation.

                item.removeFromParent(); 

                

                return new ColoredDraggable(event.getViewPort(), drag, event.getLocation());

            }       

            return null;

        } 

    

        public void onDragEnter( DragEvent event ) {

            System.out.println("+++++++ Grid.onDragEnter(" + event + ")");

        }

          

        public void onDragExit( DragEvent event ) {

            System.out.println("------- Grid.onDragExit(" + event + ")");

        }

        

        public void onDragOver( DragEvent event ) {

            System.out.println("Grid.onDragOver(" + event + ")");

            

            Vector2f hit = getCellLocation(event.getCollision().getContactPoint()); 

            Spatial item = getModel().getCell((int)hit.x, (int)hit.y);

            if( item == null ) {

                // An empty cell is a valid target

                event.getSession().setDragStatus(DragStatus.ValidTarget);

            } else {

                // A filled slot is not

                event.getSession().setDragStatus(DragStatus.InvalidTarget);

            }

        }  

    

        // Target specific

        public void onDrop( DragEvent event ) {

            System.out.println("Grid.onDrop(" + event + ")");

            

            Spatial draggedItem = event.getSession().get(DragSession.ITEM, null);                        



            Vector2f hit = getCellLocation(event.getCollision().getContactPoint());

            

            // One last check to see if the drop location is available 

            Spatial item = getModel().getCell((int)hit.x, (int)hit.y);

            if( item == null ) {

                // Then we can stick the new child right in

                getModel().setCell((int)hit.x, (int)hit.y, draggedItem);

            } else {

                // It wasn't really a valid drop

                event.getSession().setDragStatus(DragStatus.InvalidTarget);   

            }

        }

    

        // Source specific  

        public void onDragDone( DragEvent event ) {

            System.out.println("Grid.onDragDone(" + event + ")");

            

            DragSession session = event.getSession();

            

            // Check to see if drop target was null as this indicates

            // that the drag operation didn't finish and we need to 

            // put the item back.                       

            if( session.getDropTarget() == null ) {

            

                // Grab the payload we stored during drag start

                Spatial draggedItem = session.get(DragSession.ITEM, null);

                

                // Grab the original slot of the item.  We tucked this away

                // during drag start just for this case.                

                Vector2f slot = session.get("gridLocation", null);

                if( slot != null ) {

                    getModel().setCell((int)slot.x, (int)slot.y, draggedItem);

                } else {

                    System.out.println("Error, missing gridLocation for dragged item");

                    // This should not ever happen but if it does we'll at least

                    // try to deal with it

                    getModel().addChild(draggedItem);

                }  

            } 

        }

    }  

    

    private class ColoredDraggable extends DefaultDraggable {

 

        private Material originalMaterial;

        private ColorRGBA color = ColorRGBA.Blue; 

        private ColorRGBA none = ColorRGBA.Gray;

        private ColorRGBA invalid = ColorRGBA.Red;

        

        private Geometry geom;

        private Material mat;

    

        public ColoredDraggable( ViewPort view, Spatial spatial, Vector2f start ) {

            super(view, spatial, start);

 

            this.geom = (Geometry)spatial;
            this.originalMaterial = geom.getMaterial(); 
            this.mat = originalMaterial.clone();
        }
        protected void setColor( ColorRGBA color ) {
            mat.setColor("Diffuse", color);
            mat.setColor("Ambient", color);
            geom.setMaterial(mat);
        }
        @Override       
        public void updateDragStatus( DragStatus status ) {
            switch( status ) {
                case InvalidTarget:
                    setColor(invalid);
                    break;
                case ValidTarget:
                    //setColor(color);
                    geom.setMaterial(originalMaterial);
                    break;  
                case NoTarget:
                default:
                    setColor(none);                    
                    break;
            }

        }        

    }
}

Share this post


Link to post
Share on other sites
Advertisement

You need an expert on the specific GUI toolkit that you use, for that.

 

This is a generic game development forum, which has very few such experts.

 

Find a forum dedicated to your GUI library, they should be able to help you.

Share this post


Link to post
Share on other sites
You might want to read the forum FAQ, especially the part about asking questions.
If you also only copy/pasted your large amount of code into that other forum without giving any more information, its no wonder people ignored you.

Share this post


Link to post
Share on other sites

thanks for the help

I create a inventory system my problem i can´t put work my grab system
i grab some code of example of pickingdemo.java
how create a grab event to grab my container and move around the map

the problem is in this code

the soluction is create a grab event i don´t know how 

 MouseEventControl.addListenersToSpatial(mainWindow,

                    new DefaultMouseListener() {

                        @Override

                      public void mouseButtonEvent(MouseButtonEvent event, Spatial target, Spatial capture) {


                       

                           if(event.getButtonIndex()==MouseInput.BUTTON_LEFT && event.isPressed()){
					event.setConsumed();
					System.out.println("Start drag");
					
				if(event.getButtonIndex()==MouseInput.BUTTON_LEFT && event.isReleased() && mainWindow != null){
					System.out.println("Stop drag");

				}
                   

                        }

                    

                        @Override
                        public void mouseEntered(MouseMotionEvent event, Spatial target, Spatial capture ) {

                            System.err.println("Passou o rato por cima");
                        
                        }



                        public void mouseExited( MouseMotionEvent event, Spatial target, Spatial capture ) {
 System.err.println("Mouse Saiu");
                                                  }                        

                    });

Edited by Landi20

Share this post


Link to post
Share on other sites

i grab some code of example of pickingdemo.java

"thowing code" at a problem pretty much never works. It akin to being lost, and simply picking a random direction and going that way. its seldom gets you closer to your goal.

You got the first step,you know what you need, a picking algo.

You also have the second step, you have some sample code.

But you don't just wire it up right quick and hope for the best. You don't even know if it even works!  You use it to learn the algo. Odds are you'll find bugs in the sample, i almost always do. I often have to use two or three samples to get one correct one. even with stuff from Rastertek.

Learn how the code works, then use it. Don't just treat it as a black box, until its passed your white box testing first.

So yes, you're going to have to learn the picking algo.

 

For 3D,  the general algo is: cast ray, check for intersections with objects / triangles etc.  For a simple pick vs ground mesh, as i recall, i check the distance to the ground at each step of the raycast.  when its close enough to zero, i return a hit.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement