Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2008, 2009, Memo Akten, www.memo.tv The Mega Super Awesome Visuals Company *** All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of MSA Visuals nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *********************************************************************
  
 
 package com.nativelibs4java.opencl.demos.particles;
 
 
 
 import javax.swing.*;
 
 import  javax.media.opengl.*;
 import static javax.media.opengl.GL.*;
 import  javax.media.opengl.awt.*;
 
 import  com.jogamp.opengl.util.*;
 import  com.jogamp.common.nio.*;
 
 import java.awt.*;
 import java.io.File;
 import java.net.URL;
 import java.util.Map;
 import static javax.media.opengl.GL.*;
 import  javax.media.opengl.glu.GLU;

Author(s):
Olivier (ported to JavaCL/OpenCL4Java)
 
 public class ParticlesDemo implements GLEventListener {
 
     public static Component createGLCanvas(int widthint heightboolean useSwing) {
         GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
         GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2));
         Component canvas = useSwing ? new GLJPanel(caps) : new GLCanvas(caps);
         canvas.setSize(widthheight);
         canvas.setIgnoreRepaint(true);
         canvas.setPreferredSize(new Dimension(widthheight));
         canvas.setSize(new Dimension(widthheight));
 
         return canvas;
     }
 
     static File lastFile;
     volatile boolean paused;
     final static float DEFAULT_MOUSE_WEIGHT = 0.7f;
     volatile float mouseWeight = ;
 
     static class ParticlesCountItem {
         public int count;
         public String string;
        public ParticlesCountItem(int countString string) {
            this. = count;
            this. = string;
        }
        @Override
        public String toString() {
            return ;
        }
    }
    public static void main(String[] args) {
        try {
            System.setProperty("sun.java2d.noddraw","true");
            try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ex) {}
            SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable();
            JFrame f = new JFrame("JavaCL Particles Demo");
            Box tb = Box.createHorizontalBox();
            final JButton openImage = new JButton("Import"), saveImage = new JButton("Export"), changeBlend = new JButton("Change Blend");
            tb.add(openImage);
            //tb.add(saveImage);
            tb.add(changeBlend);
            //final JCheckBox limi
            final AssertionError[] err = new AssertionError[1];
            final ParticlesDemo demo = new ParticlesDemo();
            final int nSpeeds = 21;
            final JSlider speedSlider = new JSlider(0, nSpeeds - 1);
            speedSlider.setValue(nSpeeds / 2);
            //f.getContentPane().add("West", slider);
            tb.add(speedSlider);
            //slider.setOrientation(JSlider.VERTICAL);
            speedSlider.addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    int d = speedSlider.getValue() - nSpeeds / 2;
                    demo.speedFactor = (d == 0 ? 1 : d > 0 ? d : -1f/d) * ;
                }
            });
            changeBlend.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    demo.iBlend = (demo.iBlend + 1) % demo.blends.length;
                }
            });
            final Component canvas = createGLCanvas(1000, 800, demo.settings.isDirectGLRendering());
            f.setLayout(new BorderLayout());
            f.add("Center"canvas);
            saveImage.addActionListener(new ActionListener() {
                @SuppressWarnings("deprecation")
                public void actionPerformed(ActionEvent ae) {
                    boolean paused = demo.paused;
                    demo.paused = true;
                    BufferedImage im = new BufferedImage(canvas.getWidth(), canvas.getHeight(), .);
                    Graphics g = im.createGraphics();
                    canvas.paint(g);
                    g.dispose();
                    FileDialog fc = new FileDialog((Frame)null);
                    fc.setMode(.);
                    fc.show();
                    if (fc.getFile() != null) {
                        try {
                            ImageIO.write(im"jpeg" = new File(new File(fc.getDirectory()), fc.getFile()));
                        } catch (Exception ex) {
                            ParticlesDemo.exception(ex);
                            Logger.getLogger(ParticlesDemo.class.getName()).log(.nullex);
                        }
                    }
                    demo.paused = paused;
                }
            });
            openImage.addActionListener(new ActionListener() {
                @SuppressWarnings("deprecation")
                public void actionPerformed(ActionEvent ae) {
                    boolean paused = demo.paused;
                    demo.paused = true;
                    FileDialog fc = new FileDialog((Frame)null);
                    fc.setMode(.);
                    fc.show();
                    if (fc.getFile() != null) {
                        try {
                            BufferedImage im = ImageIO.read( = new File(new File(fc.getDirectory()), fc.getFile()));
                            demo.setImage(im);
                        } catch (Exception ex) {
                            ParticlesDemo.exception(ex);
                            Logger.getLogger(ParticlesDemo.class.getName()).log(.nullex);
                        }
                    }
                    demo.paused = paused;
                }
            });
            canvas.addMouseWheelListener(new MouseWheelListener() {
                @Override
                public void mouseWheelMoved(MouseWheelEvent e) {
                    if (e.getUnitsToScroll() > 0)
                        for (int i = e.getUnitsToScroll(); i-- != 0;)
                            demo.mouseWeight *= 1.1f;
                    else
                        for (int i = -e.getUnitsToScroll(); i-- != 0;)
                            demo.mouseWeight /= 1.1f;
                }
            });
            canvas.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent ke) {
                    switch (ke.getKeyCode()) {
                        case .:
                            demo.paused = !demo.paused;
                            break;
                        case .:
                        case .:
                            demo.mouseWeight = 1;
                            break;
                    }
                }
            });
            final JSlider sliderMass = new JSlider(0, nSpeeds - 1);
            sliderMass.setValue(nSpeeds / 2);
            //f.getContentPane().add("East", sliderMass);
            //sliderMass.setOrientation(JSlider.VERTICAL);
            sliderMass.addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    int d = sliderMass.getValue() - nSpeeds / 2;
                    demo.massFactor = (d == 0 ? 1 : d > 0 ? d : -1f/d) * ;
                }
            });
            tb.add(sliderMass);
            f.add("North"tb);
            canvas.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getButton() != . || me.isMetaDown() || me.isControlDown())
                        demo.mouseWeight = 1;
                    else
                        demo.paused = !demo.paused;
                }
                @Override
                public void mouseExited(MouseEvent e) {
                    demo.hasMouse = false;
                }
                @Override
                public void mouseEntered(MouseEvent e) {
                    demo.hasMouse = true;
                }
            });
            canvas.addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    demo.mouseX = e.getX();
                    demo.mouseY = e.getY();
                    demo.lastMouseMove = System.currentTimeMillis();
                }
            });
            //f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
            f.pack();
            f.setVisible(true);
            FPSAnimator animator;
            if (canvas instanceof GLCanvas) {
                ((GLCanvas)canvas).addGLEventListener(demo);
                animator = new FPSAnimator(((GLCanvas)canvas), 30);
            } else {
                ((GLJPanel)canvas).addGLEventListener(demo);
                animator = new FPSAnimator(((GLJPanel)canvas), 30);
            }
            //animator.setRunAsFastAsPossible(true);
            animator.start();
        } catch (Exception ex) {
            exception(ex);
            Logger.getLogger(ParticlesDemo.class.getName()).log(.nullex);
        }
    }
    public void setImage(BufferedImage image) {
        int iWidth = image.getWidth(), iHeight = image.getHeight();
        int[] pixels = image.getRGB(0, 0, iWidthiHeightnull, 0, iWidth);
        int nPixels = iWidth * iHeight;
        float[] nonEmptyPixelsX = new float[nPixels], nonEmptyPixelsY = new float[nPixels];
        int[] nonEmptyPixels = new int[nPixels];
        int nNonEmptyPixels = 0;
        int hw = iWidth / 2, hh = iHeight / 2;
        for (int iPixel = 0; iPixel < nPixelsiPixel++) {
            int pixel = pixels[iPixel];
            if ((pixel & 0xff000000) != 0)
            {
                int y = iPixel / iWidthx = iPixel - y * iWidth;
                nonEmptyPixels[nNonEmptyPixels] = pixel;
                nonEmptyPixelsX[nNonEmptyPixels] = x - hw;
                nonEmptyPixelsY[nNonEmptyPixels] = hh - y;
                nNonEmptyPixels++;
            }
        }
        .finish();
        
        FloatBuffer positionsView = .asFloatBuffer();
        for (int iPoint = 0; iPoint < iPoint++) {
            int iPixel = (int)(.nextFloat() * (nNonEmptyPixels - 1));
            .put(iPixel, 0);
            .put(iPixel + 1, 0);
            int colorOffset = iPoint * ( / 4);
            int posOffset = iPoint * ( / 4) + 1;
            colorView.put(colorOffsetnonEmptyPixels[iPixel]);
            positionsView.put(posOffsetnonEmptyPixelsX[iPixel]);
            positionsView.put(posOffset + 1, nonEmptyPixelsY[iPixel]);
        }
        .rewind();
        .write(false);
        if ()
        if ()
        .finish();
    }
    CLQueue queue;
    boolean useOpenGLContext = false;
    int particlesCount;
    int[] vbo = new int[1];
    static final float DEFAULT_SLOWDOWN_FACTOR = 0.7f;
    static final float DEFAULT_SPEED_FACTOR = 2f, DEFAULT_MASS_FACTOR = 2;
    boolean hasMouse = false;
    boolean limitToScreen = false;
    long lastMouseMove;
    //CLKernel updateParticleKernel;
    int elementSize = 4 * 4;//4 + 2 * 4 + 4; // 4 color bytes and 2 position floats, 1 dummy alignment float
    Random random = new Random(System.nanoTime());
    public ParticlesDemo() {
        ParticlesCountItem[] items = new ParticlesCountItem[] {
            new ParticlesCountItem(1024, "1K"),
            new ParticlesCountItem(1024 * 10,"10K"),
            new ParticlesCountItem(1024 * 100,"100K"),
            new ParticlesCountItem(1024 * 1000,"1M"),
            new ParticlesCountItem(1024 * 10000,"10M")
        };
        JComboBox cb = new JComboBox(items);
        cb.setSelectedIndex(2);
        JLabel lb = new JLabel("Number of particles");
        Box countPanel = Box.createHorizontalBox();
        SetupUtils.setEtchedTitledBorder(countPanel"Particles Demo Settings");
        countPanel.add(lb);
        countPanel.add(Box.createHorizontalStrut(5));
        countPanel.add(cb);
        cb.setMinimumSize(new Dimension(100, 10));
        cb.setMaximumSize(new Dimension(200, .));
        countPanel.add(Box.createHorizontalGlue());
        //sett.removeOpenGLComponents();
        final JPanel opts = new JPanel(new BorderLayout());
        JLabel detailsLab = new JLabel("<html><body><a href='#'>Advanced OpenCL settings...</a></body>".);
        detailsLab.setCursor(Cursor.getPredefinedCursor(.));
        opts.add("Center"detailsLab);
        detailsLab.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                opts.removeAll();
                opts.add("Center");
                opts.invalidate();
                Component c = opts.getParent();
                while (c != null) {
                    if (c instanceof Frame) {
                        ((Frame)c).pack();
                        break;
                    }
                    if (c instanceof JDialog) {
                        ((JDialog)c).pack();
                        break;
                    }
                    c = c.getParent();
                }
            }
        });
        int opt = JOptionPane.showConfirmDialog(nullnew Object[] { countPanelopts }, "JavaCL Particles Demo".);
        if (opt != .)
            System.exit(0);
    }
    int[] blends = new int[] {
        GL_ONE_MINUS_SRC_ALPHA,
        GL_ONE,
        GL_ONE_MINUS_DST_ALPHA,
        GL_ONE_MINUS_DST_COLOR,
        GL_ONE_MINUS_SRC_COLOR,
        GL_SRC_ALPHA,
        GL_DST_ALPHA,
        GL_SRC_COLOR,
        GL_DST_COLOR,
    };
    volatile int iBlend = 0;
    public static void exception(Throwable ex) {
        StringWriter sout = new StringWriter();
        ex.printStackTrace(new PrintWriter(sout));
        JOptionPane.showMessageDialog(nullsout.toString(), "[Error] " + ParticlesDemo.class.getSimpleName() + " JavaCL Demo".);
    }
    @Override
    public void init(GLAutoDrawable glad) {
        try {
            GL2 gl = (GL2)glad.getGL();
            gl.glClearColor(0, 0, 0, 1);
            gl.glClear(GL_COLOR_BUFFER_BIT);
            //gl.glViewport(0, 0, (int)width, (int)height);
            gl.glEnable(GL_BLEND);
            gl.glEnable(GL2.GL_POINT_SMOOTH);
            try {
                if () {
                     = JavaCL.createContextFromCurrentGL();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null"Sharing of context between OpenCL and OpenGL failed.\n" +
                        "The demo will run fine without anyway.""JavaCL Demo".);
            }
            if ( == null) {
                 = false;
                CLDevice device = .getDevice();
                if (device == null)
                    device = JavaCL.getBestDevice();
                 = JavaCL.createContext(nulldevice);
            }
             = .createDefaultQueue();
            
            FloatBuffer masses = NIOUtils.directFloats(.getByteOrder());
             = NIOUtils.directFloats(2 * .getByteOrder());
            
            FloatBuffer positionsView = .asFloatBuffer();
            for (int i = 0; i < i++) {
                masses.put(0.5f + 0.5f * .nextFloat());
                
			    .put((.nextFloat() - 0.5f) * 0.2f);
                .put((.nextFloat() - 0.5f) * 0.2f);
                int colorOffset = i * ;
                int posOffset = i * ( / 4) + 1;
                byte r = (byte)128, g = rb = ra = r;
                .put(colorOffset++, r);
                .put(colorOffset++, g);
                .put(colorOffset++, b);
                .put(colorOffseta);
                
                float x = (.nextFloat() - 0.5f) * 200,
                        y = (.nextFloat() - 0.5f) * 200;
                positionsView.put(posOffsetx);
                positionsView.put(posOffset + 1, y);
            }
            .rewind();
            masses.rewind();
            .rewind();
            
             = .createFloatBuffer(.false);
             = .createFloatBuffer(.massestrue);
            gl.glGenBuffers(1, , 0);
            gl.glBindBuffer(GL_ARRAY_BUFFER, [0]);
            gl.glBindBuffer(GL_ARRAY_BUFFER, [0]);
            gl.glBufferData(GL_ARRAY_BUFFER, (int) NIOUtils.getSizeInBytes(), , GL2.GL_DYNAMIC_COPY);
            gl.glBindBuffer(GL_ARRAY_BUFFER, 0);
            if () {
            } else
                
            String hsv2rgbSrc = IOUtils.readText(ParticlesDemo.class.getResourceAsStream("HSVtoRGB.c"));
            //String src = IOUtils.readText(ParticlesDemo.class.getResourceAsStream("ParticlesDemo.c"));
            CLProgram program = .createProgram(hsv2rgbSrc);
             = new ParticlesDemoProgram(program);
            //updateParticleKernel = program.build().createKernel("updateParticle");
            updateKernelArgs();
            gl.glPointSize(2f);
        } catch (Exception ex) {
            Logger.getLogger(ParticlesDemo.class.getName()).log(.nullex);
            ex.printStackTrace();
            exception(ex);
            System.exit(1);
        }
    }
    @Override
    public void dispose(GLAutoDrawable glad) {
        
    }
    @Override
    public void display(GLAutoDrawable glad) {
        GL2 gl = (GL2)glad.getGL();
        
        gl.glBlendFunc(GL_SRC_ALPHA, []);
        gl.glMatrixMode(GL2.GL_PROJECTION);
        gl.glLoadIdentity();
        new GLU().gluOrtho2D(- / 2 - 1,  / 2 + 1, -/2 - 1, /2 + 1);
        gl.glMatrixMode(GL2.GL_MODELVIEW);
        gl.glBindBuffer(GL_ARRAY_BUFFER, [0]);
        if () {
            .finish();
        } else {
            //interleavedColorAndPositionsMem.map(queue, CLMem.MapFlags.Read);
            gl.glBufferSubData(GL_ARRAY_BUFFER, 0, (int)NIOUtils.getSizeInBytes(), );
            //interleavedColorAndPositionsMem.unmap(queue, interleavedColorAndPositionsTemp);
        }
        gl.glClear(GL_COLOR_BUFFER_BIT);
        gl.glColor3f(1.0f, 1.0f, 1.0f);
        //gl.glEnableClientState(GL_VERTEX_ARRAY);
        //gl.glEnableClientState(GL_COLOR_ARRAY);
        //gl.glColorPointer(4, GL_UNSIGNED_BYTE, elementSize,
        gl.glInterleavedArrays(GL2.GL_C4UB_V2F, , 0);
        
        gl.glDrawArrays(GL_POINTS, 0, );
        gl.glBindBuffer(GL_ARRAY_BUFFER, 0);
        if (!)
            updateKernelArgs();
    }
    @Override
    public void reshape(GLAutoDrawable gladint xint yint widthint height) {
        this. = width;
        this. = height;
        
    }
    private synchronized void updateKernelArgs() {
        if ()
        try {
            CLEvent evt = .updateParticle(
                ,
                ,
                ,
                .asCLFloatBuffer(),
                new float[] { -  / 2f,  / 2f - },
                new float[] {},
                ,
                ,
                ,
                 ?  : 0,
                (byte)( ? 1 : 0),
                new int[] {  }, null
            );
            evt.release(); // the gc might be to slow to reclaim the event, so do manual memory management here
        } catch (Throwable ex) {
            exception(ex);
            System.exit(1);
        }
        if ()
    }
New to GrepCode? Check out our FAQ X