Ejemplo n.º 1
0
def get_OCL_context():
    """
    Retrieves the OpenCL context
    """
    if not pyopencl:
        raise RuntimeError("OpenCL unuseable")
    ctx = None
    if sys.platform == "darwin":
        ctx = pyopencl.Context(properties=get_gl_sharing_context_properties(),
                               devices=[])
    else:
        # Some OSs prefer clCreateContextFromType, some prefer
        # clCreateContext. Try both and loop.
        for platform in pyopencl.get_platforms():
            try:
                ctx = pyopencl.Context(
                    properties=[(pyopencl.context_properties.PLATFORM,
                                 platform)] +
                    get_gl_sharing_context_properties())
            except:
                for device in platform.get_devices():
                    try:
                        ctx = pyopencl.Context(properties=[
                            (pyopencl.context_properties.PLATFORM, platform)
                        ] + get_gl_sharing_context_properties(),
                                               devices=[device])
                    except:
                        ctx = None
                    else:
                        break
            else:
                break
            if ctx:
                break
    return ctx
Ejemplo n.º 2
0
    def _get_context(self, device, gl_sharing):
        """
        Get an OpenCL context.
        @param device : OpenCL device
        @param gl_sharing : Flag to build a OpenGL shared OpenCL context
        @return OpenCL context

        """
        props = None
        if gl_sharing:
            from pyopencl.tools import get_gl_sharing_context_properties
            import sys
            if sys.platform == "darwin":
                props = get_gl_sharing_context_properties()
            else:
                # Some OSs prefer clCreateContextFromType, some prefer
                # clCreateContext. Try both.
                props = \
                    [(cl.context_properties.PLATFORM, self.platform)] \
                    + get_gl_sharing_context_properties()
            ctx = cl.Context(properties=props, devices=[device])
        else:
            ctx = cl.Context([device])
        if __VERBOSE__:
            print " Context:"
            if not props is None:
                print "  - properties           :", props
        return ctx
Ejemplo n.º 3
0
def get_OCL_context():
    """
    Retrieves the OpenCL context
    """
    if not pyopencl:
        raise RuntimeError("OpenCL unuseable")
    ctx = None
    if sys.platform == "darwin":
        ctx = pyopencl.Context(properties=get_gl_sharing_context_properties(),
                         devices=[])
    else:
        # Some OSs prefer clCreateContextFromType, some prefer
        # clCreateContext. Try both and loop.
        for platform in pyopencl.get_platforms():
            try:
                ctx = pyopencl.Context(properties=[
                            (pyopencl.context_properties.PLATFORM, platform)]
                                       + get_gl_sharing_context_properties())
            except:
                for device in platform.get_devices():
                    try:
                        ctx = pyopencl.Context(properties=[
                            (pyopencl.context_properties.PLATFORM, platform)]
                                               + get_gl_sharing_context_properties(),
                            devices=[device])
                    except:
                        ctx = None
                    else:
                        break
            else:
                break
            if ctx:
                break
    return ctx
Ejemplo n.º 4
0
    def __init__(self, filename, *args, **kwargs):
        plats = cl.get_platforms()
        from pyopencl.tools import get_gl_sharing_context_properties
        import sys

        if sys.platform == "darwin":
            self.ctx = cl.Context(properties=get_gl_sharing_context_properties(), devices=[])
        else:
            self.ctx = cl.Context(
                properties=[(cl.context_properties.PLATFORM, plats[0])] + get_gl_sharing_context_properties(),
                devices=None,
            )

        self.queue = cl.CommandQueue(self.ctx)

        self.loadProgram(filename)

        self.gl_objects = []
        # TODO get these from kwargs
        self.kernelargs = None
        self.global_size = (0,)
        self.local_size = None
        self.PreExecute = None
        self.PostExecute = None
        self.kernelname = filename.split(".")[0]
Ejemplo n.º 5
0
def clinit():
    """Initialize OpenCL with GL-CL interop.
    """
    if sys.platform == "darwin":
        print(dir(cl.context_properties))
        ctx = cl.Context(properties=get_gl_sharing_context_properties(), devices=[])
    else:
        # Some OSs prefer clCreateContextFromType, some prefer
        # clCreateContext. Try both.
        try:
            ctx = cl.Context(
                properties=[(cl.context_properties.PLATFORM, platform)] + get_gl_sharing_context_properties()
            )
        except:
            ctx = cl.Context(
                properties=[(cl.context_properties.PLATFORM, platform)] + get_gl_sharing_context_properties(),
                devices=[platform.get_devices()[0]],
            )

    # plats = cl.get_platforms()
    # ctx = cl.Context(properties=[
    #         (cl.context_properties.PLATFORM, plats[0])]
    #         + get_gl_sharing_context_properties(), devices = None)
    #                                   #[plats[0].get_devices()[DEVICE]])
    print(ctx)
    queue = cl.CommandQueue(ctx)

    return ctx, queue
Ejemplo n.º 6
0
	def openclContext(self, device_index=0):
		if not self._cl_ctx:
			if device_index:
				self._cl_ctx = cl.Context(	properties=get_gl_sharing_context_properties(),
										devices = [self._devices[device_index]])
			else:	
				self._cl_ctx = cl.Context(	properties=get_gl_sharing_context_properties(),
										devices = self._devices)

			logger.debug("OpenCL context created: %s" % self._cl_ctx)
		return self._cl_ctx
Ejemplo n.º 7
0
def _create_context():
    if sys.platform == 'darwin':
        props = cl_tools.get_gl_sharing_context_properties()
        ctx = cl.Context(properties=props, devices=[])
    else:
        props = [(cl.context_properties.PLATFORM, cl.get_platforms()[0])]
        props += cl_tools.get_gl_sharing_context_properties()
        ctx = cl.Context(properties=props)
    for i, dev in enumerate(ctx.devices):
        log.info('device %d: %s, driver version %s' % (i, dev.version, dev.driver_version))
        log.info('device %d: %s by %s' % (i, dev.name, dev.vendor))
    return ctx
Ejemplo n.º 8
0
    def __init__(self,
                 dev_id,
                 kernel_file="kernels.cl",
                 workers_exp1=5,
                 workers_exp2=5,
                 interop=False):

        self.platform = cl.get_platforms()[
            dev_id]  # Select the  platform [dev_id]
        print('You ve selected the plateform : %s' % (self.platform.name))

        # Create a context with all the devices
        self.device = self.platform.get_devices()[
            0]  # Select the first device on this platform [0]

        if (interop):
            if sys.platform == "darwin":
                self.ctx = cl.Context(
                    properties=get_gl_sharing_context_properties(), devices=[])
            else:
                try:
                    self.ctx = cl.Context(
                        properties=[(cl.context_properties.PLATFORM,
                                     self.platform)] +
                        get_gl_sharing_context_properties())
                except:
                    self.ctx = cl.Context(
                        properties=[
                            (cl.context_properties.PLATFORM, self.platform)
                        ] + get_gl_sharing_context_properties(),
                        devices=[self.platform.get_devices()[0]])
        else:
            self.ctx = cl.Context([self.device])

        # Create kernels
        self.prg = cl.Program(self.ctx, open(kernel_file).read()).build()

        # Create a simple queue
        self.queue = cl.CommandQueue(
            self.ctx,
            self.ctx.devices[0],
            properties=cl.command_queue_properties.PROFILING_ENABLE)

        if (workers_exp1 == None or workers_exp2 == None):
            self.local_size_2D = None
            self.local_size_3D = None
            self.local_size_inlet = None
        else:
            val1 = 2**workers_exp1
            val2 = 2**workers_exp2
            self.local_size_2D = (val1, val2)
            self.local_size_3D = (1, val1, val2)
            self.local_size_inlet = (val2, )
Ejemplo n.º 9
0
    def __init_cl_stuff(self):
        # Figure out platform and device
        platform = cl.get_platforms()[0]
        if sys.platform == "darwin":
            self.context = cl.Context(
                properties=get_gl_sharing_context_properties(), devices=[])
        else:
            # Some OSs prefer clCreateContextFromType, some prefer clCreateContext. Try both.
            try:
                self.context = cl.Context(
                    properties=[(cl.context_properties.PLATFORM, platform)] +
                    get_gl_sharing_context_properties())
            except:
                self.context = cl.Context(
                    properties=[(cl.context_properties.PLATFORM, platform)] +
                    get_gl_sharing_context_properties(),
                    devices=[platform.get_devices()[0]])

        print(Style.BRIGHT + 'DEVICE: \t' + Style.RESET_ALL,
              self.context.devices[0])
        print(Style.BRIGHT + 'VERSION: \t' + Style.RESET_ALL,
              self.context.devices[0].get_info(cl.device_info.VERSION))

        # Make OpenCL buffers, one for each OpenGL VBO
        self.position_buffer = cl.GLBuffer(self.context,
                                           cl.mem_flags.READ_WRITE,
                                           int(self.position_vbo))
        self.color_buffer = cl.GLBuffer(self.context, cl.mem_flags.READ_WRITE,
                                        int(self.color_vbo))
        self.lifetime_buffer = cl.GLBuffer(self.context,
                                           cl.mem_flags.READ_WRITE,
                                           int(self.lifetime_vbo))
        self.gl_buffers = (self.position_buffer, self.color_buffer,
                           self.lifetime_buffer)

        # Make other OpenCL buffers
        self.seed_buffer = cl.Buffer(self.context, cl.mem_flags.READ_WRITE,
                                     self.n_particles * 8)  # buffer of ulong
        self.velocity_buffer = cl.Buffer(self.context, cl.mem_flags.READ_WRITE,
                                         self.n_particles * 4 *
                                         4)  # buffer of float4

        # Compile kernel program
        try:
            program_src = file_to_string(KERNEL_FILENAME)
            self.kernel = cl.Program(self.context, program_src).build()
        except cl.RuntimeError as e:
            raise ParticleSystemException('Error compiling ' +
                                          KERNEL_FILENAME + '\n' + str(e))

        # Will need a command queue to run kernel
        self.queue = cl.CommandQueue(self.context)
Ejemplo n.º 10
0
 def clinit(self):
     plats = cl.get_platforms()
     from pyopencl.tools import get_gl_sharing_context_properties
     import sys 
     if sys.platform == "darwin":
         self.ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                          devices=[])
     else:
         self.ctx = cl.Context(properties=[
             (cl.context_properties.PLATFORM, plats[0])]
             + get_gl_sharing_context_properties(), devices=None)
             
     self.queue = cl.CommandQueue(self.ctx)
Ejemplo n.º 11
0
def _create_context():
    if sys.platform == 'darwin':
        props = cl_tools.get_gl_sharing_context_properties()
        ctx = cl.Context(properties=props, devices=[])
    else:
        props = [(cl.context_properties.PLATFORM, cl.get_platforms()[0])]
        props += cl_tools.get_gl_sharing_context_properties()
        ctx = cl.Context(properties=props)
    for i, dev in enumerate(ctx.devices):
        log.info('device %d: %s, driver version %s' %
                 (i, dev.version, dev.driver_version))
        log.info('device %d: %s by %s' % (i, dev.name, dev.vendor))
    return ctx
Ejemplo n.º 12
0
    def openclContext(self, device_index=0):
        if not self._cl_ctx:
            if device_index:
                self._cl_ctx = cl.Context(
                    properties=get_gl_sharing_context_properties(),
                    devices=[self._devices[device_index]])
            else:
                self._cl_ctx = cl.Context(
                    properties=get_gl_sharing_context_properties(),
                    devices=self._devices)

            logger.debug("OpenCL context created: %s" % self._cl_ctx)
        return self._cl_ctx
 def clinit(self):
     plats = cl.get_platforms()
     from pyopencl.tools import get_gl_sharing_context_properties
     import sys 
     if sys.platform == "darwin":
         self.ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                          devices=[])
     else:
         self.ctx = cl.Context(properties=[
             (cl.context_properties.PLATFORM, plats[0])]
             + get_gl_sharing_context_properties(), devices=None)
             
     self.queue = cl.CommandQueue(self.ctx)
Ejemplo n.º 14
0
def clinit():
    """Initialize OpenCL with GL-CL interop.
    """
    plats = cl.get_platforms()
    # handling OSX
    if sys.platform == "darwin":
        ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                             devices=[])
    else:
        ctx = cl.Context(properties=[
                            (cl.context_properties.PLATFORM, plats[0])]
                            + get_gl_sharing_context_properties())
    queue = cl.CommandQueue(ctx)
    return ctx, queue
Ejemplo n.º 15
0
def clinit():
    """Initialize OpenCL with GL-CL interop.
    """
    plats = cl.get_platforms()
    # handling OSX
    if sys.platform == "darwin":
        ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                             devices=[])
    else:
        ctx = cl.Context(properties=[
                            (cl.context_properties.PLATFORM, plats[0])]
                            + get_gl_sharing_context_properties())
    queue = cl.CommandQueue(ctx)
    return ctx, queue
Ejemplo n.º 16
0
    def initCL(self):
        platforms = cl.get_platforms()

        if sys.platform == "darwin":
            self.clContext = cl.Context(properties=get_gl_sharing_context_properties(), devices=[])
        else:
            try:
                self.clContext = cl.Context(properties=[
                                                           (cl.context_properties.PLATFORM, platforms)]
                                                       + get_gl_sharing_context_properties())
            except:
                raise SystemError('Could not create OpenCL context')

        self.queue = cl.CommandQueue(self.clContext, properties=cl.command_queue_properties.PROFILING_ENABLE)
	def __init__(self, gpuOnly=True, sharedGlContext=False, hidePlatformDetails=False):
		super(BaseCalculator, self).__init__()
		self.platform = cl.get_platforms()[0]
		self.devices = self.platform.get_devices()

		if not hidePlatformDetails:
			for platform in cl.get_platforms():
				for device in platform.get_devices():
					print("===============================================================")
					print("Platform name:", platform.name)
					print("Platform profile:", platform.profile)
					print("Platform vendor:", platform.vendor)
					print("Platform version:", platform.version)
					print("---------------------------------------------------------------")
					print("Device name:", device.name)
					print("Device type:", cl.device_type.to_string(device.type))
					print("Device memory: ", device.global_mem_size//1024//1024, 'MB')
					print("Device max clock speed:", device.max_clock_frequency, 'MHz')
					print("Device compute units:", device.max_compute_units)
					print("Device max work group size:", device.max_work_group_size)
					print("Device max work item sizes:", device.max_work_item_sizes)

		properties = None
		if sharedGlContext:
			assert cl.have_gl()
			properties = get_gl_sharing_context_properties()

		devices = self.devices
		if gpuOnly and len(self.devices) > 1:
			devices = [self.devices[1]]

		self.context = cl.Context(properties=properties, devices=devices)

		self.queue = None
Ejemplo n.º 18
0
    def setup(self):
        self.platform = cl.get_platforms()[0]
        if self.opengl:
            self.context = cl.Context(
                properties=[(cl.context_properties.PLATFORM, self.platform)] + get_gl_sharing_context_properties())
        else:
            self.context = cl.Context(
                properties=[(cl.context_properties.PLATFORM, self.platform)])
        self.queue = cl.CommandQueue(self.context)

        self.program = cl.Program(self.context, self.kernel_src).build(
            '-cl-single-precision-constant -cl-opt-disable')

        self.cl_particle_velocity_a = cl.Buffer(self.context, mf.COPY_HOST_PTR, hostbuf=self.np_particle_velocity)
        self.cl_particle_velocity_b = cl.Buffer(self.context, mf.COPY_HOST_PTR, hostbuf=self.np_particle_velocity)

        if self.opengl:
            self.gl_particle_position_a = vbo.VBO(data=self.np_particle_position, usage=gl.GL_DYNAMIC_DRAW, target=gl.GL_ARRAY_BUFFER)
            self.gl_particle_position_a.bind()
            self.gl_particle_position_b = vbo.VBO(data=self.np_particle_position, usage=gl.GL_DYNAMIC_DRAW, target=gl.GL_ARRAY_BUFFER)
            self.gl_particle_position_b.bind()

            self.cl_particle_position_a = cl.GLBuffer(self.context, mf.READ_WRITE, int(self.gl_particle_position_a))
            self.cl_particle_position_b = cl.GLBuffer(self.context, mf.READ_WRITE, int(self.gl_particle_position_b))
        else:
            self.cl_particle_position_a = cl.Buffer(self.context, mf.COPY_HOST_PTR, hostbuf=self.np_particle_position)
            self.cl_particle_position_b = cl.Buffer(self.context, mf.COPY_HOST_PTR, hostbuf=self.np_particle_position)

        self.cl_last_collide = cl.Buffer(self.context, mf.COPY_HOST_PTR, hostbuf=self.np_last_collide)
        self.cl_particle_velocity_norms = cl.Buffer(self.context, mf.COPY_HOST_PTR, hostbuf=self.np_particle_velocity_norms)
Ejemplo n.º 19
0
    def create_gpu_driver(cls):
        platform = cl.get_platforms()[0]
        devices = platform.get_devices()
        gpu_device = devices[1]
        properties = get_gl_sharing_context_properties()

        context = cl.Context( devices=[gpu_device])
        return cls(cl.CommandQueue(context))
Ejemplo n.º 20
0
	def initialize(self, *args, **kwargs):
		plats = cl.get_platforms()
		card_dex = len(plats) - 1
		if sys.platform == "darwin":
			self.ctx = cl.Context(properties=\
				get_gl_sharing_context_properties(),
										devices=[])
		else:
			props = [(cl.context_properties.PLATFORM,plats[card_dex])]+\
									get_gl_sharing_context_properties()
			try: self.ctx = cl.Context(properties=props, devices=None)
			except TypeError:
				print 'no GPU contexts will work properly...'; return
		self.queue = cl.CommandQueue(self.ctx)
		self.verify_cl_extension(*args, **kwargs)
		print 'initialized gpu worker using:', self.gpu_cl_extension_key
		print 'using:', plats[card_dex], 'given:', plats, 'as options'
Ejemplo n.º 21
0
def clinit():
    """Initialize OpenCL with GL-CL interop.
    """
    plats = cl.get_platforms()
    ctx = cl.Context(properties=[(cl.context_properties.PLATFORM, plats[0])] +
                     get_gl_sharing_context_properties(),
                     devices=[plats[0].get_devices()[DEVICE]])
    queue = cl.CommandQueue(ctx)
    return ctx, queue
Ejemplo n.º 22
0
def clinit():
    """Initialize OpenCL with GL-CL interop.
    """
    plats = cl.get_platforms()
    ctx = cl.Context(properties=[
            (cl.context_properties.PLATFORM, plats[0])]
            + get_gl_sharing_context_properties(), devices =
                                      [plats[0].get_devices()[DEVICE]])
    queue = cl.CommandQueue(ctx)
    return ctx, queue
	def prepareClBuffer(self):
		platform = cl.get_platforms()
		self.ctx = cl.Context(properties=get_gl_sharing_context_properties(),devices=[])
		self.queue = cl.CommandQueue(self.ctx)
		self._cl_buf_pos  = cl.GLBuffer(self.ctx, mf.READ_WRITE, int(self.vbo_id[0]))
		self._cl_buf_vel  = cl.GLBuffer(self.ctx, mf.READ_WRITE, int(self.vbo_id[1]))
		self._cl_p_ww     = cl.Buffer(self.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=self._p_ww)
		self._cl_p_has_ww = cl.Buffer(self.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=self._p_ww)
		self._cl_p_ww_len = numpy.int32(len(self._p_ww))
		self.prog = cl.Program(self.ctx, CL_KERNEL).build()
Ejemplo n.º 24
0
 def initialize(self, *args, **kwargs):
     plats = cl.get_platforms()
     card_dex = len(plats) - 1
     if sys.platform == "darwin":
         self.ctx = cl.Context(properties=\
          get_gl_sharing_context_properties(),
                devices=[])
     else:
         props = [(cl.context_properties.PLATFORM,plats[card_dex])]+\
               get_gl_sharing_context_properties()
         try:
             self.ctx = cl.Context(properties=props, devices=None)
         except TypeError:
             print 'no GPU contexts will work properly...'
             return
     self.queue = cl.CommandQueue(self.ctx)
     self.verify_cl_extension(*args, **kwargs)
     print 'initialized gpu worker using:', self.gpu_cl_extension_key
     print 'using:', plats[card_dex], 'given:', plats, 'as options'
Ejemplo n.º 25
0
    def __init__(self, filename):
        plats = cl.get_platforms()
        from pyopencl.tools import get_gl_sharing_context_properties
        import sys 
        if sys.platform == "darwin":
            self.ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                             devices=[])
        else:
            self.ctx = cl.Context(properties=[
                (cl.context_properties.PLATFORM, plats[0])]
                + get_gl_sharing_context_properties(), devices=None)
                
        self.queue = cl.CommandQueue(self.ctx)

        self.loadProgram(filename)
        
        self.kernelargs = None
        self.gl_objects = []
        self.PreExecute = None
        self.PostExecute = None
Ejemplo n.º 26
0
    def __init__(self, filename):
        plats = cl.get_platforms()
        from pyopencl.tools import get_gl_sharing_context_properties
        import sys
        if sys.platform == "darwin":
            self.ctx = cl.Context(
                properties=get_gl_sharing_context_properties(), devices=[])
        else:
            self.ctx = cl.Context(
                properties=[(cl.context_properties.PLATFORM, plats[0])] +
                get_gl_sharing_context_properties(),
                devices=None)

        self.queue = cl.CommandQueue(self.ctx)

        self.loadProgram(filename)

        self.kernelargs = None
        self.gl_objects = []
        self.PreExecute = None
        self.PostExecute = None
Ejemplo n.º 27
0
Archivo: sph.py Proyecto: dancsi/pysph
 def cl_init_context(self):
     """
     Define context and queue.
     """
     device = self.cl_pick_device()
     platform = device.platform
     additional_properties = []
     if self.gl_interop:
         from pyopencl.tools import get_gl_sharing_context_properties
         additional_properties = get_gl_sharing_context_properties()
     self.ctx = cl.Context(properties=[(cl.context_properties.PLATFORM, platform)] + additional_properties)
     self.queue = cl.CommandQueue(self.ctx, device=device, properties=cl.command_queue_properties.OUT_OF_ORDER_EXEC_MODE_ENABLE)
Ejemplo n.º 28
0
    def __init__(self, gl_positions, gl_colors, velocities, dt=0.001):
        # First, we have to initialize the OpenCL context. That means we have
        # to get a list of available platforms and select one:
        platform = cl.get_platforms()[0]
        # Then, we can create a context. Passing
        # <code>get_gl_sharing_context_properties()</code> as a property
        # ensures that we share state with the active OpenGL context:
        self.ctx = cl.Context(
            properties=[(cl.context_properties.PLATFORM, platform)] +
            get_gl_sharing_context_properties(),
            devices=[platform.get_devices()[0]])
        # A command queue is necessary for serializing OpenCL commands:
        self.queue = cl.CommandQueue(self.ctx)
        # Finally, we can compile the kernel:
        self.program = cl.Program(self.ctx, kernel_code).build()

        # The constructor parameters are stored for later use:
        self.gl_positions = gl_positions
        self.gl_colors = gl_colors
        self.velocities = velocities
        # The <code>dt</code> value will later be passed to an OpenCL kernel as
        # a 32-bit float. We therefore wrap it in a numpy <code>float32</code>
        # object:
        self.dt = numpy.float32(dt)

        # Next, we generate OpenCL buffers. The positions and colors are
        # contained in OpenGL buffers, which we wrap in PyOpenCL's
        # <code>GLBuffer</code> class:
        self.cl_positions = cl.GLBuffer(self.ctx, cl.mem_flags.READ_WRITE,
                                        self.gl_positions._id)
        self.cl_colors = cl.GLBuffer(self.ctx, cl.mem_flags.READ_WRITE,
                                     self.gl_colors._id)
        # Note how we had to extract the <code>_id</code>s from the
        # <code>ArrayBuffer</code> objects. In pure <i>glitter</i> code, you
        # should never (have to) access this value; however for interaction
        # with other OpenGL-related libraries, this cannot always be avoided.

        # The velocities are given as a numpy array, which is simply uploaded
        # into a new OpenCL <code>Buffer</code> object along with the initial
        # values of the positions and colors:
        self.cl_velocities = cl.Buffer(self.ctx,
                                       cl.mem_flags.READ_ONLY
                                       | cl.mem_flags.COPY_HOST_PTR,
                                       hostbuf=velocities)
        self.cl_initial_positions = cl.Buffer(self.ctx,
                                              cl.mem_flags.READ_ONLY
                                              | cl.mem_flags.COPY_HOST_PTR,
                                              hostbuf=self.gl_positions.data)
        self.cl_initial_velocities = cl.Buffer(self.ctx,
                                               cl.mem_flags.READ_ONLY
                                               | cl.mem_flags.COPY_HOST_PTR,
                                               hostbuf=self.velocities)
Ejemplo n.º 29
0
Archivo: filter.py Proyecto: h3tch/psm
def init_opencl(sharing=True):
    global context, command_queue
    if context is not None:
        return
    platform = cl.get_platforms()[-1]
    devices = platform.get_devices()
    if sharing:
        context = cl.Context(
            devices=devices,
            properties=[(cl.context_properties.PLATFORM, platform)] +
            get_gl_sharing_context_properties())
    else:
        context = cl.Context(devices=devices)
    command_queue = cl.CommandQueue(context)
Ejemplo n.º 30
0
def initialize():
    platform = cl.get_platforms()[0]

    from pyopencl.tools import get_gl_sharing_context_properties
    import sys
    if sys.platform == "darwin":
        ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                devices=[])
    else:
        # Some OSs prefer clCreateContextFromType, some prefer
        # clCreateContext. Try both.
        try:
            ctx = cl.Context(properties=[
                (cl.context_properties.PLATFORM, platform)]
                + get_gl_sharing_context_properties())
        except:
            ctx = cl.Context(properties=[
                (cl.context_properties.PLATFORM, platform)]
                + get_gl_sharing_context_properties(),
                devices = [platform.get_devices()[0]])

    glClearColor(1, 1, 1, 1)
    glColor(0, 0, 1)
    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    rawGlBufferData(GL_ARRAY_BUFFER, n_vertices * 2 * 4, None, GL_STATIC_DRAW)
    glEnableClientState(GL_VERTEX_ARRAY)
    glVertexPointer(2, GL_FLOAT, 0, None)
    coords_dev = cl.GLBuffer(ctx, cl.mem_flags.READ_WRITE, int(vbo))
    prog = cl.Program(ctx, src).build()
    queue = cl.CommandQueue(ctx)
    cl.enqueue_acquire_gl_objects(queue, [coords_dev])
    prog.generate_sin(queue, (n_vertices,), None, coords_dev)
    cl.enqueue_release_gl_objects(queue, [coords_dev])
    queue.finish()
    glFlush()
Ejemplo n.º 31
0
def clinit():
    """Initialize OpenCL with GL-CL interop.
    """
    # import ipdb; ipdb.set_trace()
    plats = cl.get_platforms()
    # handling OSX
    if sys.platform == "darwin":
        ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                         devices=[])
    else:
        ctx = cl.Context(
            properties=[(cl.context_properties.PLATFORM, plats[0])] +
            get_gl_sharing_context_properties())
    # try:
    #     ctx = cl.Context(properties=[
    #         (cl.context_properties.PLATFORM, platform)]
    #         + get_gl_sharing_context_properties())
    # except:
    #     ctx = cl.Context(properties=[
    #         (cl.context_properties.PLATFORM, platform)]
    #         + get_gl_sharing_context_properties(),
    #         devices = [platform.get_devices()[0]])
    queue = cl.CommandQueue(ctx)
    return ctx, queue
Ejemplo n.º 32
0
def initialize():
    platform = cl.get_platforms()[0]

    from pyopencl.tools import get_gl_sharing_context_properties
    import sys
    if sys.platform == "darwin":
        ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                         devices=[])
    else:
        # Some OSs prefer clCreateContextFromType, some prefer
        # clCreateContext. Try both.
        try:
            ctx = cl.Context(
                properties=[(cl.context_properties.PLATFORM, platform)] +
                get_gl_sharing_context_properties())
        except:
            ctx = cl.Context(
                properties=[(cl.context_properties.PLATFORM, platform)] +
                get_gl_sharing_context_properties(),
                devices=[platform.get_devices()[0]])

    glClearColor(1, 1, 1, 1)
    glColor(0, 0, 1)
    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    rawGlBufferData(GL_ARRAY_BUFFER, n_vertices * 2 * 4, None, GL_STATIC_DRAW)
    glEnableClientState(GL_VERTEX_ARRAY)
    glVertexPointer(2, GL_FLOAT, 0, None)
    coords_dev = cl.GLBuffer(ctx, cl.mem_flags.READ_WRITE, int(vbo))
    prog = cl.Program(ctx, src).build()
    queue = cl.CommandQueue(ctx)
    cl.enqueue_acquire_gl_objects(queue, [coords_dev])
    prog.generate_sin(queue, (n_vertices, ), None, coords_dev)
    cl.enqueue_release_gl_objects(queue, [coords_dev])
    queue.finish()
    glFlush()
Ejemplo n.º 33
0
    def __init__(self, filename, *args, **kwargs):
        plats = cl.get_platforms()
        from pyopencl.tools import get_gl_sharing_context_properties
        import sys 
        if sys.platform == "darwin":
            self.ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                             devices=[])
        else:
            self.ctx = cl.Context(properties=[
                (cl.context_properties.PLATFORM, plats[0])]
                + get_gl_sharing_context_properties(), devices=None)
                
        self.queue = cl.CommandQueue(self.ctx)

        self.loadProgram(filename)
        
        self.gl_objects = []
        #TODO get these from kwargs
        self.kernelargs = None
        self.global_size = (0, )
        self.local_size = None
        self.PreExecute = None
        self.PostExecute = None
        self.kernelname = filename.split(".")[0]
Ejemplo n.º 34
0
 def clinit(self):
     plats = cl.get_platforms()
     from pyopencl.tools import get_gl_sharing_context_properties
     if sys.platform == "darwin":
         self.ctx= cl.create_some_context()
         #print cl.context_properties.
         #print get_gl_sharing_context_properties()
         #print "ctx_props.CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE", cl.get_apple_cgl_share_group()
         print cl.get_apple_cgl_share_group()
         #self.ctx = cl.Context(properties=get_gl_sharing_context_properties(), devices=[])
     else:
         self.ctx = cl.Context(properties=[(cl.context_properties.PLATFORM, plats[0])]
             + get_gl_sharing_context_properties(), devices=None)
             
     self.queue = cl.CommandQueue(self.ctx)
Ejemplo n.º 35
0
 def cl_init_context(self):
     """
     Define context and queue.
     """
     device = self.cl_pick_device()
     platform = device.platform
     additional_properties = []
     if self.gl_interop:
         from pyopencl.tools import get_gl_sharing_context_properties
         additional_properties = get_gl_sharing_context_properties()
     # Some OSs prefer clCreateContextFromType, some prefer clCreateContext. Try both.
     try: 
         self.ctx = cl.Context(properties=[(cl.context_properties.PLATFORM, platform)] + additional_properties)
     except:
         self.ctx = cl.Context(properties=[(cl.context_properties.PLATFORM, platform)] + additional_properties, devices=[device])
     self.queue = cl.CommandQueue(self.ctx, device=device, properties=cl.command_queue_properties.OUT_OF_ORDER_EXEC_MODE_ENABLE)
Ejemplo n.º 36
0
def get_cl_context(gl_context):
    """Creates a CL context, with or without given GL context."""
    if gl_context is not None: # ... with OpenGL interop?
        with gl_context:
            assert cl.have_gl(), "GL interoperability not enabled."
            from pyopencl.tools import get_gl_sharing_context_properties
            cl_platform = cl.get_platforms()[0]
            cl_properties = [(cl.context_properties.PLATFORM, cl_platform)] + get_gl_sharing_context_properties()
            cl_devices = [cl_platform.get_devices()[-1]]  # Only one is allowed!
            cl_context = cl.Context(properties=cl_properties, devices=cl_devices)
    else: # ... or in stand-alone mode, CL context without GL?
        cl_platform = cl.get_platforms()[0]  # @UndefinedVariable
        cl_properties = [(cl.context_properties.PLATFORM, cl_platform)]
        cl_devices = [cl_platform.get_devices()[-1]]  # Only one is allowed!
        cl_context = cl.Context(properties=cl_properties, devices=cl_devices)
    return cl_context
	def __init__(self, gpuOnly=True, sharedGlContext=False):
		super(BaseCalculator, self).__init__()
		self.platform = cl.get_platforms()[0]
		self.devices = self.platform.get_devices()

		properties = None
		if sharedGlContext:
			assert cl.have_gl()
			properties = get_gl_sharing_context_properties()

		devices = self.devices
		if gpuOnly and len(self.devices) > 1:
			devices = [self.devices[0]]

		self.context = cl.Context(properties=properties, devices=devices)

		self.queue = None
Ejemplo n.º 38
0
def get_cl_context(gl_context):
    """Creates a CL context, with or without given GL context."""
    if gl_context is not None:  # ... with OpenGL interop?
        with gl_context:
            assert cl.have_gl(), "GL interoperability not enabled."
            from pyopencl.tools import get_gl_sharing_context_properties
            cl_platform = cl.get_platforms()[0]
            cl_properties = [(cl.context_properties.PLATFORM, cl_platform)
                             ] + get_gl_sharing_context_properties()
            cl_devices = [cl_platform.get_devices()[-1]
                          ]  # Only one is allowed!
            cl_context = cl.Context(properties=cl_properties,
                                    devices=cl_devices)
    else:  # ... or in stand-alone mode, CL context without GL?
        cl_platform = cl.get_platforms()[0]  # @UndefinedVariable
        cl_properties = [(cl.context_properties.PLATFORM, cl_platform)]
        cl_devices = [cl_platform.get_devices()[-1]]  # Only one is allowed!
        cl_context = cl.Context(properties=cl_properties, devices=cl_devices)
    return cl_context
Ejemplo n.º 39
0
    def __init__(self, gl_positions, gl_colors, velocities, dt=0.001):
        # First, we have to initialize the OpenCL context. That means we have
        # to get a list of available platforms and select one:
        platform = cl.get_platforms()[0]
        # Then, we can create a context. Passing
        # <code>get_gl_sharing_context_properties()</code> as a property
        # ensures that we share state with the active OpenGL context:
        self.ctx = cl.Context(properties=[(cl.context_properties.PLATFORM, platform)] +
                get_gl_sharing_context_properties(), devices=[platform.get_devices()[0]])
        # A command queue is necessary for serializing OpenCL commands:
        self.queue = cl.CommandQueue(self.ctx)
        # Finally, we can compile the kernel:
        self.program = cl.Program(self.ctx, kernel_code).build()

        # The constructor parameters are stored for later use:
        self.gl_positions = gl_positions
        self.gl_colors = gl_colors
        self.velocities = velocities
        # The <code>dt</code> value will later be passed to an OpenCL kernel as
        # a 32-bit float. We therefore wrap it in a numpy <code>float32</code>
        # object:
        self.dt = numpy.float32(dt)

        # Next, we generate OpenCL buffers. The positions and colors are
        # contained in OpenGL buffers, which we wrap in PyOpenCL's
        # <code>GLBuffer</code> class:
        self.cl_positions = cl.GLBuffer(self.ctx, cl.mem_flags.READ_WRITE, self.gl_positions._id)
        self.cl_colors = cl.GLBuffer(self.ctx, cl.mem_flags.READ_WRITE, self.gl_colors._id)
        # Note how we had to extract the <code>_id</code>s from the
        # <code>ArrayBuffer</code> objects. In pure <i>glitter</i> code, you
        # should never (have to) access this value; however for interaction
        # with other OpenGL-related libraries, this cannot always be avoided.

        # The velocities are given as a numpy array, which is simply uploaded
        # into a new OpenCL <code>Buffer</code> object along with the initial
        # values of the positions and colors:
        self.cl_velocities = cl.Buffer(self.ctx, cl.mem_flags.READ_ONLY |
                cl.mem_flags.COPY_HOST_PTR, hostbuf=velocities)
        self.cl_initial_positions = cl.Buffer(self.ctx, cl.mem_flags.READ_ONLY |
                cl.mem_flags.COPY_HOST_PTR, hostbuf=self.gl_positions.data)
        self.cl_initial_velocities = cl.Buffer(self.ctx, cl.mem_flags.READ_ONLY |
                cl.mem_flags.COPY_HOST_PTR, hostbuf=self.velocities)
Ejemplo n.º 40
0
def init_device(cpu_device=False):
    # Find a device... default is for GPU
    device_type_name = 'gpu'
    if cpu_device:
        device_type_name = 'cpu'

    # Grab OpenCL device calls
    device_type = deviceDict[device_type_name]

    print('\n============== Grabbing Compute Resources =============\n')
    platform = cl.get_platforms()[0]
    print('\t\tPlatform: %s' % platform)
    device = platform.get_devices(device_type=device_type)
    print('\t\tDevice: %s' % device[0])
    print('\n=======================================================\n')
    context = cl.Context(
        devices=device,
        properties=[(cl.context_properties.PLATFORM, platform)] +
        get_gl_sharing_context_properties())
    return device, context
Ejemplo n.º 41
0
    def __init__(self, gl_image, gl_lapl_mask):
        platform = cl.get_platforms()[0]
        self.ctx = cl.Context(
            properties=[(cl.context_properties.PLATFORM, platform)] +
            get_gl_sharing_context_properties(),
            devices=None)
        self.queue = cl.CommandQueue(self.ctx)
        self.program = cl.Program(self.ctx, kernel_code).build()

        self.shape = gl_image.shape[1], gl_image.shape[0]
        self.cl_image = cl.GLTexture(self.ctx, cl.mem_flags.READ_WRITE,
                                     GL_TEXTURE_2D, 0, gl_image._id, 2)
        self.cl_lapl_mask = cl.GLTexture(self.ctx, cl.mem_flags.READ_ONLY,
                                         GL_TEXTURE_2D, 0, gl_lapl_mask._id, 2)

        if self.use_gl_texture_as_tmp:
            self.gl_tmp = Texture2D(gl_image.data)
            self.cl_tmp = cl.GLTexture(self.ctx, cl.mem_flags.READ_WRITE,
                                       GL_TEXTURE_2D, 0, self.gl_tmp._id, 2)
        else:
            self.cl_tmp = cl.Image(
                self.ctx, cl.mem_flags.READ_WRITE,
                self.cl_image.get_image_info(cl.image_info.FORMAT), self.shape)
Ejemplo n.º 42
0
    def cl_init_context(self):
        """
        Define context and queue.
        """
        device = self.cl_pick_device()
        platform = device.platform
        additional_properties = []

        from pyopencl.tools import get_gl_sharing_context_properties
        additional_properties = get_gl_sharing_context_properties()
        # Some OSs prefer clCreateContextFromType, some prefer clCreateContext. Try both.
        try:
            self.ctx = cl.Context(
                properties=[(cl.context_properties.PLATFORM, platform)] +
                additional_properties)
        except:
            self.ctx = cl.Context(
                properties=[(cl.context_properties.PLATFORM, platform)] +
                additional_properties,
                devices=[device])
        self.queue = cl.CommandQueue(self.ctx,
                                     device=device,
                                     properties=cl.command_queue_properties.
                                     OUT_OF_ORDER_EXEC_MODE_ENABLE)
    # Draw the VBOs
    glDrawArrays(GL_POINTS, 0, num_particles)

    glDisableClientState(GL_COLOR_ARRAY)
    glDisableClientState(GL_VERTEX_ARRAY)

    glDisable(GL_BLEND)

    glutSwapBuffers()

window = glut_window()

(np_position, np_velocity, gl_position, gl_color) = initial_buffers(num_particles)

platform = cl.get_platforms()[0]
context = cl.Context(properties=[(cl.context_properties.PLATFORM, platform)] + get_gl_sharing_context_properties())  
queue = cl.CommandQueue(context)

cl_velocity = cl.Buffer(context, mf.COPY_HOST_PTR, hostbuf=np_velocity)
cl_start_position = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=np_position)
cl_start_velocity = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=np_velocity)

cl_gl_position = cl.GLBuffer(context, mf.READ_WRITE, int(gl_position.buffers[0]))
cl_gl_color = cl.GLBuffer(context, mf.READ_WRITE, int(gl_color.buffers[0]))

kernel = """__kernel void particle_fountain(__global float4* position, 
                                            __global float4* color, 
                                            __global float4* velocity, 
                                            __global float4* start_position, 
                                            __global float4* start_velocity, 
                                            float time_step)
Ejemplo n.º 44
0
    def __init__(self, gl_image, gl_lapl_mask):
        platform = cl.get_platforms()[0]
        self.ctx = cl.Context(properties=[(cl.context_properties.PLATFORM, platform)] + get_gl_sharing_context_properties(), devices=None)
        self.queue = cl.CommandQueue(self.ctx)
        self.program = cl.Program(self.ctx, kernel_code).build()

        self.shape = gl_image.shape[1], gl_image.shape[0]
        self.cl_image = cl.GLTexture(self.ctx, cl.mem_flags.READ_WRITE, GL_TEXTURE_2D, 0, gl_image._id, 2)
        self.cl_lapl_mask = cl.GLTexture(self.ctx, cl.mem_flags.READ_ONLY, GL_TEXTURE_2D, 0, gl_lapl_mask._id, 2)

        if self.use_gl_texture_as_tmp:
            self.gl_tmp = Texture2D(gl_image.data)
            self.cl_tmp = cl.GLTexture(self.ctx, cl.mem_flags.READ_WRITE, GL_TEXTURE_2D, 0, self.gl_tmp._id, 2)
        else:
            self.cl_tmp = cl.Image(self.ctx, cl.mem_flags.READ_WRITE, self.cl_image.get_image_info(cl.image_info.FORMAT), self.shape)
Ejemplo n.º 45
0
 def clinit(self):
     from pyopencl.tools import get_gl_sharing_context_properties
     plat = cl.get_platforms()
     GF9400 = plat[0].get_devices()[1]
     self.ctx = cl.Context(devices = [GF9400],properties=get_gl_sharing_context_properties())
     self.queue = cl.CommandQueue(self.ctx, properties=cl.command_queue_properties.PROFILING_ENABLE)
Ejemplo n.º 46
0
    def __init__(self, network, step_size=0.00025):
        """
            Creates a visualization window for a given network. The network cannot be compiled yet!
        """

        self.network = network

        #set up timing parameters
        self.refresh_rate_ms = 30 #in ms
        self.sim_dur_per_refresh = 0.005 # amount of time
        self.step_size = step_size
        self.num_steps_per_refresh = int(self.sim_dur_per_refresh / self.step_size)

        #mouse handling for transforming scene
        self.mouse_down = False
        self.mouse_old = np.array([0., 0.])
        self.rotate = np.array([0., 0., 0.])
        self.translate = np.array([0., 0., 0.])
        self.initrans = np.array([0., 0., -2.])

        self.width = 1024
        self.height = 768

        self.simulation_time = 0.0

        glutInit(sys.argv)
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowSize(self.width, self.height)
        glutInitWindowPosition(0, 0)
        self.win = glutCreateWindow('Network')

        #gets called by GLUT every frame
        glutDisplayFunc(self.draw)

        #handle user input
        glutKeyboardFunc(self.on_key)
        glutMouseFunc(self.on_click)
        glutMotionFunc(self.on_mouse_motion)


        #this will call draw every 30 ms
        glutTimerFunc(self.refresh_rate_ms, self.timer, self.refresh_rate_ms)

        #setup OpenGL scene
        self.glinit()

        #create position and color VBOs
        unit_positions = self.network.get_unit_positions()
        print 'unit_positions:'
        print unit_positions
        self.pos_vbo = vbo.VBO(data=unit_positions, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER)
        self.pos_vbo.bind()

        unit_colors = self.network.get_unit_colors()
        print 'unit_colors:'
        print unit_colors
        self.col_vbo = vbo.VBO(data=unit_colors, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER)
        self.col_vbo.bind()

        self.network.visualize = True
        self.network.color_vbo = self.col_vbo

        #create a CL context for the network to use
        plats = cl.get_platforms()
        if sys.platform == "darwin":
            cl_context = cl.Context(properties=get_gl_sharing_context_properties(), devices=[])
        else:
            props = [(cl.context_properties.PLATFORM, plats[0])] + get_gl_sharing_context_properties()
            cl_context = cl.Context(properties=props, devices=None)

        self.network.cl_context = cl_context

        #compile the network
        self.network.compile()

        glutMainLoop()
Ejemplo n.º 47
0
     (1.0, 1.0),
     (0.0, 0.0),
     (1.0, 1.0),
     (0.0, 1.0),)
 )
 geometry_vbo = vbo.VBO(data=pos, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER)
 texcoord_vbo = vbo.VBO(data=pos, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER)
 
 glClearColor(1.0, 0.0, 0.0, 1.0)
 
 platform = cl.get_platforms()[0]
 
 from pyopencl.tools import get_gl_sharing_context_properties
 import sys
 if sys.platform == "darwin":
     ctx = cl.Context(properties=get_gl_sharing_context_properties(),
             devices=[])
 else:
     # Some OSs prefer clCreateContextFromType, some prefer
     # clCreateContext. Try both.
     try:
         ctx = cl.Context(properties=[
             (cl.context_properties.PLATFORM, platform)]
             + get_gl_sharing_context_properties())
     except:
         ctx = cl.Context(properties=[
             (cl.context_properties.PLATFORM, platform)]
             + get_gl_sharing_context_properties(),
             devices = [platform.get_devices()[0]])
             
 
Ejemplo n.º 48
0
    def __init__(self, device=None, useGPU: bool = True) -> None:

        self._isUsingOpenCL2 = False
        self._isDebugBuild = False
        self._isUsingGPU = useGPU
        self._gl_interop = False
        self._clDevice = None

        # Show compiled output by setting envrionment flag
        self.enableCompilerOutput(OpenCLFlags.ENABLE_COMPILER_OUTPUT)
        self.enableCompilerCache(OpenCLFlags.ENABLE_CACHE)

        os.environ["AMPLXE_LOG_LEVEL"] = "TRACE"
        os.environ["TPSS_DEBUG"] = "1"

        if device:
            self._device = device
            self._platform = device.platform

        else:
            # Preselect the default platform and device

            # Get the OpenCL Platforms
            self._platform = cl.get_platforms()[0]

            logging.debug('Initialising OpenCL Runtime - {:s}'.format(
                self.platform.name))

            gpuDevices = self.gpuDevices  # get GPU devices of selected platform
            cpuDevices = self.cpuDevices  # get GPU devices of selected platform

            if len(gpuDevices) > 0 and useGPU:
                self._device = gpuDevices[0]  # take first GPU
                logging.debug('Using GPU - {:s} ({:s}) for OpenCL'.format(
                    self.device.name, self.device.version))

            elif len(cpuDevices) > 0:
                self._device = cpuDevices[0]  # take first CPU
                logging.debug('Using CPU for OpenCL')
            else:
                raise RuntimeError('No OpenCL device currently available')

        if self.isUsingGPU() and cl.have_gl() and self.hasGLShareExtension():
            from pyopencl.tools import get_gl_sharing_context_properties

            # Try setting up an OpenCL context with a Gl_Sharing
            try:
                self._context = cl.Context(
                    properties=[(cl.context_properties.PLATFORM,
                                 self.platform)] +
                    get_gl_sharing_context_properties())
                self._gl_interop = True
            except:
                logging.warning('Issue with GL Sharing at runtime')
                self._context = cl.Context(properties=[
                    (cl.context_properties.PLATFORM, self.platform)
                ],
                                           devices=[self.device])

        else:
            self._context = cl.Context(properties=[
                (cl.context_properties.PLATFORM, self.platform)
            ],
                                       devices=[self.device])
Ejemplo n.º 49
0
            p:                      - start or pause the program\n
            q,Esc:                  - exit the program\n
          ------------------------------------------------------------------------------\n
          \n"""

#-----
# MAIN
#-----
if __name__=="__main__":
    printHelp()
    window = glut_window()
    
    (np_datax, np_datay, np_dataz, np_life, np_position, np_velocity, np_zmel, gl_position, gl_color) = initial_buffers(num_particles)
    
    platform = cl.get_platforms()[0]
    context = cl.Context(properties=[(cl.context_properties.PLATFORM, platform)] + get_gl_sharing_context_properties())  
    queue = cl.CommandQueue(context)
    
    cl_life = cl.Buffer(context, mf.COPY_HOST_PTR, hostbuf=np_life)
    cl_velocity = cl.Buffer(context, mf.COPY_HOST_PTR, hostbuf=np_velocity)
    cl_zmel = cl.Buffer(context, mf.COPY_HOST_PTR, hostbuf=np_zmel)
    
    cl_datax = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=np_datax)
    cl_datay = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=np_datay)
    cl_dataz = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=np_dataz)

    cl_start_position = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=np_position)
    cl_start_velocity = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=np_velocity)
    
    if hasattr(gl_position,'buffers'):
        cl_gl_position = cl.GLBuffer(context, mf.READ_WRITE, int(gl_position.buffers[0]))
Ejemplo n.º 50
0
def init():
    platform = cl.get_platforms()[0]
    global ctx
    from pyopencl.tools import get_gl_sharing_context_properties
    import sys
    if sys.platform == "darwin":
        ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                devices=[])
    else:
        # Some OSs prefer clCreateContextFromType, some prefer
        # clCreateContext. Try both.
        try:
            ctx = cl.Context(properties=[
                (cl.context_properties.PLATFORM, platform)]
                + get_gl_sharing_context_properties())
        except:
            ctx = cl.Context(properties=[
                (cl.context_properties.PLATFORM, platform)]
                + get_gl_sharing_context_properties(),
                devices = [platform.get_devices()[0]])

    global buf
    global tex
    global tex1
    global image

    image = read_pgm("lena512.pgm", byteorder='<')
    image = image.ravel() # make 1D
    size = image_height * image_width


    #Texture setup base
    tex1 = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, tex1)

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE8, image_width, image_height, 0, GL_RED, GL_UNSIGNED_BYTE, image);



    # Texture setup CL
    tex = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, tex)

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE8, image_width, image_height, 0, GL_RED, GL_UNSIGNED_BYTE, None);


    # Buffer setup
    buf = glGenBuffers(1)
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER, buf)
    glBufferData(GL_PIXEL_UNPACK_BUFFER, image_height * image_width, None, GL_STREAM_DRAW)


    # CL setup
    global queue
    global prog

    #image_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=image)
    #mem = cl.GLBuffer(ctx, mf.WRITE_ONLY, numpy.float32(buf))

    queue = cl.CommandQueue(ctx)
    prog = cl.Program(ctx, src).build()

    #cl.enqueue_acquire_gl_objects(queue, [mem])
    #add_knl = prog.add
    #add_knl.set_args(image_buf, mem)
    #cl.enqueue_nd_range_kernel(queue, add_knl, image.shape, None)
    #cl.enqueue_release_gl_objects(queue, [mem])

    #queue.finish()
    #glFlush()


    # Unbind
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
    glBindTexture(GL_TEXTURE_2D, 0);
Ejemplo n.º 51
0
    glut.glutIdleFunc(idle_cb)
    glut.glutDisplayFunc(display_cb)
    glut.glutKeyboardFunc(keyboard_cb)
    glut.glutReshapeFunc(reshape_cb)
    glut.glutMouseFunc(mouse_cb)
    glut.glutMotionFunc(mouse_motion_cb)

    # must create VBOs before initializing openCL context???

    # Initialize simulation controller
    controller = Controller(screen_width, screen_height, 0)
    camera = Camera(0.05, 10)

    # Initialize OpenCL
    cl_platform = cl.get_platforms()[0]
    cl_context = cl.Context(
        properties=[(cl.context_properties.PLATFORM, cl_platform)] +
        get_gl_sharing_context_properties())
    cl_queue = cl.CommandQueue(cl_context)
    cl_program = cl.Program(cl_context, open('gravity.c', 'r').read()).build()
    kernel_step = cl_program.gravity
    kernel_init = cl_program.initialize

    controller.cl_init()

    # Begin main loop
    initialize_scene()
    glut.glutMainLoop()

    #glutFullScreen()
Ejemplo n.º 52
0
    return


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    f = QtOpenGL.QGLFormat.defaultFormat()

    f.setSampleBuffers(True)
    QtOpenGL.QGLFormat.setDefaultFormat(f)

    canvas = CGLPlotWidget()

    gl_context = canvas.context()
    gl_context.makeCurrent()
    cl_context = cl.Context(properties=get_gl_sharing_context_properties(), devices=[])

    plot1 = LinePlot(gl_context, cl_context,
                     n_vertices, scale=0.5, color=(1, 0, 0))

    plot2 = LinePlot(gl_context, cl_context,
                     n_vertices, scale=1.1, color=(0, .8, .2))


    generate_sin = cl.Program(cl_context, src).build().generate_sin

    pipe_segment = ComputationalPipe(gl_context, cl_context, (n_vertices,), None,
                                     generate_sin,
                                     plot1.vtx_array.cl_buffer, np.float32(1.1))

    plot1.add_pipe_segment(pipe_segment)
Ejemplo n.º 53
0
 def clinit(self):
     plats = cl.get_platforms()
     from pyopencl.tools import get_gl_sharing_context_properties
     self.ctx = cl.Context(properties=get_gl_sharing_context_properties(),
                           devices=[])
     self.queue = cl.CommandQueue(self.ctx)
Ejemplo n.º 54
0
    def __init__(self,
                 descriptor,
                 geometry,
                 moments,
                 collide,
                 pop_eq_src='',
                 boundary_src='',
                 platform=0,
                 precision='single',
                 layout=None,
                 padding=None,
                 align=False,
                 opengl=False):
        self.descriptor = descriptor
        self.geometry = geometry
        self.grid = Grid(self.geometry, padding)

        self.time = 0

        self.float_type = {
            'single': (numpy.float32, 'float'),
            'double': (numpy.float64, 'double'),
        }.get(precision, None)

        self.mako_lookup = TemplateLookup(directories=[Path(__file__).parent])

        self.platform = cl.get_platforms()[platform]

        if opengl:
            try:
                self.context = cl.Context(
                    properties=[(cl.context_properties.PLATFORM,
                                 self.platform)] +
                    get_gl_sharing_context_properties())
            except:
                self.context = cl.Context(
                    properties=[(cl.context_properties.PLATFORM, self.platform)
                                ] + get_gl_sharing_context_properties(),
                    devices=[self.platform.get_devices()[0]])
        else:
            self.context = cl.Context(
                properties=[(cl.context_properties.PLATFORM, self.platform)])

        self.queue = cl.CommandQueue(self.context)

        self.memory = Memory(self.descriptor, self.grid, self.context,
                             self.float_type[0], align, opengl)
        self.tick = False

        self.moments = moments
        self.collide = collide

        self.pop_eq_src = pop_eq_src
        self.boundary_src = boundary_src

        self.layout = layout

        self.compiler_args = {
            'single': '-cl-single-precision-constant -cl-fast-relaxed-math',
            'double': '-cl-fast-relaxed-math'
        }.get(precision, None)

        self.build_kernel()

        self.program.equilibrilize(self.queue, self.grid.size(), self.layout,
                                   self.memory.cl_pop_a,
                                   self.memory.cl_pop_b).wait()

        self.material = numpy.ndarray(shape=(self.memory.volume, 1),
                                      dtype=numpy.int32)
Ejemplo n.º 55
0
def _make_context(platform_id=None, device_id=None):
    """
    Actually creates a context and return its ids'

    Parameters
    ----------
    platform_id : platform number
        int
    device_id : device number in the platform
        int

    """
    if not pyopencl:
        raise RuntimeError("PyOpenCL not installed on the system !")
    properties = get_gl_sharing_context_properties()
    enum_plat = pyopencl.context_properties.PLATFORM
    ids = None
    if (platform_id is not None) and (device_id is not None):
        platform = pyopencl.get_platforms()[platform_id]
        device = platform.get_devices()[device_id]
        try:
            ctx = pyopencl.Context(devices=[device],
                                   properties=[(enum_plat, platform)]
                                   + properties)
            ids = (platform_id, device_id)
        except:
            ctx = None

    elif sys.platform == "darwin":
        ctx = pyopencl.Context(properties=properties,
                               devices=[])
        for platform_id, platform in enumerate(pyopencl.get_platforms()):
            for device_id, device in enumerate(platform.get_device()):
                if ctx.devices[0] == device:
                    ids = (platform_id, device_id)
    else:
        # Some OSs prefer clCreateContextFromType, some prefer
        # clCreateContext. Try both and loop.
        for platform_id, platform in enumerate(pyopencl.get_platforms()):
            try:
                ctx = pyopencl.Context(properties=properties +
                                       [(enum_plat, platform)])
                device = ctx.devices[0]
                if device.type != pyopencl.device_type.GPU:
                    # Wrongly selected non GPU device
                    ctx = None
                    raise
            except:
                for device_id, device in enumerate(platform.get_devices()):
                    if device.type != pyopencl.device_type.GPU:
                        continue
                    try:
                        ctx = pyopencl.Context(devices=[device],
                                               properties=properties +
                                               [(enum_plat, platform)])
                    except:
                        ctx = None
                    else:
                        ids = (platform_id, device_id)
                        break
            else:
                for device_id, device in enumerate(platform.get_devices()):
                    if ctx.devices[0] == device:
                        ids = (platform_id, device_id)
                        break
                break
            if ctx:
                break
    return ctx, ids