Пример #1
0
// This function has to be called after all the OpenGL textures have been created
bool RayCastRenderer::resetBuffers(void)
{
  F();

  size_t cell_cnt = m_data_width * m_data_height * m_data_depth;

  try
  {
    m_cell_cnts_buf = boost::compute::buffer(m_cl_ctx, cell_cnt * sizeof(cl_uint));
    m_grads_x_buf = boost::compute::buffer(m_cl_ctx, cell_cnt * sizeof(cl_float));
    m_grads_y_buf = boost::compute::buffer(m_cl_ctx, cell_cnt * sizeof(cl_float));
    m_grads_z_buf = boost::compute::buffer(m_cl_ctx, cell_cnt * sizeof(cl_float));
    m_data_cl_img = boost::compute::opengl_texture(m_cl_ctx, GL_TEXTURE_3D, 0, m_data.textureId());
  }
  catch (const boost::compute::opencl_error & e)
  {
    ERRORM(e.what());
    return false;
  }
  catch (const std::exception & e)
  {
    ERRORM("An unexpected error occured during SPHUniformGrid initialization: " << e.what());
    return false;
  }

  return true;
}
Пример #2
0
Файл: ocl.cpp Проект: jcxz/DIP
bool GLBuffer::bufferData(const GLvoid *data, GLsizeiptr size, AccessType at, GLenum usage)
{
  assert(m_ctx != nullptr);

  OGLF->glGetError();  // clear any previous errors

  OGLF->glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
  OGLF->glBufferData(GL_ARRAY_BUFFER, size, data, usage);

  {
    GLenum err = OGLF->glGetError();
    if (err != GL_NO_ERROR)
    {
      ERRORM("Failed to buffer data: " << ogl::errorToStr(err));
      return false;
    }
  }

  OGLF->glBindBuffer(GL_ARRAY_BUFFER, 0);

  cl_int err = CL_SUCCESS;
  cl_mem mem = clCreateFromGLBuffer(m_ctx, at, m_vbo, &err);
  if (err != CL_SUCCESS)
  {
    ERRORM("Failed to create OpenCL buffer: " << ocl::errorToStr(err));
    return false;
  }

  clReleaseMemObject(m_mem);

  m_mem = mem;

  return true;
}
Пример #3
0
bool ConvFilterBase::setFilterKernel(const float *filter, int size, int filter_w,
                                     QCLBuffer & filter_ocl,
                                     QCLKernel & kernel_ocl,
                                     int & filter_ocl_size)
{
  if (size != filter_ocl_size)
  {
    filter_ocl = m_ctx->createBufferCopy(filter, size * sizeof(float), QCLMemoryObject::ReadOnly);
    if (filter_ocl.isNull())
    {
      ERRORM("Failed to create convolution kernel buffer: " << m_ctx->lastError());
      return false;
    }

    filter_ocl_size = size;

    kernel_ocl.setArg(FILTER_IDX, filter_ocl);
    kernel_ocl.setArg(FILTER_SIZE_IDX, filter_w);
    kernel_ocl.setArg(FILTER_SIZE_HALF_IDX, (filter_w - 1) / 2);
  }
  else
  {
    if (!filter_ocl.write(filter, size * sizeof(float)))
    {
      ERRORM("Failed to write convolution kernel data: " << m_ctx->lastError());
      return false;
    }
  }

  return true;
}
Пример #4
0
bool DebugParticleSystem::init(void)
{
    try
    {
        /* create gen_rand_particles program and kernel */
        {
            QFile f(":/src/opencl/gen_rand_particles.cl");
            if (!f.open(QFile::ReadOnly)) return false;
            m_gen_rand_particles_prog = boost::compute::program::build_with_source(f.readAll().toStdString(), m_cl_ctx);
            m_gen_rand_particles_kernel = m_gen_rand_particles_prog.create_kernel("gen_part_positions");
        }

        /* create polar_spiral program and kernel */
        {
            QFile f(":/src/opencl/polar_spiral.cl");
            if (!f.open(QFile::ReadOnly)) return false;
            m_polar_spiral_prog = boost::compute::program::build_with_source(f.readAll().toStdString(), m_cl_ctx);
            m_polar_spiral_kernel = m_polar_spiral_prog.create_kernel("polar_spiral");
        }
    }
    catch (const boost::compute::opencl_error & e)
    {
        ERRORM("DebugParticleSystem: An OpenCL error occured: " << e.what());
        return false;
    }
    catch (const std::exception & e)
    {
        ERRORM("DebugParticleSystem: An unexpected error occured during ParticleSystem initialization: "
               << e.what());
        return false;
    }

    return true;
}
Пример #5
0
Файл: Movie.cpp Проект: jcxz/ZPO
bool Movie::saveAsAVI(const std::string & filename, int fourcc) const
{
  if (m_frames.empty())
  {
    WARNM("There are no frames in the movie");
    return true;
  }

  cv::Size frame_size(m_frame_w, m_frame_h);
  cv::VideoWriter writer(filename, fourcc, m_fps, frame_size, true);
  if (!writer.isOpened())
  {
    ERRORM("Failed to create video writer");
    return false;
  }

  cv::Mat frame;

  for (int i = 0; i < m_frames.size(); ++i)
  {
    if (!qImage2CvMat(m_frames[i], frame))
    {
      ERRORM("Unsupported conversion from "
             << utils::qImageFormatToString(m_frames[i].format())
             << " pixel format");
      return false;
    }

    writer.write(frame);
  }

  return true;
}
Пример #6
0
bool RayCastRenderer::initCL(const boost::compute::context & ctx,
                             const boost::compute::command_queue & queue)
{
  F();

  try
  {
    // build opencl program
    QFile f(":/src/opencl/ray_cast_renderer.cl");
    if (!f.open(QFile::ReadOnly)) return false;

    m_prog = boost::compute::program::create_with_source(f.readAll().toStdString(), ctx);
    m_prog.build();

    // print build log in case there are any warnings
    std::string log(m_prog.build_log());
    if (!log.empty())
    {
      WARNM("---------------------- Build log ---------------------------------");
      WARNM(log);
      WARNM("------------------- End of Build log -----------------------------");
    }

    // create kernels
    m_calculate_particle_cnts_kernel = m_prog.create_kernel("ray_cast_renderer_calculate_particle_cnts");
    utils::ocl::printKernelInfo(m_calculate_particle_cnts_kernel);

    m_calculate_gradients_kernel = m_prog.create_kernel("ray_cast_renderer_calculate_gradients");
    utils::ocl::printKernelInfo(m_calculate_gradients_kernel);

    m_calculate_normals_kernel = m_prog.create_kernel("ray_cast_renderer_calculate_normals");
    utils::ocl::printKernelInfo(m_calculate_normals_kernel);

    m_queue = queue;
    m_cl_ctx = ctx;
  }
  catch (const boost::compute::opencl_error & e)
  {
    ERRORM(e.what());
    if (e.error_code() == CL_BUILD_PROGRAM_FAILURE) ERRORM(m_prog.build_log());
    return false;
  }
  catch (const std::exception & e)
  {
    ERRORM("An unexpected error occured during SPHUniformGrid initialization: " << e.what());
    return false;
  }

  return true;
}
Пример #7
0
Файл: Movie.cpp Проект: jcxz/ZPO
bool Movie::saveAsAVI(const std::string & filename, int fourcc)
{
  if (m_frames.empty())
  {
    WARNM("There are no frames in the movie");
    return true;
  }

  cv::Size frame_size(m_frame_w, m_frame_h);
  cv::VideoWriter writer(filename, fourcc, m_fps, frame_size, true);
  if (!writer.isOpened())
  {
    ERRORM("Failed to create video writer");
    return false;
  }

  //cv::Mat cv_frame(m_frame_h, m_frame_w, CV_8UC3, nullptr);
  cv::Mat cv_frame(m_frame_h, m_frame_w, CV_8UC4, nullptr);

  for (int i = 0; i < m_frames.size(); ++i)
  {
    QImage & frame = m_frames[i];

    if (frame.format() != QImage::Format_RGB888)
    {
      INFOM("Converting frame #" << i << " from "
            << utils::qImageFormatToString(frame.format())
            << " to QImage::Format_RGB888");

      frame = frame.convertToFormat(QImage::Format_RGB888);
      if (frame.isNull())
      {
        ERRORM("Failed to convert pixel format of frame #" << i << " to QImage::Format_RGB888");
        return false;
      }
    }

    // the const cast is here because the function called is constBits which returns a const pointer
    // and constBits() in turn is called because it does not detach the pixel buffer from QImage,
    // which is the desired behaviour in this case.
    // The cost_cast should also be safe here, since write method of VideoWriter should write to the
    // pixels provided
    cv_frame.data = const_cast<uchar*>(frame.constBits());
    writer.write(cv_frame);
  }

  return true;
}
Пример #8
0
Файл: ogl.cpp Проект: jcxz/DIP
bool loadSkyBoxTexture(QOpenGLTexture & tex,
                       const char *posx, const char *negx,
                       const char *posy, const char *negy,
                       const char *posz, const char *negz)
{
  if (!tex.create())
  {
    ERRORM("Failed to create skybox texture's OpenGL object name");
    return false;
  }

  tex.bind();
  utils::misc::ScopedGuard guard([&tex] { tex.release(); });
  (void) guard;

  if (!loadTextureHelper(posx, GL_TEXTURE_CUBE_MAP_POSITIVE_X)) return false;
  if (!loadTextureHelper(negx, GL_TEXTURE_CUBE_MAP_NEGATIVE_X)) return false;
  if (!loadTextureHelper(posy, GL_TEXTURE_CUBE_MAP_POSITIVE_Y)) return false;
  if (!loadTextureHelper(negy, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y)) return false;
  if (!loadTextureHelper(posz, GL_TEXTURE_CUBE_MAP_POSITIVE_Z)) return false;
  if (!loadTextureHelper(negz, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)) return false;

  OGLF->glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  OGLF->glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  OGLF->glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
  OGLF->glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  OGLF->glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  return true;
}
Пример #9
0
bool RayCastRenderer::resetDataTexture(void)
{
  F();

  // nahratie dat do textury
  if (!m_data.create())
  {
    ERRORM("Failed to create OpenGL 3D texture for volume data");
    return false;
  }

  OGLF->glBindTexture(GL_TEXTURE_3D, m_data.textureId());

  //OGLF->glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  //OGLF->glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  //OGLF->glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
  OGLF->glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  OGLF->glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  OGLF->glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
  OGLF->glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  OGLF->glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

  OGLF->glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA,
                     m_data_width, m_data_height, m_data_depth,
                     0, GL_RGBA, GL_FLOAT, nullptr);

  OGLF->glBindTexture(GL_TEXTURE_3D, 0);

  return true;
}
Пример #10
0
int elf_check_supported(Elf_Env *env, Elf64_Ehdr *hdr) {
	if (hdr->e_ident[0] != 0x7f ||
		hdr->e_ident[1] != 'E'  ||
		hdr->e_ident[2] != 'L'  ||
		hdr->e_ident[3] != 'F') {
		ERROR("Bad magic number");
		return 0;
	}
	if(hdr->e_ident[EI_CLASS] != 2) {
		ERROR("Bad EI_CLASS");
		return 0;
	}
	if(hdr->e_ident[EI_DATA] != 2) {
		ERROR("Bad EI_DATA");
		return 0;
	}
	if(hdr->e_ident[EI_VERSION] != 1) {
		ERROR("Bad EI_VERSION");
		return 0;
	}
	if(hdr->e_ident[EI_OSABI] != 9) {
		ERRORM("Bad EI_OSABI: %X", hdr->e_ident[EI_OSABI]);
		return 0;
	}
	if(hdr->e_ident[EI_ABIVERSION] != 0) {
		ERRORM("Bad EI_ABIVERSION: %X", hdr->e_ident[EI_ABIVERSION]);
		return 0;
	}
	if(hdr->e_type != 2) {
		ERRORM("Bad e_type: %X", hdr->e_type);
		return 0;
	}
	if(hdr->e_machine != 8) {
		ERRORM("Bad e_machine: %X", hdr->e_machine);
		return 0;
	}
	if(hdr->e_version != 1) {
		ERROR("Bad e_version");
		return 0;
	}
	if((hdr->e_flags != 0x30000007) && (hdr->e_flags != 0x30C2C005)) {
		ERRORM("Bad e_flags: %X", hdr->e_flags);
		return 0;
	}
	return 1;
}
Пример #11
0
bool MeshWarpWidget::setImage(const QString & filename)
{
  QImage img(filename);
  if (img.isNull())
  {
    ERRORM("Failed to open image: " << filename.toStdString());
    return false;
  }
  return setImage(img);
}
Пример #12
0
bool OilifyFilter::init(void)
{
  // skip OpenCL initialization in case context is not given
  if (m_ctx == nullptr) return (m_good = true);

  // compile program
  m_program = m_ctx->buildProgramFromSourceFile(CLSRCFILE("oilify.cl"));
  if (m_program.isNull())
  {
    ERRORM("Failed to create Oilify filter program: " << m_program.log().toStdString());
    return false;
  }

  // create kernel
#ifndef OPTIMIZED_VER
  m_kernel = m_program.createKernel("oilify");
  if (m_kernel.isNull())
  {
    ERRORM("Failed to create Oilify filter kernel: " << m_program.log().toStdString());
    return false;
  }
#else
  m_kernel_oilify = m_program.createKernel("oilify");
  if (m_kernel_oilify.isNull())
  {
    ERRORM("Failed to create Oilify filter kernel: " << m_program.log().toStdString());
    return false;
  }

  m_kernel_oilify_prepare = m_program.createKernel("oilify_prepare");
  if (m_kernel_oilify_prepare.isNull())
  {
    ERRORM("Failed to create oilify_prepare filter kernel: " << m_program.log().toStdString());
    return false;
  }
#endif

  setRadius(DEFAULT_RADIUS);
  setLevels(DEFAULT_LEVELS);

  return (m_good = true);
}
Пример #13
0
bool DebugParticleSystem::reset_impl(const io::VoxelMesh * /* mesh */)
{
    INFOM("DebugParticleSystem: Initializing Test Simulation data");

    unsigned int part_num = m_sim_params->particleCount();

    /* allocate the buffers to hold particle positions and colors */
    if (!m_particle_pos_buf.bufferData(nullptr, part_num * sizeof(cl_float4), utils::ocl::GLBuffer::WRITE_ONLY))
    {
        ERRORM("DebugParticleSystem: Failed to initialize position GLBuffer");
        return false;
    }

    if (!m_particle_col_buf.bufferData(nullptr, part_num * sizeof(cl_float4), utils::ocl::GLBuffer::WRITE_ONLY))
    {
        ERRORM("DebugParticleSystem: Failed to initialize color GLBuffer");
        return false;
    }

    /* initialize kernel arguments */
    if (!utils::ocl::KernelArgs(m_gen_rand_particles_kernel, "m_gen_rand_particles_kernel")
            .arg(m_particle_pos_buf.getCLID())
            .arg(m_particle_col_buf.getCLID()))
        //.arg((cl_ulong) (time(nullptr))))
    {
        return false;
    }

    cl_float3 position = { 0.0f, 0.0f, 0.0f };
    if (!utils::ocl::KernelArgs(m_polar_spiral_kernel, "m_polar_spiral_kernel")
            .arg(m_particle_pos_buf.getCLID())
            .arg(m_particle_col_buf.getCLID())
            .arg(position))
    {
        return false;
    }

    m_sim_params->setTime(0.0f);

    return true;
}
Пример #14
0
bool RayCastRenderer::reset_impl(int w, int h)
{
  F();

  if ((m_data_width <= 0) || (m_data_height <= 0) || (m_data_depth <= 0))
  {
    ERRORM("RayCastRenderer: grid size is not set");
    return false;
  }

  if ((m_cell_starts_buf.get() == nullptr) || (m_cell_ends_buf.get() == nullptr))
  {
    ERRORM("RayCastRenderer: cell_starts or cell_ends buffer is not set");
    return false;
  }

  return resetDataTexture() &&
      resetBuffers() &&
      resetFramebuffer(w, h) &&
      resetTransferFunctionTexture();
}
Пример #15
0
bool PointSpriteRenderer::init(void)
{
  // compile shaders
  if (!utils::ogl::buildShaderProgram(m_prog,
                                      ":/src/opengl/point_sprite_renderer.vert",
                                      ":/src/opengl/point_sprite_renderer.frag"))
  {
    ERRORM("Failed to compile shaders for point sprite program");
    return false;
  }

  // set default light parameters
  m_light_pos.setX(-10.0f);
  m_light_pos.setY( 10.0f);
  m_light_pos.setZ( 15.0f);

  m_light_ambient_col.setX(0.8f);
  m_light_ambient_col.setY(0.8f);
  m_light_ambient_col.setZ(0.8f);

  m_light_diffuse_col.setX(1.0f);
  m_light_diffuse_col.setY(1.0f);
  m_light_diffuse_col.setZ(1.0f);

  // uniform color program
  GLuint uc_prog = m_prog.programId();

  OGLF->glUseProgram(uc_prog);
  //OGLF->glUniform3f(OGLF->glGetUniformLocation(uc_prog, "light_pos"), -10.0f, 10.0f, 15.0f);
  //OGLF->glUniform3f(OGLF->glGetUniformLocation(uc_prog, "light_col_a"), 0.8f, 0.8f, 0.8f);
  //OGLF->glUniform3f(OGLF->glGetUniformLocation(uc_prog, "light_col_d"), 1.0f, 1.0f, 1.0f);
  OGLF->glUniform3f(OGLF->glGetUniformLocation(uc_prog, "light_col_s"), 1.0f, 1.0f, 1.0f);

  OGLF->glUseProgram(0);

  // Create vertex array object
  return m_vao.create();
}
Пример #16
0
float *ConvFilterBase::mapFilterKernel(int size, int filter_w,
                                       QCLBuffer & filter_ocl,
                                       QCLKernel & kernel_ocl,
                                       int & filter_ocl_size)
{
  if (size != filter_ocl_size)
  {
    filter_ocl = m_ctx->createBufferDevice(size * sizeof(float), QCLBuffer::ReadOnly);
    if (filter_ocl.isNull())
    {
      ERRORM("Failed to create convolution kernel buffer: " << m_ctx->lastError());
      return nullptr;
    }

    filter_ocl_size = size;

    kernel_ocl.setArg(FILTER_IDX, filter_ocl);
    kernel_ocl.setArg(FILTER_SIZE_IDX, filter_w);
    kernel_ocl.setArg(FILTER_SIZE_HALF_IDX, (filter_w - 1) / 2);
  }

  return (float *) filter_ocl.map(QCLBuffer::WriteOnly);
}
Пример #17
0
bool OilifyFilter::runCL(const QCLImage2D & src, int w, int h, QCLImage2D & dst)
{
  if (!isGood()) return false;
#ifndef OPTIMIZED_VER
  m_kernel.setArg(SRC_IDX, src);
  m_kernel.setArg(DST_IDX, dst);
  m_kernel.setGlobalWorkSize(w, h);
  m_kernel.run();
#else
  if ((m_tmp_buf_w != w) || (m_tmp_buf_h != h))
  {
    QCLImageFormat fmt(QCLImageFormat::Order_BGRA, QCLImageFormat::Type_Unnormalized_UInt8);
    m_tmp_buf = m_ctx->createImage2DDevice(fmt, QSize(w, h), QCLImage2D::ReadWrite);
    if (m_tmp_buf.isNull())
    {
      ERRORM("Failed to create temporary buffer for Oilify Filter: " << m_ctx->lastError());
      return false;
    }

    m_tmp_buf_w = w;
    m_tmp_buf_h = h;

    m_kernel_oilify_prepare.setGlobalWorkSize(w, h);
    m_kernel_oilify.setGlobalWorkSize(w, h);
  }

  m_kernel_oilify_prepare.setArg(SRC_IDX, src);
  m_kernel_oilify_prepare.setArg(DST_IDX, m_tmp_buf);
  m_kernel_oilify_prepare.run();

  m_kernel_oilify.setArg(SRC_IDX, m_tmp_buf);
  m_kernel_oilify.setArg(DST_IDX, dst);
  m_kernel_oilify.run();
#endif
  return true;
}
Пример #18
0
Movie *MainWindow::morphMovie(const QImage & src_img, const Mesh & src_mesh,
                              const QImage & dst_img, const Mesh & dst_mesh,
                              int nframes)
{
  if (!src_mesh.hasSameDimensions(dst_mesh))
  {
    ERRORM("source mesh has different dimensions than destination mesh");
    return nullptr;
  }

  Mesh tmp_mesh(src_mesh.sizeX(), src_mesh.sizeY(), src_mesh.width(), src_mesh.heigth());

  Movie *movie = new Movie;

  ui->progressBar->setMaximum(nframes);
  ui->progressBar->show();

  for (int i = 0; i < nframes; ++i)
  {
    float t = float(i) / (float(nframes - 1));

    QImage frame(morphFrame(src_img, src_mesh, dst_img, dst_mesh, tmp_mesh, t));
    if (frame.isNull())
    {
      WARNM("Failed to morph frame n. " << i);
    }

    movie->addFrame(frame);

    ui->progressBar->setValue(i);
  }

  ui->progressBar->hide();

  return movie;
}
Пример #19
0
Файл: ogl.cpp Проект: jcxz/DIP
bool load2DTexture(QOpenGLTexture & tex,
                   const char *name,
                   GLint internal_format,
                   GLint filter_mode, GLint clamp_mode)
{
  if (!tex.create())
  {
    ERRORM("Failed to create 2D texture's OpenGL object name");
    return false;
  }

  tex.bind();
  utils::misc::ScopedGuard guard([&tex] { tex.release(); });
  (void) guard;

  if (!loadTextureHelper(name, GL_TEXTURE_2D, internal_format)) return false;

  OGLF->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter_mode);
  OGLF->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter_mode);
  OGLF->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, clamp_mode);
  OGLF->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, clamp_mode);

  return true;
}
Пример #20
0
Файл: ocl.cpp Проект: jcxz/DIP
bool selectGLDeviceAndPlatform(cl_device_id *device, cl_platform_id *platform)
{
  assert(device != nullptr);
  assert(platform != nullptr);

  /* first try to get the necessary extension */
  clGetGLContextInfoKHR_fn clGetGLContextInfoKHR = (clGetGLContextInfoKHR_fn) clGetExtensionFunctionAddress("clGetGLContextInfoKHR");
  if (clGetGLContextInfoKHR == nullptr)
  {
    ERRORM("clGetGLContextInfoKHR extension function not supproted.");
    return false;
  }

#if defined(FLUIDSIM_OS_MAC)
  cl_context_properties props[] = {
    CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
    (cl_context_properties) CGLGetShareGroup(CGLGetCurrentContext()),
    0
  };

  cl_int err = clGetGLContextInfoKHR(props,                                  // the OpenGL context
                                     CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR,   // get the id of the device currently executing OpenGL
                                     sizeof(*device),
                                     device,
                                     nullptr);
  if (err != CL_SUCCESS)
  {
    ERRORM("Failed to retrieve the OpenCL id of the device executing OpenGL: " << errorToStr(err));
    return false;
  }

  /* get the platform associated with the device */
  err = clGetDeviceInfo(*device, CL_DEVICE_PLATFORM, sizeof(*platform), platform, nullptr);
  if (err != CL_SUCCESS)
  {
    ERRORM("Failed to retirieve platform id for the device executing OpenGL: " << errorToStr(err));
    return false;
  }
#else
  cl_context_properties props[] = {
#if defined(FLUIDSIM_OS_UNIX)
    CL_GL_CONTEXT_KHR, (cl_context_properties) glXGetCurrentContext(),
    CL_GLX_DISPLAY_KHR, (cl_context_properties) glXGetCurrentDisplay(),
    CL_CONTEXT_PLATFORM, (cl_context_properties) nullptr,
#elif defined(FLUIDSIM_OS_WIN)
    CL_GL_CONTEXT_KHR, (cl_context_properties) wglGetCurrentContext(),
    CL_WGL_HDC_KHR, (cl_context_properties) wglGetCurrentDC(),
    CL_CONTEXT_PLATFORM, (cl_context_properties) nullptr,
#else
# error "Unsupported OS platform"
#endif
    0
  };

  std::vector<boost::compute::platform> platform_list = boost::compute::system::platforms();

  for (const boost::compute::platform & p : platform_list)
  {
    WARNM("platform: " << p.name());
    props[5] = (cl_context_properties) p.id();
    cl_int err = clGetGLContextInfoKHR(props,                                 // the OpenGL context
                                       CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR,  // get the id of the device currently executing OpenGL
                                       sizeof(*device),
                                       device,
                                       nullptr);
    if ((err == CL_SUCCESS) && (boost::compute::device(*device).type() == CL_DEVICE_TYPE_GPU))
    {
      *platform = (cl_platform_id) props[5];
      return true;
    }
    else
    {
      WARNM("clGetGLContextInfoKHR: " << errorToStr(err));
    }
  }
#endif

  return false;
}
Пример #21
0
Файл: ocl.cpp Проект: jcxz/DIP
bool initCLGLContext(boost::compute::context & ctx)
{
  INFOM("Initializing OpenCL/OpenGL shared context");

#if 1
  /* select appropriate device and platform */
  cl_platform_id platform = nullptr;
  cl_device_id device = nullptr;

  if ((!utils::ocl::selectGLDeviceAndPlatform(&device, &platform)) &&
      (!utils::ocl::selectPlatformAndDevice(&device, &platform)))
  {
    ERRORM("Failed to select an appropriate device or platform");
    return false;
  }

  /* setup context */
  cl_context_properties props[] = {
#if defined(FLUIDSIM_OS_MAC)
    CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
    (cl_context_properties) CGLGetShareGroup(CGLGetCurrentContext()),
#elif defined(FLUIDSIM_OS_UNIX)
    CL_GL_CONTEXT_KHR, (cl_context_properties) glXGetCurrentContext(),
    CL_GLX_DISPLAY_KHR, (cl_context_properties) glXGetCurrentDisplay(),
    CL_CONTEXT_PLATFORM, (cl_context_properties) platform,
#elif defined(FLUIDSIM_OS_WIN)
    CL_GL_CONTEXT_KHR, (cl_context_properties) wglGetCurrentContext(),
    CL_WGL_HDC_KHR, (cl_context_properties) wglGetCurrentDC(),
    CL_CONTEXT_PLATFORM, (cl_context_properties) platform,
#else
# error "Unsupported OS platform"
#endif
    0
  };

  /* create opencl context */
  cl_int err = CL_SUCCESS;
  cl_context ctx_ = clCreateContext(props, 1, &device, nullptr, nullptr, &err);
  if (err != CL_SUCCESS)
  {
    ERRORM("Failed to create OpenCL context: " << utils::ocl::errorToStr(err));
    return false;
  }

  ctx = boost::compute::context(ctx_, false);
  utils::ocl::printDeviceInfo(ctx.get_devices());
#else
  try
  {
    /* create opencl context */
    ctx = boost::compute::opengl_create_shared_context();
    utils::ocl::printDeviceInfo(ctx.get_devices());
  }
  catch (const boost::compute::opencl_error & e)
  {
    ERRORM(e.what());
    return false;
  }
  catch (const boost::compute::unsupported_extension_error & e)
  {
    ERRORM(e.what());
    return false;
  }
  catch (const std::exception & e)
  {
    ERRORM("An unexpected error occured during opencl context initialization: " << e.what());
    return false;
  }
#endif

  INFOM("Successfully initialized OpenCL context");
  INFOM("Using device   : " << ctx.get_device().name());
  INFOM("Using platform : " << ctx.get_device().platform().name());

  return true;
}
Пример #22
0
bool RayCastRenderer::resetTransferFunctionTexture(void)
{
  F();

  // nahratie dat do textury
  if (!m_transfer_func.create())
  {
    ERRORM("Failed to create OpenGL 1D texture for transfer function");
    return false;
  }

  static constexpr int n = 1024;
  static constexpr float factor = 255.0f / float(n);

  unsigned char *pixels = new unsigned char[n * 4];

#define BLUE_FOAM_CLEAR_WATER

  for (int i = 0; i < n; ++i)
  {
#ifdef BLUE_FOAM_CLEAR_WATER
    //if (i < 5)
    //if (i < -1)
    if (i > 256)
    {
      pixels[i * 4 + 0] = 0;  // red
      pixels[i * 4 + 1] = 0;  // green
      pixels[i * 4 + 2] = i * factor;  // blue
      pixels[i * 4 + 3] = 0;
    }
    else
    {
      pixels[i * 4 + 0] = 0;  // red
      pixels[i * 4 + 1] = 0;  // green
      pixels[i * 4 + 2] = i * factor;  // blue
      //pixels[i * 4 + 3] = i * factor; //255;
      pixels[i * 4 + 3] = i * factor; //255;
    }
#elif YELLOW_GREEN_WATER
    if (i > 256)
    {
      pixels[i * 4 + 0] = 0;  // red
      pixels[i * 4 + 1] = 0;  // green
      pixels[i * 4 + 2] = i * factor;  // blue
      pixels[i * 4 + 3] = 0;
    }
    else
    {
      pixels[i * 4 + 0] = i * i * factor;  // red
      pixels[i * 4 + 1] = i * i * factor;  // green
      pixels[i * 4 + 2] = i * factor;  // blue
      pixels[i * 4 + 3] = i * factor; //255;
    }
#elif GRAY_WATER
    if (i > 256)
    {
      pixels[i * 4 + 0] = 0;  // red
      pixels[i * 4 + 1] = 0;  // green
      pixels[i * 4 + 2] = i * factor;  // blue
      pixels[i * 4 + 3] = 0;
    }
    else
    {
      pixels[i * 4 + 0] = i * i * factor;  // red
      pixels[i * 4 + 1] = i * i * factor;  // green
      pixels[i * 4 + 2] = i * i * factor;  // blue
      pixels[i * 4 + 3] = i * factor; //255;
    }
#else
    if (i > 256)
    {
      pixels[i * 4 + 0] = 0;  // red
      pixels[i * 4 + 1] = 0;  // green
      pixels[i * 4 + 2] = i * factor;  // blue
      pixels[i * 4 + 3] = 10 / i;
    }
    else
    {
      pixels[i * 4 + 0] = i * factor;  // red
      pixels[i * 4 + 1] = i * factor;  // green
      pixels[i * 4 + 2] = (256 / i) * factor;  // blue
      pixels[i * 4 + 3] = i * factor; //255;
    }
#endif
  }

  m_transfer_func.bind();

  OGLF->glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  OGLF->glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  OGLF->glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

  OGLF->glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, n, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

  OGLF->glBindTexture(GL_TEXTURE_1D, 0);

  delete [] pixels;

  return true;
}