<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/fileapi/file_system_file_util_proxy.h"

#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop_proxy.h"
#include "webkit/fileapi/cross_file_util_helper.h"
#include "webkit/fileapi/file_system_file_util.h"
#include "webkit/fileapi/file_system_operation_context.h"

namespace fileapi {

using base::Bind;
using base::Callback;
using base::Owned;
using base::PlatformFileError;
using base::Unretained;

namespace {

typedef fileapi::FileSystemFileUtilProxy Proxy;

class CopyOrMoveHelper {
 public:
  CopyOrMoveHelper(CrossFileUtilHelper* helper)
      : helper_(helper),
        error_(base::PLATFORM_FILE_OK) {}
  ~CopyOrMoveHelper() {}

  void RunWork() {
    error_ = helper_->DoWork();
  }

  void Reply(const Proxy::StatusCallback& callback) {
    if (!callback.is_null())
      callback.Run(error_);
  }

 private:
  scoped_ptr<CrossFileUtilHelper> helper_;
  base::PlatformFileError error_;
  DISALLOW_COPY_AND_ASSIGN(CopyOrMoveHelper);
};

class EnsureFileExistsHelper {
 public:
  EnsureFileExistsHelper() : error_(base::PLATFORM_FILE_OK), created_(false) {}

  void RunWork(FileSystemFileUtil* file_util,
               FileSystemOperationContext* context,
               const FileSystemPath& path) {
    error_ = file_util->EnsureFileExists(context, path, &created_);
  }

  void Reply(const Proxy::EnsureFileExistsCallback& callback) {
    if (!callback.is_null())
      callback.Run(error_, created_);
  }

 private:
  base::PlatformFileError error_;
  bool created_;
  DISALLOW_COPY_AND_ASSIGN(EnsureFileExistsHelper);
};

class GetFileInfoHelper {
 public:
  GetFileInfoHelper() : error_(base::PLATFORM_FILE_OK) {}

  void RunWork(FileSystemFileUtil* file_util,
               FileSystemOperationContext* context,
               const FileSystemPath& path) {
    error_ = file_util->GetFileInfo(
        context, path, &file_info_, &platform_path_);
  }

  void Reply(const Proxy::GetFileInfoCallback& callback) {
    if (!callback.is_null())
      callback.Run(error_, file_info_, platform_path_);
  }

 private:
  base::PlatformFileError error_;
  base::PlatformFileInfo file_info_;
  FilePath platform_path_;
  DISALLOW_COPY_AND_ASSIGN(GetFileInfoHelper);
};

class ReadDirectoryHelper {
 public:
  ReadDirectoryHelper() : error_(base::PLATFORM_FILE_OK) {}

  void RunWork(FileSystemFileUtil* file_util,
               FileSystemOperationContext* context,
               const FileSystemPath& path) {
    error_ = file_util->ReadDirectory(context, path, &entries_);
  }

  void Reply(const Proxy::ReadDirectoryCallback& callback) {
    if (!callback.is_null())
      callback.Run(error_, entries_, false  /* has_more */);
  }

 private:
  base::PlatformFileError error_;
  std::vector<Proxy::Entry> entries_;
  DISALLOW_COPY_AND_ASSIGN(ReadDirectoryHelper);
};

}  // namespace

// static
bool FileSystemFileUtilProxy::Delete(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    bool recursive,
    const StatusCallback& callback) {
  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      base::Bind(&FileSystemFileUtil::Delete, base::Unretained(file_util),
                 context, path, recursive),
      callback);
}

// static
bool FileSystemFileUtilProxy::CreateOrOpen(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    int file_flags,
    const CreateOrOpenCallback& callback) {
  return base::FileUtilProxy::RelayCreateOrOpen(
      message_loop_proxy,
      base::Bind(&FileSystemFileUtil::CreateOrOpen, base::Unretained(file_util),
                 context, path, file_flags),
      base::Bind(&FileSystemFileUtil::Close, base::Unretained(file_util),
                 context),
      callback);
}

// static
bool FileSystemFileUtilProxy::Copy(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* src_util,
    FileSystemFileUtil* dest_util,
    const FileSystemPath& src_path,
    const FileSystemPath& dest_path,
    const StatusCallback& callback) {
  CopyOrMoveHelper* helper = new CopyOrMoveHelper(
      new CrossFileUtilHelper(
          context, src_util, dest_util, src_path, dest_path,
          CrossFileUtilHelper::OPERATION_COPY));
  return message_loop_proxy->PostTaskAndReply(
        FROM_HERE,
        Bind(&CopyOrMoveHelper::RunWork, Unretained(helper)),
        Bind(&CopyOrMoveHelper::Reply, Owned(helper), callback));
}

// static
bool FileSystemFileUtilProxy::Move(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
      FileSystemFileUtil* src_util,
      FileSystemFileUtil* dest_util,
      const FileSystemPath& src_path,
      const FileSystemPath& dest_path,
    const StatusCallback& callback) {
  CopyOrMoveHelper* helper = new CopyOrMoveHelper(
      new CrossFileUtilHelper(
          context, src_util, dest_util, src_path, dest_path,
          CrossFileUtilHelper::OPERATION_MOVE));
  return message_loop_proxy->PostTaskAndReply(
        FROM_HERE,
        Bind(&CopyOrMoveHelper::RunWork, Unretained(helper)),
        Bind(&CopyOrMoveHelper::Reply, Owned(helper), callback));
}

// static
bool FileSystemFileUtilProxy::EnsureFileExists(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    const EnsureFileExistsCallback& callback) {
  EnsureFileExistsHelper* helper = new EnsureFileExistsHelper;
  return message_loop_proxy->PostTaskAndReply(
        FROM_HERE,
        Bind(&EnsureFileExistsHelper::RunWork, Unretained(helper),
             file_util, context, path),
        Bind(&EnsureFileExistsHelper::Reply, Owned(helper), callback));
}

// static
bool FileSystemFileUtilProxy::CreateDirectory(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    bool exclusive,
    bool recursive,
    const StatusCallback& callback) {
  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      base::Bind(&FileSystemFileUtil::CreateDirectory,
                 base::Unretained(file_util),
                 context, path, exclusive, recursive),
      callback);
}

// static
bool FileSystemFileUtilProxy::GetFileInfo(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    const GetFileInfoCallback& callback) {
  GetFileInfoHelper* helper = new GetFileInfoHelper;
  return message_loop_proxy->PostTaskAndReply(
        FROM_HERE,
        Bind(&GetFileInfoHelper::RunWork, Unretained(helper),
             file_util, context, path),
        Bind(&GetFileInfoHelper::Reply, Owned(helper), callback));
}

// static
bool FileSystemFileUtilProxy::ReadDirectory(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    const ReadDirectoryCallback& callback) {
  ReadDirectoryHelper* helper = new ReadDirectoryHelper;
  return message_loop_proxy->PostTaskAndReply(
        FROM_HERE,
        Bind(&ReadDirectoryHelper::RunWork, Unretained(helper),
             file_util, context, path),
        Bind(&ReadDirectoryHelper::Reply, Owned(helper), callback));
}

// static
bool FileSystemFileUtilProxy::Touch(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    const base::Time& last_access_time,
    const base::Time& last_modified_time,
    const StatusCallback& callback) {
  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      base::Bind(&FileSystemFileUtil::Touch, base::Unretained(file_util),
                 context, path, last_access_time, last_modified_time),
      callback);
}

// static
bool FileSystemFileUtilProxy::Truncate(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    int64 length,
    const StatusCallback& callback) {
  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      base::Bind(&FileSystemFileUtil::Truncate, base::Unretained(file_util),
                 context, path, length),
      callback);
}

}  // namespace fileapi
<commit_msg>Use RelayFileTask instead of CopyOrMoveHelper<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/fileapi/file_system_file_util_proxy.h"

#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop_proxy.h"
#include "webkit/fileapi/cross_file_util_helper.h"
#include "webkit/fileapi/file_system_file_util.h"
#include "webkit/fileapi/file_system_operation_context.h"

namespace fileapi {

using base::Bind;
using base::Callback;
using base::Owned;
using base::PlatformFileError;
using base::Unretained;

namespace {

typedef fileapi::FileSystemFileUtilProxy Proxy;

class EnsureFileExistsHelper {
 public:
  EnsureFileExistsHelper() : error_(base::PLATFORM_FILE_OK), created_(false) {}

  void RunWork(FileSystemFileUtil* file_util,
               FileSystemOperationContext* context,
               const FileSystemPath& path) {
    error_ = file_util->EnsureFileExists(context, path, &created_);
  }

  void Reply(const Proxy::EnsureFileExistsCallback& callback) {
    if (!callback.is_null())
      callback.Run(error_, created_);
  }

 private:
  base::PlatformFileError error_;
  bool created_;
  DISALLOW_COPY_AND_ASSIGN(EnsureFileExistsHelper);
};

class GetFileInfoHelper {
 public:
  GetFileInfoHelper() : error_(base::PLATFORM_FILE_OK) {}

  void RunWork(FileSystemFileUtil* file_util,
               FileSystemOperationContext* context,
               const FileSystemPath& path) {
    error_ = file_util->GetFileInfo(
        context, path, &file_info_, &platform_path_);
  }

  void Reply(const Proxy::GetFileInfoCallback& callback) {
    if (!callback.is_null())
      callback.Run(error_, file_info_, platform_path_);
  }

 private:
  base::PlatformFileError error_;
  base::PlatformFileInfo file_info_;
  FilePath platform_path_;
  DISALLOW_COPY_AND_ASSIGN(GetFileInfoHelper);
};

class ReadDirectoryHelper {
 public:
  ReadDirectoryHelper() : error_(base::PLATFORM_FILE_OK) {}

  void RunWork(FileSystemFileUtil* file_util,
               FileSystemOperationContext* context,
               const FileSystemPath& path) {
    error_ = file_util->ReadDirectory(context, path, &entries_);
  }

  void Reply(const Proxy::ReadDirectoryCallback& callback) {
    if (!callback.is_null())
      callback.Run(error_, entries_, false  /* has_more */);
  }

 private:
  base::PlatformFileError error_;
  std::vector<Proxy::Entry> entries_;
  DISALLOW_COPY_AND_ASSIGN(ReadDirectoryHelper);
};

}  // namespace

// static
bool FileSystemFileUtilProxy::Delete(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    bool recursive,
    const StatusCallback& callback) {
  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      base::Bind(&FileSystemFileUtil::Delete, base::Unretained(file_util),
                 context, path, recursive),
      callback);
}

// static
bool FileSystemFileUtilProxy::CreateOrOpen(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    int file_flags,
    const CreateOrOpenCallback& callback) {
  return base::FileUtilProxy::RelayCreateOrOpen(
      message_loop_proxy,
      base::Bind(&FileSystemFileUtil::CreateOrOpen, base::Unretained(file_util),
                 context, path, file_flags),
      base::Bind(&FileSystemFileUtil::Close, base::Unretained(file_util),
                 context),
      callback);
}

// static
bool FileSystemFileUtilProxy::Copy(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* src_util,
    FileSystemFileUtil* dest_util,
    const FileSystemPath& src_path,
    const FileSystemPath& dest_path,
    const StatusCallback& callback) {
  CrossFileUtilHelper* helper =
      new CrossFileUtilHelper(
          context, src_util, dest_util, src_path, dest_path,
          CrossFileUtilHelper::OPERATION_COPY);

  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      Bind(&CrossFileUtilHelper::DoWork, Owned(helper)),
      callback);
}

// static
bool FileSystemFileUtilProxy::Move(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
      FileSystemFileUtil* src_util,
      FileSystemFileUtil* dest_util,
      const FileSystemPath& src_path,
      const FileSystemPath& dest_path,
    const StatusCallback& callback) {
  CrossFileUtilHelper* helper =
      new CrossFileUtilHelper(
          context, src_util, dest_util, src_path, dest_path,
          CrossFileUtilHelper::OPERATION_MOVE);
  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      Bind(&CrossFileUtilHelper::DoWork, Owned(helper)),
      callback);
}

// static
bool FileSystemFileUtilProxy::EnsureFileExists(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    const EnsureFileExistsCallback& callback) {
  EnsureFileExistsHelper* helper = new EnsureFileExistsHelper;
  return message_loop_proxy->PostTaskAndReply(
        FROM_HERE,
        Bind(&EnsureFileExistsHelper::RunWork, Unretained(helper),
             file_util, context, path),
        Bind(&EnsureFileExistsHelper::Reply, Owned(helper), callback));
}

// static
bool FileSystemFileUtilProxy::CreateDirectory(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    bool exclusive,
    bool recursive,
    const StatusCallback& callback) {
  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      base::Bind(&FileSystemFileUtil::CreateDirectory,
                 base::Unretained(file_util),
                 context, path, exclusive, recursive),
      callback);
}

// static
bool FileSystemFileUtilProxy::GetFileInfo(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    const GetFileInfoCallback& callback) {
  GetFileInfoHelper* helper = new GetFileInfoHelper;
  return message_loop_proxy->PostTaskAndReply(
        FROM_HERE,
        Bind(&GetFileInfoHelper::RunWork, Unretained(helper),
             file_util, context, path),
        Bind(&GetFileInfoHelper::Reply, Owned(helper), callback));
}

// static
bool FileSystemFileUtilProxy::ReadDirectory(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    const ReadDirectoryCallback& callback) {
  ReadDirectoryHelper* helper = new ReadDirectoryHelper;
  return message_loop_proxy->PostTaskAndReply(
        FROM_HERE,
        Bind(&ReadDirectoryHelper::RunWork, Unretained(helper),
             file_util, context, path),
        Bind(&ReadDirectoryHelper::Reply, Owned(helper), callback));
}

// static
bool FileSystemFileUtilProxy::Touch(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    const base::Time& last_access_time,
    const base::Time& last_modified_time,
    const StatusCallback& callback) {
  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      base::Bind(&FileSystemFileUtil::Touch, base::Unretained(file_util),
                 context, path, last_access_time, last_modified_time),
      callback);
}

// static
bool FileSystemFileUtilProxy::Truncate(
    MessageLoopProxy* message_loop_proxy,
    FileSystemOperationContext* context,
    FileSystemFileUtil* file_util,
    const FileSystemPath& path,
    int64 length,
    const StatusCallback& callback) {
  return base::FileUtilProxy::RelayFileTask(
      message_loop_proxy, FROM_HERE,
      base::Bind(&FileSystemFileUtil::Truncate, base::Unretained(file_util),
                 context, path, length),
      callback);
}

}  // namespace fileapi
<|endoftext|>


<commit_before>#include "minimap_widget.h"

#include <asdf_multiplat/main/asdf_multiplat.h>
#include <glm/gtc/matrix_transform.hpp>

using namespace asdf;

minimap_widget_t::minimap_widget_t(asdf::hexmap::editor::editor_t& _edtior, QWidget *parent) :
    QOpenGLWidget(parent)
  , map_data(_edtior.map_data)
{
}

minimap_widget_t::~minimap_widget_t()
{
}

void minimap_widget_t::initializeGL()
{
    using namespace asdf;
    using namespace hexmap;

    ASSERT(app.renderer, "asdf app renderer should exist by now");

    //apparently this func gets called again when the widget is in a dock widget that gets undocked
    if(!gl_state)
    {
        void* qt_gl_context = reinterpret_cast<void*>(context());
        gl_state = std::make_unique<gl_state_t>(qt_gl_context);
        GL_State.set_current_state_machine(*(gl_state.get()));

        rendered_map = std::make_unique<ui::hex_map_t>(map_data);
        minimap = std::make_unique<ui::minimap_t>(*(rendered_map.get()));
    }
}

void minimap_widget_t::resizeGL(int w, int h){
    ASSERT(minimap, "");
    minimap->render_target.texture.write(nullptr, w, h); //resize render target texture

    auto& camera = rendered_map->camera;
    camera.set_aspect_ratio(w, h);
    camera.viewport = asdf::viewport_for_size_aspect(map_data.hex_grid.size_units(), camera.aspect_ratio);

    is_dirty = true;
}

void minimap_widget_t::paintGL(){
    //ASSERT(!CheckGLError(), "GL Error");
    CheckGLError(); //clear gl errors. I think QT is doing something stupid

    //set global GL_State proxy object to point to this context
    ASSERT(reinterpret_cast<void*>(context()) == gl_state->gl_context, "wtf? the GL context changed");
    GL_State.set_current_state_machine(*(gl_state.get()));

    //put the widget's fbo at the bottom of the stack
    auto const& t = minimap->render_target.texture;
    scoped_fbo_t scoped(defaultFramebufferObject(), 0,0, t.width, t.height);

    glDisable(GL_DEPTH_TEST);

    auto& gl_clear_color = asdf::app.renderer->gl_clear_color;
    glClearColor(gl_clear_color.r
                       , gl_clear_color.g
                       , gl_clear_color.b
                       , gl_clear_color.a);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glDisable(GL_CULL_FACE);

    if(is_dirty)
    {
        minimap->rebuild();
        is_dirty = false;
    }

    using namespace asdf;
    using namespace glm;

    //renders the prebuilt minimap texture onto a quad
    auto const& shader = app.renderer->screen_shader;
    GL_State->bind(shader);
    //asdf_renderer_t::quad_vertex_t::vertex_spec.set_vertex_attribs(shader);

    shader->world_matrix = mat4();
    shader->view_matrix = mat4();
    shader->projection_matrix = glm::ortho<float>(-0.5f, 0.5f, -0.5f, 0.5f, -1.0f, 1.0f);
    shader->update_wvp_uniform();

    //glBindTexture(GL_TEXTURE_2D, minimap->render_target.texture.texture_id);
    //GL_State->bind(app.renderer->quad.vbo);
    //glDrawArrays(GL_TRIANGLES, 0, 6);
    //GL_State->unbind_vbo();

    GL_State->unbind_shader();
    //minimap->render();
}

void minimap_widget_t::mousePressEvent(QMouseEvent*){
}

void minimap_widget_t::mouseReleaseEvent(QMouseEvent*){
}

void minimap_widget_t::mouseMoveEvent(QMouseEvent*){
}

void minimap_widget_t::wheelEvent(QWheelEvent*){
}
<commit_msg>minimap can render the quad to the screen without using app.quad vao (since its not sharable between contexts)<commit_after>#include "minimap_widget.h"

#include <asdf_multiplat/main/asdf_multiplat.h>
#include <glm/gtc/matrix_transform.hpp>

using namespace asdf;

minimap_widget_t::minimap_widget_t(asdf::hexmap::editor::editor_t& _edtior, QWidget *parent) :
    QOpenGLWidget(parent)
  , map_data(_edtior.map_data)
{
}

minimap_widget_t::~minimap_widget_t()
{
}

void minimap_widget_t::initializeGL()
{
    using namespace asdf;
    using namespace hexmap;

    ASSERT(app.renderer, "asdf app renderer should exist by now");

    //apparently this func gets called again when the widget is in a dock widget that gets undocked
    if(!gl_state)
    {
        void* qt_gl_context = reinterpret_cast<void*>(context());
        gl_state = std::make_unique<gl_state_t>(qt_gl_context);
        GL_State.set_current_state_machine(*(gl_state.get()));

        rendered_map = std::make_unique<ui::hex_map_t>(map_data);
        minimap = std::make_unique<ui::minimap_t>(*(rendered_map.get()));
    }
}

void minimap_widget_t::resizeGL(int w, int h){
    ASSERT(minimap, "");
    minimap->render_target.texture.write(nullptr, w, h); //resize render target texture

    auto& camera = rendered_map->camera;
    camera.set_aspect_ratio(w, h);
    camera.viewport = asdf::viewport_for_size_aspect(map_data.hex_grid.size_units(), camera.aspect_ratio);

    is_dirty = true;
}

void minimap_widget_t::paintGL(){
    //ASSERT(!CheckGLError(), "GL Error");
    CheckGLError(); //clear gl errors. I think QT is doing something stupid

    //set global GL_State proxy object to point to this context
    ASSERT(reinterpret_cast<void*>(context()) == gl_state->gl_context, "wtf? the GL context changed");
    GL_State.set_current_state_machine(*(gl_state.get()));

    //put the widget's fbo at the bottom of the stack
    auto const& t = minimap->render_target.texture;
    scoped_fbo_t scoped(defaultFramebufferObject(), 0,0, t.width, t.height);

    glDisable(GL_DEPTH_TEST);

    auto& gl_clear_color = asdf::app.renderer->gl_clear_color;
    glClearColor(gl_clear_color.r
                       , gl_clear_color.g
                       , gl_clear_color.b
                       , gl_clear_color.a);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glDisable(GL_CULL_FACE);

    if(is_dirty)
    {
        minimap->rebuild();
        is_dirty = false;
    }

    using namespace asdf;
    using namespace glm;

    //renders the prebuilt minimap texture onto a quad
    auto const& shader = app.renderer->screen_shader;
    GL_State->bind(shader);

    shader->world_matrix = mat4();
    shader->view_matrix = mat4();
    shader->projection_matrix = glm::ortho<float>(-0.5f, 0.5f, -0.5f, 0.5f, -1.0f, 1.0f);
    shader->update_wvp_uniform();

    glBindTexture(GL_TEXTURE_2D, minimap->render_target.texture.texture_id);
    GL_State->bind(app.renderer->quad.vbo);
    asdf_renderer_t::quad_vertex_t::vertex_spec.set_vertex_attribs(shader);
    glDrawArrays(app.renderer->quad.draw_mode, 0, app.renderer->quad.num_verts);
    GL_State->unbind_vbo();

    GL_State->unbind_shader();
}

void minimap_widget_t::mousePressEvent(QMouseEvent*){
}

void minimap_widget_t::mouseReleaseEvent(QMouseEvent*){
}

void minimap_widget_t::mouseMoveEvent(QMouseEvent*){
}

void minimap_widget_t::wheelEvent(QWheelEvent*){
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/video_coding/decoding_state.h"

#include "webrtc/base/logging.h"
#include "webrtc/common_video/h264/h264_common.h"
#include "webrtc/modules/include/module_common_types.h"
#include "webrtc/modules/video_coding/frame_buffer.h"
#include "webrtc/modules/video_coding/jitter_buffer_common.h"
#include "webrtc/modules/video_coding/packet.h"

namespace webrtc {

VCMDecodingState::VCMDecodingState()
    : sequence_num_(0),
      time_stamp_(0),
      picture_id_(kNoPictureId),
      temporal_id_(kNoTemporalIdx),
      tl0_pic_id_(kNoTl0PicIdx),
      full_sync_(true),
      in_initial_state_(true) {
  memset(frame_decoded_, 0, sizeof(frame_decoded_));
}

VCMDecodingState::~VCMDecodingState() {}

void VCMDecodingState::Reset() {
  // TODO(mikhal): Verify - not always would want to reset the sync
  sequence_num_ = 0;
  time_stamp_ = 0;
  picture_id_ = kNoPictureId;
  temporal_id_ = kNoTemporalIdx;
  tl0_pic_id_ = kNoTl0PicIdx;
  full_sync_ = true;
  in_initial_state_ = true;
  memset(frame_decoded_, 0, sizeof(frame_decoded_));
  received_sps_.clear();
  received_pps_.clear();
}

uint32_t VCMDecodingState::time_stamp() const {
  return time_stamp_;
}

uint16_t VCMDecodingState::sequence_num() const {
  return sequence_num_;
}

bool VCMDecodingState::IsOldFrame(const VCMFrameBuffer* frame) const {
  assert(frame != NULL);
  if (in_initial_state_)
    return false;
  return !IsNewerTimestamp(frame->TimeStamp(), time_stamp_);
}

bool VCMDecodingState::IsOldPacket(const VCMPacket* packet) const {
  assert(packet != NULL);
  if (in_initial_state_)
    return false;
  return !IsNewerTimestamp(packet->timestamp, time_stamp_);
}

void VCMDecodingState::SetState(const VCMFrameBuffer* frame) {
  assert(frame != NULL && frame->GetHighSeqNum() >= 0);
  if (!UsingFlexibleMode(frame))
    UpdateSyncState(frame);
  sequence_num_ = static_cast<uint16_t>(frame->GetHighSeqNum());
  time_stamp_ = frame->TimeStamp();
  picture_id_ = frame->PictureId();
  temporal_id_ = frame->TemporalId();
  tl0_pic_id_ = frame->Tl0PicId();

  for (const NaluInfo& nalu : frame->GetNaluInfos()) {
    if (nalu.type == H264::NaluType::kPps) {
      if (nalu.pps_id < 0) {
        LOG(LS_WARNING) << "Received pps without pps id.";
      } else if (nalu.sps_id < 0) {
        LOG(LS_WARNING) << "Received pps without sps id.";
      } else {
        received_pps_[nalu.pps_id] = nalu.sps_id;
      }
    } else if (nalu.type == H264::NaluType::kSps) {
      if (nalu.sps_id < 0) {
        LOG(LS_WARNING) << "Received sps without sps id.";
      } else {
        received_sps_.insert(nalu.sps_id);
      }
    }
  }

  if (UsingFlexibleMode(frame)) {
    uint16_t frame_index = picture_id_ % kFrameDecodedLength;
    if (in_initial_state_) {
      frame_decoded_cleared_to_ = frame_index;
    } else if (frame->FrameType() == kVideoFrameKey) {
      memset(frame_decoded_, 0, sizeof(frame_decoded_));
      frame_decoded_cleared_to_ = frame_index;
    } else {
      if (AheadOfFramesDecodedClearedTo(frame_index)) {
        while (frame_decoded_cleared_to_ != frame_index) {
          frame_decoded_cleared_to_ =
              (frame_decoded_cleared_to_ + 1) % kFrameDecodedLength;
          frame_decoded_[frame_decoded_cleared_to_] = false;
        }
      }
    }
    frame_decoded_[frame_index] = true;
  }

  in_initial_state_ = false;
}

void VCMDecodingState::CopyFrom(const VCMDecodingState& state) {
  sequence_num_ = state.sequence_num_;
  time_stamp_ = state.time_stamp_;
  picture_id_ = state.picture_id_;
  temporal_id_ = state.temporal_id_;
  tl0_pic_id_ = state.tl0_pic_id_;
  full_sync_ = state.full_sync_;
  in_initial_state_ = state.in_initial_state_;
  frame_decoded_cleared_to_ = state.frame_decoded_cleared_to_;
  memcpy(frame_decoded_, state.frame_decoded_, sizeof(frame_decoded_));
  received_sps_ = state.received_sps_;
  received_pps_ = state.received_pps_;
}

bool VCMDecodingState::UpdateEmptyFrame(const VCMFrameBuffer* frame) {
  bool empty_packet = frame->GetHighSeqNum() == frame->GetLowSeqNum();
  if (in_initial_state_ && empty_packet) {
    // Drop empty packets as long as we are in the initial state.
    return true;
  }
  if ((empty_packet && ContinuousSeqNum(frame->GetHighSeqNum())) ||
      ContinuousFrame(frame)) {
    // Continuous empty packets or continuous frames can be dropped if we
    // advance the sequence number.
    sequence_num_ = frame->GetHighSeqNum();
    time_stamp_ = frame->TimeStamp();
    return true;
  }
  return false;
}

void VCMDecodingState::UpdateOldPacket(const VCMPacket* packet) {
  assert(packet != NULL);
  if (packet->timestamp == time_stamp_) {
    // Late packet belonging to the last decoded frame - make sure we update the
    // last decoded sequence number.
    sequence_num_ = LatestSequenceNumber(packet->seqNum, sequence_num_);
  }
}

void VCMDecodingState::SetSeqNum(uint16_t new_seq_num) {
  sequence_num_ = new_seq_num;
}

bool VCMDecodingState::in_initial_state() const {
  return in_initial_state_;
}

bool VCMDecodingState::full_sync() const {
  return full_sync_;
}

void VCMDecodingState::UpdateSyncState(const VCMFrameBuffer* frame) {
  if (in_initial_state_)
    return;
  if (frame->TemporalId() == kNoTemporalIdx ||
      frame->Tl0PicId() == kNoTl0PicIdx) {
    full_sync_ = true;
  } else if (frame->FrameType() == kVideoFrameKey || frame->LayerSync()) {
    full_sync_ = true;
  } else if (full_sync_) {
    // Verify that we are still in sync.
    // Sync will be broken if continuity is true for layers but not for the
    // other methods (PictureId and SeqNum).
    if (UsingPictureId(frame)) {
      // First check for a valid tl0PicId.
      if (frame->Tl0PicId() - tl0_pic_id_ > 1) {
        full_sync_ = false;
      } else {
        full_sync_ = ContinuousPictureId(frame->PictureId());
      }
    } else {
      full_sync_ =
          ContinuousSeqNum(static_cast<uint16_t>(frame->GetLowSeqNum()));
    }
  }
}

bool VCMDecodingState::ContinuousFrame(const VCMFrameBuffer* frame) const {
  // Check continuity based on the following hierarchy:
  // - Temporal layers (stop here if out of sync).
  // - Picture Id when available.
  // - Sequence numbers.
  // Return true when in initial state.
  // Note that when a method is not applicable it will return false.
  assert(frame != NULL);
  // A key frame is always considered continuous as it doesn't refer to any
  // frames and therefore won't introduce any errors even if prior frames are
  // missing.
  if (frame->FrameType() == kVideoFrameKey &&
      HaveSpsAndPps(frame->GetNaluInfos())) {
    return true;
  }
  // When in the initial state we always require a key frame to start decoding.
  if (in_initial_state_)
    return false;
  if (ContinuousLayer(frame->TemporalId(), frame->Tl0PicId()))
    return true;
  // tl0picId is either not used, or should remain unchanged.
  if (frame->Tl0PicId() != tl0_pic_id_)
    return false;
  // Base layers are not continuous or temporal layers are inactive.
  // In the presence of temporal layers, check for Picture ID/sequence number
  // continuity if sync can be restored by this frame.
  if (!full_sync_ && !frame->LayerSync())
    return false;
  if (UsingPictureId(frame)) {
    if (UsingFlexibleMode(frame)) {
      return ContinuousFrameRefs(frame);
    } else {
      return ContinuousPictureId(frame->PictureId());
    }
  } else {
    return ContinuousSeqNum(static_cast<uint16_t>(frame->GetLowSeqNum())) &&
           HaveSpsAndPps(frame->GetNaluInfos());
  }
}

bool VCMDecodingState::ContinuousPictureId(int picture_id) const {
  int next_picture_id = picture_id_ + 1;
  if (picture_id < picture_id_) {
    // Wrap
    if (picture_id_ >= 0x80) {
      // 15 bits used for picture id
      return ((next_picture_id & 0x7FFF) == picture_id);
    } else {
      // 7 bits used for picture id
      return ((next_picture_id & 0x7F) == picture_id);
    }
  }
  // No wrap
  return (next_picture_id == picture_id);
}

bool VCMDecodingState::ContinuousSeqNum(uint16_t seq_num) const {
  return seq_num == static_cast<uint16_t>(sequence_num_ + 1);
}

bool VCMDecodingState::ContinuousLayer(int temporal_id, int tl0_pic_id) const {
  // First, check if applicable.
  if (temporal_id == kNoTemporalIdx || tl0_pic_id == kNoTl0PicIdx)
    return false;
  // If this is the first frame to use temporal layers, make sure we start
  // from base.
  else if (tl0_pic_id_ == kNoTl0PicIdx && temporal_id_ == kNoTemporalIdx &&
           temporal_id == 0)
    return true;

  // Current implementation: Look for base layer continuity.
  if (temporal_id != 0)
    return false;
  return (static_cast<uint8_t>(tl0_pic_id_ + 1) == tl0_pic_id);
}

bool VCMDecodingState::ContinuousFrameRefs(const VCMFrameBuffer* frame) const {
  uint8_t num_refs = frame->CodecSpecific()->codecSpecific.VP9.num_ref_pics;
  for (uint8_t r = 0; r < num_refs; ++r) {
    uint16_t frame_ref = frame->PictureId() -
                         frame->CodecSpecific()->codecSpecific.VP9.p_diff[r];
    uint16_t frame_index = frame_ref % kFrameDecodedLength;
    if (AheadOfFramesDecodedClearedTo(frame_index) ||
        !frame_decoded_[frame_index]) {
      return false;
    }
  }
  return true;
}

bool VCMDecodingState::UsingPictureId(const VCMFrameBuffer* frame) const {
  return (frame->PictureId() != kNoPictureId && picture_id_ != kNoPictureId);
}

bool VCMDecodingState::UsingFlexibleMode(const VCMFrameBuffer* frame) const {
  return frame->CodecSpecific()->codecType == kVideoCodecVP9 &&
         frame->CodecSpecific()->codecSpecific.VP9.flexible_mode;
}

// TODO(philipel): change how check work, this check practially
// limits the max p_diff to 64.
bool VCMDecodingState::AheadOfFramesDecodedClearedTo(uint16_t index) const {
  // No way of knowing for sure if we are actually ahead of
  // frame_decoded_cleared_to_. We just make the assumption
  // that we are not trying to reference back to a very old
  // index, but instead are referencing a newer index.
  uint16_t diff =
      index > frame_decoded_cleared_to_
          ? kFrameDecodedLength - (index - frame_decoded_cleared_to_)
          : frame_decoded_cleared_to_ - index;
  return diff > kFrameDecodedLength / 2;
}

bool VCMDecodingState::HaveSpsAndPps(const std::vector<NaluInfo>& nalus) const {
  std::set<int> new_sps;
  std::map<int, int> new_pps;
  for (const NaluInfo& nalu : nalus) {
    // Check if this nalu actually contains sps/pps information or dependencies.
    if (nalu.sps_id == -1 && nalu.pps_id == -1)
      continue;
    switch (nalu.type) {
      case H264::NaluType::kPps:
        if (nalu.pps_id < 0) {
          LOG(LS_WARNING) << "Received pps without pps id.";
        } else if (nalu.sps_id < 0) {
          LOG(LS_WARNING) << "Received pps without sps id.";
        } else {
          new_pps[nalu.pps_id] = nalu.sps_id;
        }
        break;
      case H264::NaluType::kSps:
        if (nalu.sps_id < 0) {
          LOG(LS_WARNING) << "Received sps without sps id.";
        } else {
          new_sps.insert(nalu.sps_id);
        }
        break;
      default: {
        int needed_sps = -1;
        auto pps_it = new_pps.find(nalu.pps_id);
        if (pps_it != new_pps.end()) {
          needed_sps = pps_it->second;
        } else {
          auto pps_it2 = received_pps_.find(nalu.pps_id);
          if (pps_it2 == received_pps_.end()) {
            return false;
          }
          needed_sps = pps_it2->second;
        }
        if (new_sps.find(needed_sps) == new_sps.end() &&
            received_sps_.find(needed_sps) == received_sps_.end()) {
          return false;
        }
        break;
      }
    }
  }
  return true;
}

}  // namespace webrtc
<commit_msg>Added sanity check to VCMDecodingState::UsingFlexibleMode to prevent OOB error.<commit_after>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/video_coding/decoding_state.h"

#include "webrtc/base/logging.h"
#include "webrtc/common_video/h264/h264_common.h"
#include "webrtc/modules/include/module_common_types.h"
#include "webrtc/modules/video_coding/frame_buffer.h"
#include "webrtc/modules/video_coding/jitter_buffer_common.h"
#include "webrtc/modules/video_coding/packet.h"

namespace webrtc {

VCMDecodingState::VCMDecodingState()
    : sequence_num_(0),
      time_stamp_(0),
      picture_id_(kNoPictureId),
      temporal_id_(kNoTemporalIdx),
      tl0_pic_id_(kNoTl0PicIdx),
      full_sync_(true),
      in_initial_state_(true) {
  memset(frame_decoded_, 0, sizeof(frame_decoded_));
}

VCMDecodingState::~VCMDecodingState() {}

void VCMDecodingState::Reset() {
  // TODO(mikhal): Verify - not always would want to reset the sync
  sequence_num_ = 0;
  time_stamp_ = 0;
  picture_id_ = kNoPictureId;
  temporal_id_ = kNoTemporalIdx;
  tl0_pic_id_ = kNoTl0PicIdx;
  full_sync_ = true;
  in_initial_state_ = true;
  memset(frame_decoded_, 0, sizeof(frame_decoded_));
  received_sps_.clear();
  received_pps_.clear();
}

uint32_t VCMDecodingState::time_stamp() const {
  return time_stamp_;
}

uint16_t VCMDecodingState::sequence_num() const {
  return sequence_num_;
}

bool VCMDecodingState::IsOldFrame(const VCMFrameBuffer* frame) const {
  assert(frame != NULL);
  if (in_initial_state_)
    return false;
  return !IsNewerTimestamp(frame->TimeStamp(), time_stamp_);
}

bool VCMDecodingState::IsOldPacket(const VCMPacket* packet) const {
  assert(packet != NULL);
  if (in_initial_state_)
    return false;
  return !IsNewerTimestamp(packet->timestamp, time_stamp_);
}

void VCMDecodingState::SetState(const VCMFrameBuffer* frame) {
  assert(frame != NULL && frame->GetHighSeqNum() >= 0);
  if (!UsingFlexibleMode(frame))
    UpdateSyncState(frame);
  sequence_num_ = static_cast<uint16_t>(frame->GetHighSeqNum());
  time_stamp_ = frame->TimeStamp();
  picture_id_ = frame->PictureId();
  temporal_id_ = frame->TemporalId();
  tl0_pic_id_ = frame->Tl0PicId();

  for (const NaluInfo& nalu : frame->GetNaluInfos()) {
    if (nalu.type == H264::NaluType::kPps) {
      if (nalu.pps_id < 0) {
        LOG(LS_WARNING) << "Received pps without pps id.";
      } else if (nalu.sps_id < 0) {
        LOG(LS_WARNING) << "Received pps without sps id.";
      } else {
        received_pps_[nalu.pps_id] = nalu.sps_id;
      }
    } else if (nalu.type == H264::NaluType::kSps) {
      if (nalu.sps_id < 0) {
        LOG(LS_WARNING) << "Received sps without sps id.";
      } else {
        received_sps_.insert(nalu.sps_id);
      }
    }
  }

  if (UsingFlexibleMode(frame)) {
    uint16_t frame_index = picture_id_ % kFrameDecodedLength;
    if (in_initial_state_) {
      frame_decoded_cleared_to_ = frame_index;
    } else if (frame->FrameType() == kVideoFrameKey) {
      memset(frame_decoded_, 0, sizeof(frame_decoded_));
      frame_decoded_cleared_to_ = frame_index;
    } else {
      if (AheadOfFramesDecodedClearedTo(frame_index)) {
        while (frame_decoded_cleared_to_ != frame_index) {
          frame_decoded_cleared_to_ =
              (frame_decoded_cleared_to_ + 1) % kFrameDecodedLength;
          frame_decoded_[frame_decoded_cleared_to_] = false;
        }
      }
    }
    frame_decoded_[frame_index] = true;
  }

  in_initial_state_ = false;
}

void VCMDecodingState::CopyFrom(const VCMDecodingState& state) {
  sequence_num_ = state.sequence_num_;
  time_stamp_ = state.time_stamp_;
  picture_id_ = state.picture_id_;
  temporal_id_ = state.temporal_id_;
  tl0_pic_id_ = state.tl0_pic_id_;
  full_sync_ = state.full_sync_;
  in_initial_state_ = state.in_initial_state_;
  frame_decoded_cleared_to_ = state.frame_decoded_cleared_to_;
  memcpy(frame_decoded_, state.frame_decoded_, sizeof(frame_decoded_));
  received_sps_ = state.received_sps_;
  received_pps_ = state.received_pps_;
}

bool VCMDecodingState::UpdateEmptyFrame(const VCMFrameBuffer* frame) {
  bool empty_packet = frame->GetHighSeqNum() == frame->GetLowSeqNum();
  if (in_initial_state_ && empty_packet) {
    // Drop empty packets as long as we are in the initial state.
    return true;
  }
  if ((empty_packet && ContinuousSeqNum(frame->GetHighSeqNum())) ||
      ContinuousFrame(frame)) {
    // Continuous empty packets or continuous frames can be dropped if we
    // advance the sequence number.
    sequence_num_ = frame->GetHighSeqNum();
    time_stamp_ = frame->TimeStamp();
    return true;
  }
  return false;
}

void VCMDecodingState::UpdateOldPacket(const VCMPacket* packet) {
  assert(packet != NULL);
  if (packet->timestamp == time_stamp_) {
    // Late packet belonging to the last decoded frame - make sure we update the
    // last decoded sequence number.
    sequence_num_ = LatestSequenceNumber(packet->seqNum, sequence_num_);
  }
}

void VCMDecodingState::SetSeqNum(uint16_t new_seq_num) {
  sequence_num_ = new_seq_num;
}

bool VCMDecodingState::in_initial_state() const {
  return in_initial_state_;
}

bool VCMDecodingState::full_sync() const {
  return full_sync_;
}

void VCMDecodingState::UpdateSyncState(const VCMFrameBuffer* frame) {
  if (in_initial_state_)
    return;
  if (frame->TemporalId() == kNoTemporalIdx ||
      frame->Tl0PicId() == kNoTl0PicIdx) {
    full_sync_ = true;
  } else if (frame->FrameType() == kVideoFrameKey || frame->LayerSync()) {
    full_sync_ = true;
  } else if (full_sync_) {
    // Verify that we are still in sync.
    // Sync will be broken if continuity is true for layers but not for the
    // other methods (PictureId and SeqNum).
    if (UsingPictureId(frame)) {
      // First check for a valid tl0PicId.
      if (frame->Tl0PicId() - tl0_pic_id_ > 1) {
        full_sync_ = false;
      } else {
        full_sync_ = ContinuousPictureId(frame->PictureId());
      }
    } else {
      full_sync_ =
          ContinuousSeqNum(static_cast<uint16_t>(frame->GetLowSeqNum()));
    }
  }
}

bool VCMDecodingState::ContinuousFrame(const VCMFrameBuffer* frame) const {
  // Check continuity based on the following hierarchy:
  // - Temporal layers (stop here if out of sync).
  // - Picture Id when available.
  // - Sequence numbers.
  // Return true when in initial state.
  // Note that when a method is not applicable it will return false.
  assert(frame != NULL);
  // A key frame is always considered continuous as it doesn't refer to any
  // frames and therefore won't introduce any errors even if prior frames are
  // missing.
  if (frame->FrameType() == kVideoFrameKey &&
      HaveSpsAndPps(frame->GetNaluInfos())) {
    return true;
  }
  // When in the initial state we always require a key frame to start decoding.
  if (in_initial_state_)
    return false;
  if (ContinuousLayer(frame->TemporalId(), frame->Tl0PicId()))
    return true;
  // tl0picId is either not used, or should remain unchanged.
  if (frame->Tl0PicId() != tl0_pic_id_)
    return false;
  // Base layers are not continuous or temporal layers are inactive.
  // In the presence of temporal layers, check for Picture ID/sequence number
  // continuity if sync can be restored by this frame.
  if (!full_sync_ && !frame->LayerSync())
    return false;
  if (UsingPictureId(frame)) {
    if (UsingFlexibleMode(frame)) {
      return ContinuousFrameRefs(frame);
    } else {
      return ContinuousPictureId(frame->PictureId());
    }
  } else {
    return ContinuousSeqNum(static_cast<uint16_t>(frame->GetLowSeqNum())) &&
           HaveSpsAndPps(frame->GetNaluInfos());
  }
}

bool VCMDecodingState::ContinuousPictureId(int picture_id) const {
  int next_picture_id = picture_id_ + 1;
  if (picture_id < picture_id_) {
    // Wrap
    if (picture_id_ >= 0x80) {
      // 15 bits used for picture id
      return ((next_picture_id & 0x7FFF) == picture_id);
    } else {
      // 7 bits used for picture id
      return ((next_picture_id & 0x7F) == picture_id);
    }
  }
  // No wrap
  return (next_picture_id == picture_id);
}

bool VCMDecodingState::ContinuousSeqNum(uint16_t seq_num) const {
  return seq_num == static_cast<uint16_t>(sequence_num_ + 1);
}

bool VCMDecodingState::ContinuousLayer(int temporal_id, int tl0_pic_id) const {
  // First, check if applicable.
  if (temporal_id == kNoTemporalIdx || tl0_pic_id == kNoTl0PicIdx)
    return false;
  // If this is the first frame to use temporal layers, make sure we start
  // from base.
  else if (tl0_pic_id_ == kNoTl0PicIdx && temporal_id_ == kNoTemporalIdx &&
           temporal_id == 0)
    return true;

  // Current implementation: Look for base layer continuity.
  if (temporal_id != 0)
    return false;
  return (static_cast<uint8_t>(tl0_pic_id_ + 1) == tl0_pic_id);
}

bool VCMDecodingState::ContinuousFrameRefs(const VCMFrameBuffer* frame) const {
  uint8_t num_refs = frame->CodecSpecific()->codecSpecific.VP9.num_ref_pics;
  for (uint8_t r = 0; r < num_refs; ++r) {
    uint16_t frame_ref = frame->PictureId() -
                         frame->CodecSpecific()->codecSpecific.VP9.p_diff[r];
    uint16_t frame_index = frame_ref % kFrameDecodedLength;
    if (AheadOfFramesDecodedClearedTo(frame_index) ||
        !frame_decoded_[frame_index]) {
      return false;
    }
  }
  return true;
}

bool VCMDecodingState::UsingPictureId(const VCMFrameBuffer* frame) const {
  return (frame->PictureId() != kNoPictureId && picture_id_ != kNoPictureId);
}

bool VCMDecodingState::UsingFlexibleMode(const VCMFrameBuffer* frame) const {
  bool is_flexible_mode =
      frame->CodecSpecific()->codecType == kVideoCodecVP9 &&
      frame->CodecSpecific()->codecSpecific.VP9.flexible_mode;
  if (is_flexible_mode && frame->PictureId() == kNoPictureId) {
    LOG(LS_WARNING) << "Frame is marked as using flexible mode but no"
                    << "picture id is set.";
    return false;
  }
  return is_flexible_mode;
}

// TODO(philipel): change how check work, this check practially
// limits the max p_diff to 64.
bool VCMDecodingState::AheadOfFramesDecodedClearedTo(uint16_t index) const {
  // No way of knowing for sure if we are actually ahead of
  // frame_decoded_cleared_to_. We just make the assumption
  // that we are not trying to reference back to a very old
  // index, but instead are referencing a newer index.
  uint16_t diff =
      index > frame_decoded_cleared_to_
          ? kFrameDecodedLength - (index - frame_decoded_cleared_to_)
          : frame_decoded_cleared_to_ - index;
  return diff > kFrameDecodedLength / 2;
}

bool VCMDecodingState::HaveSpsAndPps(const std::vector<NaluInfo>& nalus) const {
  std::set<int> new_sps;
  std::map<int, int> new_pps;
  for (const NaluInfo& nalu : nalus) {
    // Check if this nalu actually contains sps/pps information or dependencies.
    if (nalu.sps_id == -1 && nalu.pps_id == -1)
      continue;
    switch (nalu.type) {
      case H264::NaluType::kPps:
        if (nalu.pps_id < 0) {
          LOG(LS_WARNING) << "Received pps without pps id.";
        } else if (nalu.sps_id < 0) {
          LOG(LS_WARNING) << "Received pps without sps id.";
        } else {
          new_pps[nalu.pps_id] = nalu.sps_id;
        }
        break;
      case H264::NaluType::kSps:
        if (nalu.sps_id < 0) {
          LOG(LS_WARNING) << "Received sps without sps id.";
        } else {
          new_sps.insert(nalu.sps_id);
        }
        break;
      default: {
        int needed_sps = -1;
        auto pps_it = new_pps.find(nalu.pps_id);
        if (pps_it != new_pps.end()) {
          needed_sps = pps_it->second;
        } else {
          auto pps_it2 = received_pps_.find(nalu.pps_id);
          if (pps_it2 == received_pps_.end()) {
            return false;
          }
          needed_sps = pps_it2->second;
        }
        if (new_sps.find(needed_sps) == new_sps.end() &&
            received_sps_.find(needed_sps) == received_sps_.end()) {
          return false;
        }
        break;
      }
    }
  }
  return true;
}

}  // namespace webrtc
<|endoftext|>


<commit_before>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************

#include <cstdint>

#include "concat.hpp"
#include "default_opset.hpp"
#include "exceptions.hpp"
#include "ngraph/op/concat.hpp"
#include "ngraph/validation_util.hpp"

namespace ngraph
{
    namespace onnx_import
    {
        namespace op
        {
            namespace set_1
            {
                NodeVector concat(const Node& node)
                {
                    NodeVector inputs{node.get_ng_inputs()};
                    std::int64_t axis = node.get_attribute_value<std::int64_t>("axis");
                    if (axis < 0)
                    {
                        axis = ngraph::normalize_axis(
                            node.get_description(),
                            axis,
                            inputs.at(0)->get_output_partial_shape(0).rank());
                    }
                    return {std::make_shared<default_opset::Concat>(inputs, axis)};
                }

            } // namespace set_1

        } // namespace op

    } // namespace onnx_import

} // namespace ngraph
<commit_msg>Removed normalization from importer. (#4593)<commit_after>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************

#include <cstdint>

#include "concat.hpp"
#include "default_opset.hpp"
#include "exceptions.hpp"
#include "ngraph/op/concat.hpp"
#include "ngraph/validation_util.hpp"

namespace ngraph
{
    namespace onnx_import
    {
        namespace op
        {
            namespace set_1
            {
                NodeVector concat(const Node& node)
                {
                    NodeVector inputs{node.get_ng_inputs()};
                    std::int64_t axis = node.get_attribute_value<std::int64_t>("axis");
                    return {std::make_shared<default_opset::Concat>(inputs, axis)};
                }

            } // namespace set_1

        } // namespace op

    } // namespace onnx_import

} // namespace ngraph
<|endoftext|>


<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************

#include <cstring>
#include <sstream>

#include "ngraph/log.hpp"
#include "ngraph/runtime/plaidml/plaidml_config.hpp"
#include "ngraph/runtime/plaidml/plaidml_logger.hpp"

namespace v = vertexai;
namespace vp = vertexai::plaidml;

extern "C" void vai_internal_set_vlog(std::size_t num);

namespace ngraph
{
    namespace runtime
    {
        namespace plaidml
        {
            namespace
            {
                vp::device get_device(const std::shared_ptr<vertexai::ctx>& ctx,
                                      std::size_t device_idx)
                {
                    auto dev_configs = vp::enumerate_devices(ctx);
                    if (!dev_configs.size())
                    {
                        throw std::runtime_error{"Unable to find any PlaidML devices"};
                    }
                    if (dev_configs.size() <= device_idx)
                    {
                        throw std::runtime_error{"Device index out of range"};
                    }
                    return dev_configs[device_idx].open();
                }

                void list_devices(const std::shared_ptr<vertexai::ctx>& ctx)
                {
                    auto dev_configs = vp::enumerate_devices(ctx);
                    if (!dev_configs.size())
                    {
                        NGRAPH_WARN << "No PlaidML devices found";
                        return;
                    }
                    NGRAPH_INFO << "PlaidML Devices:";
                    for (std::size_t idx = 0; idx < dev_configs.size(); ++idx)
                    {
                        const auto& config = dev_configs[idx];
                        NGRAPH_INFO << "\t" << idx << ": " << config.id() << ": "
                                    << config.description();
                    }
                }
            }
        }
    }
}

ngraph::runtime::plaidml::Config
    ngraph::runtime::plaidml::parse_config_string(const std::string& configuration_string)
{
    bool err = false;
    bool help = false;
    bool list = false;
    bool debug = false;
    std::size_t device_idx = 0;
    std::string eventlog_config;
    std::string graphviz;

#ifdef NGRAPH_DEBUG_ENABLE
    debug = true;
#endif

    // To visualize what's going on here, here's a configuration string fragment:
    //
    //     ,option_name=option_value,
    //      ^          ^^           ^
    // oname_begin     ||           |
    //         oname_end|           |
    //                  oval_begin  |
    //                          oval_end
    //
    // When there is no option value, here's where the pointers go:
    //
    //     ,option_name,
    //      ^          ^
    // oname_begin     |
    //         oname_end
    //        oval_begin
    //          oval_end

    const char* c = configuration_string.c_str();
    while (*c && *c != ':')
    {
        ++c;
    }

    // Before the options, we have an optional device index.
    if (*c)
    {
        char* dev_end;
        std::size_t explicit_idx = std::strtoul(c + 1, &dev_end, 10);
        if (dev_end != c + 1)
        {
            device_idx = explicit_idx;
            c = dev_end;
        }
    }

    while (*c)
    {
        // Invariant: c points to the character introducing the current option.

        const char* oname_begin = c + 1;
        // Invariant: oname_begin points to the first character of the option name.

        const char* oname_end = oname_begin;
        while (*oname_end && *oname_end != '=' && *oname_end != ',')
        {
            ++oname_end;
        }
        // Invariant: [oname_begin, oname_end) is the option name.

        const char* oval_begin = oname_end;
        if (*oval_begin == '=')
        {
            ++oval_begin;
        }
        const char* oval_end = oval_begin;
        while (*oval_end && *oval_end != ',')
        {
            ++oval_end;
        }
        // Invariant: [oval_begin, oval_end) is the option value.

        // Re-establish initial invariant, allowing "continue" to resume the loop.
        c = oval_end;

        // Readability definitions
        auto is_opt = [=](const char* opt) {
            auto len = strlen(opt);
            return (oname_end - oname_begin == len) && !strncmp(oname_begin, opt, len);
        };

        std::size_t oval_len = oval_end - oval_begin;
        bool has_oval = oval_begin != oname_end;

        // N.B. oval_len != 0 => has_oval, but there's no other relationship.
        // So to verify that there is a non-zero-length option value, test oval_len
        // To verify that there is no option value, test has_oval

        // Check for verbosity
        if (is_opt("v"))
        {
            if (!oval_len)
            {
                throw std::invalid_argument{"PlaidML verbosity level requires a value"};
            }
            char* val_end;
            std::size_t vlog = std::strtoul(oval_begin, &val_end, 10);
            if (oval_end != val_end)
            {
                throw std::invalid_argument{"Invalid PlaidML verbosity level"};
            }
            debug = true;
            vai_internal_set_vlog(vlog);
            continue;
        }

        // Check for help
        if (is_opt("help"))
        {
            help = true;
            continue;
        }

        // Check for PlaidML debugging
        if (is_opt("debug"))
        {
            debug = true;
            continue;
        }

        // Check for list_devices
        if (is_opt("list_devices"))
        {
            if (has_oval)
            {
                throw std::invalid_argument{"PlaidML list_devices does not take a value"};
            }
            list = true;
            continue;
        }

        // Check for eventlog
        if (is_opt("eventlog"))
        {
            if (!oval_len)
            {
                throw std::invalid_argument{"PlaidML eventlog requires a value"};
            }
            std::ostringstream e;
            e << "{\"@type\": "
                 "\"type.vertex.ai/vertexai.eventing.file.proto.EventLog\", "
                 "\"filename\": \"";
            for (const char* oc = oval_begin; oc < oval_end; ++oc)
            {
                if (!isalnum(*oc))
                {
                    e << '\\';
                }
                e << *oc;
            }
            e << "\"}";
            eventlog_config = e.str();
            continue;
        }

        // Check for visualization (GraphViz output)
        if (is_opt("graphviz"))
        {
            if (!oval_len)
            {
                throw std::invalid_argument{"PlaidML graphviz requires a value"};
            }
            graphviz = std::string{oval_begin, oval_len};
            continue;
        }

        // Reject unknown options
        NGRAPH_ERR << "Unrecognized PlaidML backend option: "
                   << std::string{oname_begin, static_cast<std::size_t>(oname_end - oname_begin)};
        err = true;
    }

    constexpr char help_text[] =
        "PlaidML Backend Specification: \""
        "PlaidML[:[device_index][,debug][,help][,list_devices][,"
        "eventlog=<filename>][,graphviz=<filename>]]\".  For example: \"PlaidML\", \""
        "PlaidML:0,list_devices\"";
    if (err)
    {
        NGRAPH_ERR << help_text;
        throw std::invalid_argument{"Invalid parameter supplied to PlaidML backend"};
    }

    if (help)
    {
        NGRAPH_INFO << help_text;
    }

    // Ensure process-level logging callbacks are in place.
    configure_plaidml_logger(debug);

    // Build the PlaidML configuration.
    Config result;

    result.ctx = std::make_shared<vertexai::ctx>();
    if (eventlog_config.length())
    {
        v::vai_exception::check_and_throw(
            vai_set_eventlog(result.ctx->get_ctx(), eventlog_config.c_str()));
    }
    if (list)
    {
        list_devices(result.ctx);
    }
    result.dev = std::make_shared<vertexai::plaidml::device>(get_device(result.ctx, device_idx));

    result.debug = debug;

    result.graphviz = graphviz;

    return result;
}
<commit_msg>Accept empty PlaidML config options<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************

#include <cstring>
#include <sstream>

#include "ngraph/log.hpp"
#include "ngraph/runtime/plaidml/plaidml_config.hpp"
#include "ngraph/runtime/plaidml/plaidml_logger.hpp"

namespace v = vertexai;
namespace vp = vertexai::plaidml;

extern "C" void vai_internal_set_vlog(std::size_t num);

namespace ngraph
{
    namespace runtime
    {
        namespace plaidml
        {
            namespace
            {
                vp::device get_device(const std::shared_ptr<vertexai::ctx>& ctx,
                                      std::size_t device_idx)
                {
                    auto dev_configs = vp::enumerate_devices(ctx);
                    if (!dev_configs.size())
                    {
                        throw std::runtime_error{"Unable to find any PlaidML devices"};
                    }
                    if (dev_configs.size() <= device_idx)
                    {
                        throw std::runtime_error{"Device index out of range"};
                    }
                    return dev_configs[device_idx].open();
                }

                void list_devices(const std::shared_ptr<vertexai::ctx>& ctx)
                {
                    auto dev_configs = vp::enumerate_devices(ctx);
                    if (!dev_configs.size())
                    {
                        NGRAPH_WARN << "No PlaidML devices found";
                        return;
                    }
                    NGRAPH_INFO << "PlaidML Devices:";
                    for (std::size_t idx = 0; idx < dev_configs.size(); ++idx)
                    {
                        const auto& config = dev_configs[idx];
                        NGRAPH_INFO << "\t" << idx << ": " << config.id() << ": "
                                    << config.description();
                    }
                }
            }
        }
    }
}

ngraph::runtime::plaidml::Config
    ngraph::runtime::plaidml::parse_config_string(const std::string& configuration_string)
{
    bool err = false;
    bool help = false;
    bool list = false;
    bool debug = false;
    std::size_t device_idx = 0;
    std::string eventlog_config;
    std::string graphviz;

#ifdef NGRAPH_DEBUG_ENABLE
    debug = true;
#endif

    // To visualize what's going on here, here's a configuration string fragment:
    //
    //     ,option_name=option_value,
    //      ^          ^^           ^
    // oname_begin     ||           |
    //         oname_end|           |
    //                  oval_begin  |
    //                          oval_end
    //
    // When there is no option value, here's where the pointers go:
    //
    //     ,option_name,
    //      ^          ^
    // oname_begin     |
    //         oname_end
    //        oval_begin
    //          oval_end

    const char* c = configuration_string.c_str();
    while (*c && *c != ':')
    {
        ++c;
    }

    // Before the options, we have an optional device index.
    if (*c)
    {
        char* dev_end;
        std::size_t explicit_idx = std::strtoul(c + 1, &dev_end, 10);
        if (dev_end != c + 1)
        {
            device_idx = explicit_idx;
            c = dev_end;
        }
    }

    while (*c)
    {
        // Invariant: c points to the character introducing the current option.

        const char* oname_begin = c + 1;
        // Invariant: oname_begin points to the first character of the option name.

        const char* oname_end = oname_begin;
        while (*oname_end && *oname_end != '=' && *oname_end != ',')
        {
            ++oname_end;
        }
        // Invariant: [oname_begin, oname_end) is the option name.

        const char* oval_begin = oname_end;
        if (*oval_begin == '=')
        {
            ++oval_begin;
        }
        const char* oval_end = oval_begin;
        while (*oval_end && *oval_end != ',')
        {
            ++oval_end;
        }
        // Invariant: [oval_begin, oval_end) is the option value.

        // Re-establish initial invariant, allowing "continue" to resume the loop.
        c = oval_end;

        // Readability definitions
        auto is_opt = [=](const char* opt) {
            auto len = strlen(opt);
            return (oname_end - oname_begin == len) && !strncmp(oname_begin, opt, len);
        };

        std::size_t oval_len = oval_end - oval_begin;
        bool has_oval = oval_begin != oname_end;

        // N.B. oval_len != 0 => has_oval, but there's no other relationship.
        // So to verify that there is a non-zero-length option value, test oval_len
        // To verify that there is no option value, test has_oval

        if (oname_begin == oname_end && !has_oval) {
          // An empty option; poor style, but advance to the next.
          continue;
        }

        // Check for verbosity
        if (is_opt("v"))
        {
            if (!oval_len)
            {
                throw std::invalid_argument{"PlaidML verbosity level requires a value"};
            }
            char* val_end;
            std::size_t vlog = std::strtoul(oval_begin, &val_end, 10);
            if (oval_end != val_end)
            {
                throw std::invalid_argument{"Invalid PlaidML verbosity level"};
            }
            debug = true;
            vai_internal_set_vlog(vlog);
            continue;
        }

        // Check for help
        if (is_opt("help"))
        {
            help = true;
            continue;
        }

        // Check for PlaidML debugging
        if (is_opt("debug"))
        {
            debug = true;
            continue;
        }

        // Check for list_devices
        if (is_opt("list_devices"))
        {
            if (has_oval)
            {
                throw std::invalid_argument{"PlaidML list_devices does not take a value"};
            }
            list = true;
            continue;
        }

        // Check for eventlog
        if (is_opt("eventlog"))
        {
            if (!oval_len)
            {
                throw std::invalid_argument{"PlaidML eventlog requires a value"};
            }
            std::ostringstream e;
            e << "{\"@type\": "
                 "\"type.vertex.ai/vertexai.eventing.file.proto.EventLog\", "
                 "\"filename\": \"";
            for (const char* oc = oval_begin; oc < oval_end; ++oc)
            {
                if (!isalnum(*oc))
                {
                    e << '\\';
                }
                e << *oc;
            }
            e << "\"}";
            eventlog_config = e.str();
            continue;
        }

        // Check for visualization (GraphViz output)
        if (is_opt("graphviz"))
        {
            if (!oval_len)
            {
                throw std::invalid_argument{"PlaidML graphviz requires a value"};
            }
            graphviz = std::string{oval_begin, oval_len};
            continue;
        }

        // Reject unknown options
        NGRAPH_ERR << "Unrecognized PlaidML backend option: "
                   << std::string{oname_begin, static_cast<std::size_t>(oname_end - oname_begin)};
        err = true;
    }

    constexpr char help_text[] =
        "PlaidML Backend Specification: \""
        "PlaidML[:[device_index][,debug][,help][,list_devices][,"
        "eventlog=<filename>][,graphviz=<filename>]]\".  For example: \"PlaidML\", \""
        "PlaidML:0,list_devices\"";
    if (err)
    {
        NGRAPH_ERR << help_text;
        throw std::invalid_argument{"Invalid parameter supplied to PlaidML backend"};
    }

    if (help)
    {
        NGRAPH_INFO << help_text;
    }

    // Ensure process-level logging callbacks are in place.
    configure_plaidml_logger(debug);

    // Build the PlaidML configuration.
    Config result;

    result.ctx = std::make_shared<vertexai::ctx>();
    if (eventlog_config.length())
    {
        v::vai_exception::check_and_throw(
            vai_set_eventlog(result.ctx->get_ctx(), eventlog_config.c_str()));
    }
    if (list)
    {
        list_devices(result.ctx);
    }
    result.dev = std::make_shared<vertexai::plaidml::device>(get_device(result.ctx, device_idx));

    result.debug = debug;

    result.graphviz = graphviz;

    return result;
}
<|endoftext|>


<commit_before>#ifndef SILICIUM_EXPECTED_HPP
#define SILICIUM_EXPECTED_HPP

#include <silicium/variant.hpp> //for inplace
#include <boost/type_traits/alignment_of.hpp>
#include <type_traits>

#define SILICIUM_HAS_EXPECTED SILICIUM_HAS_EXCEPTIONS

#if SILICIUM_HAS_EXPECTED
#include <boost/exception_ptr.hpp>
namespace Si
{
	template <class T, class ExceptionPtr = boost::exception_ptr>
	struct expected
	{
		typedef T value_type;
		typedef ExceptionPtr exception_ptr;

		expected()
			: m_state(has_value)
		{
			new (&value_address()) value_type();
		}

		expected(T &&value)
			: m_state(has_value)
		{
			new (&value_address()) value_type(std::move(value));
		}

		expected(T const &value)
			: m_state(has_value)
		{
			new (&value_address()) value_type(value);
		}

#if SILICIUM_COMPILER_HAS_VARIADIC_TEMPLATES
		template <class ...Args>
		explicit expected(Args &&...args)
			: m_state(has_value)
		{
			new (&value_address()) value_type(std::forward<Args>(args)...);
		}
#else
		template <class A0, class A1>
		expected(A0 &&a0, A1 &&a1)
			: m_state(has_value)
		{
			new (&value_address()) value_type(std::forward<A0>(a0), std::forward<A1>(a1));
		}
#endif

		expected(exception_ptr exception)
			: m_state(has_exception)
		{
			new (&exception_address()) exception_ptr(std::move(exception));
		}

		expected(expected &&other)
			: m_state(other.m_state)
		{
			switch (m_state)
			{
			case has_value:
				new (&value_address()) value_type(std::move(other.value_address()));
				break;

			case has_exception:
				new (&exception_address()) exception_ptr(std::move(other.exception_address()));
				break;
			}
		}

		expected(expected const &other)
			: m_state(other.m_state)
		{
			switch (m_state)
			{
			case has_value:
				new (&value_address()) value_type(other.value_address());
				break;

			case has_exception:
				new (&exception_address()) exception_ptr(other.exception_address());
				break;
			}
		}

		expected &operator = (T &&value)
		{
			switch (m_state)
			{
			case has_value:
				value_address() = std::move(value);
				break;

			case has_exception:
				exception_address().~exception_ptr();
				new (&value_address()) value_type(std::move(value));
				m_state = has_value;
				break;
			}
			return *this;
		}

		expected &operator = (T const &value)
		{
			switch (m_state)
			{
			case has_value:
				value_address() = value;
				break;

			case has_exception:
				{
					value_type copy(value);
					exception_address().~exception_ptr();
					new (&value_address()) value_type(std::move(copy));
					m_value = has_value;
					break;
				}
			}
			return *this;
		}

		expected &operator = (expected &&other)
		{
			switch (m_state)
			{
			case has_value:
				switch (other.m_state)
				{
				case has_value:
					value_address() = std::move(other.value_address());
					break;

				case has_exception:
					value_address().~value_type();
					new (&exception_address()) exception_ptr(std::move(other.exception_address()));
					break;
				}
				break;

			case has_exception:
				switch (other.m_state)
				{
				case has_value:
					exception_address().~exception_ptr();
					new (&value_address()) value_type(std::move(other.value_address()));
					break;

				case has_exception:
					exception_address() = std::move(other.exception_address());
					break;
				}
				break;
			}
			m_state = other.m_state;
			return *this;
		}

		expected &operator = (expected const &other)
		{
			switch (m_state)
			{
			case has_value:
				switch (other.m_state)
				{
				case has_value:
					value_address() = other.value_address();
					break;

				case has_exception:
					value_address().~value_type();
					new (&exception_address()) exception_ptr(other.exception_address());
					break;
				}
				break;

			case has_exception:
				switch (other.m_state)
				{
				case has_value:
					exception_address().~exception_ptr();
					new (&value_address()) value_type(other.value_address());
					break;

				case has_exception:
					exception_address() = other.exception_address();
					break;
				}
				break;
			}
			m_state = other.m_state;
			return *this;
		}

		T &value()
#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
			&
#endif
		{
			switch (m_state)
			{
			case has_value:
				return value_address();

			case has_exception:
				rethrow_exception(exception_address());
			}
			SILICIUM_UNREACHABLE();
		}

		T const &value() const
#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
			&
#endif
		{
			switch (m_state)
			{
			case has_value:
				return value_address();

			case has_exception:
				rethrow_exception(exception_address());
			}
			SILICIUM_UNREACHABLE();
		}

#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
		T &&value() &&
		{
			switch (m_state)
			{
			case has_value:
				return std::move(value_address());

			case has_exception:
				rethrow_exception(exception_address());
			}
			SILICIUM_UNREACHABLE();
		}
#endif

#if SILICIUM_COMPILER_HAS_VARIADIC_TEMPLATES
		template <class ...Args>
		void emplace(Args &&...args)
		{
			switch (m_state)
			{
			case has_value:
				value_address().~value_type();
				break;

			case has_exception:
				exception_address().~exception_ptr();
				break;
			}
			new (&value_address()) value_type(std::forward<Args>(args)...);
		}
#else
		void emplace()
		{
			switch (m_state)
			{
			case has_value:
				value_address().~value_type();
				break;

			case has_exception:
				exception_address().~exception_ptr();
				break;
			}
			new (&value_address()) value_type();
		}

		template <class A0>
		void emplace(A0 &&a0)
		{
			switch (m_state)
			{
			case has_value:
				value_address().~value_type();
				break;

			case has_exception:
				exception_address().~exception_ptr();
				break;
			}
			new (&value_address()) value_type(std::forward<A0>(a0));
		}

		template <class A0, class A1>
		void emplace(A0 &&a0, A1 &&a1)
		{
			switch (m_state)
			{
			case has_value:
				value_address().~value_type();
				break;

			case has_exception:
				exception_address().~exception_ptr();
				break;
			}
			new (&value_address()) value_type(std::forward<A0>(a0), std::forward<A1>(a1));
		}
#endif

		bool valid() const BOOST_NOEXCEPT
		{
			switch (m_state)
			{
			case has_value: return true;
			case has_exception: return false;
			}
			SILICIUM_UNREACHABLE();
		}

	private:

		enum state
		{
			has_value,
			has_exception
		};

		union
		{
			typename std::aligned_storage<sizeof(T), boost::alignment_of<T>::value>::type m_value;
			typename std::aligned_storage<sizeof(exception_ptr), boost::alignment_of<exception_ptr>::value>::type m_exception;
		};
		state m_state;

		T &value_address()
		{
			return *reinterpret_cast<T *>(&m_value);
		}

		T const &value_address() const
		{
			return *reinterpret_cast<T const *>(&m_value);
		}

		exception_ptr &exception_address()
		{
			return *reinterpret_cast<exception_ptr *>(&m_exception);
		}

		exception_ptr const &exception_address() const
		{
			return *reinterpret_cast<exception_ptr const *>(&m_exception);
		}
	};

	BOOST_STATIC_ASSERT(sizeof(expected<void *>) <= (sizeof(boost::exception_ptr) + sizeof(void *)));
}
#endif

#endif
<commit_msg>this time I forgot the destructor of expected<commit_after>#ifndef SILICIUM_EXPECTED_HPP
#define SILICIUM_EXPECTED_HPP

#include <silicium/variant.hpp> //for inplace
#include <boost/type_traits/alignment_of.hpp>
#include <type_traits>

#define SILICIUM_HAS_EXPECTED SILICIUM_HAS_EXCEPTIONS

#if SILICIUM_HAS_EXPECTED
#include <boost/exception_ptr.hpp>
namespace Si
{
	template <class T, class ExceptionPtr = boost::exception_ptr>
	struct expected
	{
		typedef T value_type;
		typedef ExceptionPtr exception_ptr;

		expected()
			: m_state(has_value)
		{
			new (&value_address()) value_type();
		}

		expected(T &&value)
			: m_state(has_value)
		{
			new (&value_address()) value_type(std::move(value));
		}

		expected(T const &value)
			: m_state(has_value)
		{
			new (&value_address()) value_type(value);
		}

#if SILICIUM_COMPILER_HAS_VARIADIC_TEMPLATES
		template <class ...Args>
		explicit expected(Args &&...args)
			: m_state(has_value)
		{
			new (&value_address()) value_type(std::forward<Args>(args)...);
		}
#else
		template <class A0, class A1>
		expected(A0 &&a0, A1 &&a1)
			: m_state(has_value)
		{
			new (&value_address()) value_type(std::forward<A0>(a0), std::forward<A1>(a1));
		}
#endif

		expected(exception_ptr exception)
			: m_state(has_exception)
		{
			new (&exception_address()) exception_ptr(std::move(exception));
		}

		expected(expected &&other)
			: m_state(other.m_state)
		{
			switch (m_state)
			{
			case has_value:
				new (&value_address()) value_type(std::move(other.value_address()));
				break;

			case has_exception:
				new (&exception_address()) exception_ptr(std::move(other.exception_address()));
				break;
			}
		}

		expected(expected const &other)
			: m_state(other.m_state)
		{
			switch (m_state)
			{
			case has_value:
				new (&value_address()) value_type(other.value_address());
				break;

			case has_exception:
				new (&exception_address()) exception_ptr(other.exception_address());
				break;
			}
		}

		expected &operator = (T &&value)
		{
			switch (m_state)
			{
			case has_value:
				value_address() = std::move(value);
				break;

			case has_exception:
				exception_address().~exception_ptr();
				new (&value_address()) value_type(std::move(value));
				m_state = has_value;
				break;
			}
			return *this;
		}

		expected &operator = (T const &value)
		{
			switch (m_state)
			{
			case has_value:
				value_address() = value;
				break;

			case has_exception:
				{
					value_type copy(value);
					exception_address().~exception_ptr();
					new (&value_address()) value_type(std::move(copy));
					m_value = has_value;
					break;
				}
			}
			return *this;
		}

		expected &operator = (expected &&other)
		{
			switch (m_state)
			{
			case has_value:
				switch (other.m_state)
				{
				case has_value:
					value_address() = std::move(other.value_address());
					break;

				case has_exception:
					value_address().~value_type();
					new (&exception_address()) exception_ptr(std::move(other.exception_address()));
					break;
				}
				break;

			case has_exception:
				switch (other.m_state)
				{
				case has_value:
					exception_address().~exception_ptr();
					new (&value_address()) value_type(std::move(other.value_address()));
					break;

				case has_exception:
					exception_address() = std::move(other.exception_address());
					break;
				}
				break;
			}
			m_state = other.m_state;
			return *this;
		}

		expected &operator = (expected const &other)
		{
			switch (m_state)
			{
			case has_value:
				switch (other.m_state)
				{
				case has_value:
					value_address() = other.value_address();
					break;

				case has_exception:
					value_address().~value_type();
					new (&exception_address()) exception_ptr(other.exception_address());
					break;
				}
				break;

			case has_exception:
				switch (other.m_state)
				{
				case has_value:
					exception_address().~exception_ptr();
					new (&value_address()) value_type(other.value_address());
					break;

				case has_exception:
					exception_address() = other.exception_address();
					break;
				}
				break;
			}
			m_state = other.m_state;
			return *this;
		}

		~expected()
		{
			switch (m_state)
			{
			case has_value:
				value_address().~value_type();
				break;

			case has_exception:
				exception_address().~exception_ptr();
				break;
			}
		}

		T &value()
#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
			&
#endif
		{
			switch (m_state)
			{
			case has_value:
				return value_address();

			case has_exception:
				rethrow_exception(exception_address());
			}
			SILICIUM_UNREACHABLE();
		}

		T const &value() const
#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
			&
#endif
		{
			switch (m_state)
			{
			case has_value:
				return value_address();

			case has_exception:
				rethrow_exception(exception_address());
			}
			SILICIUM_UNREACHABLE();
		}

#if SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER
		T &&value() &&
		{
			switch (m_state)
			{
			case has_value:
				return std::move(value_address());

			case has_exception:
				rethrow_exception(exception_address());
			}
			SILICIUM_UNREACHABLE();
		}
#endif

#if SILICIUM_COMPILER_HAS_VARIADIC_TEMPLATES
		template <class ...Args>
		void emplace(Args &&...args)
		{
			switch (m_state)
			{
			case has_value:
				value_address().~value_type();
				break;

			case has_exception:
				exception_address().~exception_ptr();
				break;
			}
			new (&value_address()) value_type(std::forward<Args>(args)...);
		}
#else
		void emplace()
		{
			switch (m_state)
			{
			case has_value:
				value_address().~value_type();
				break;

			case has_exception:
				exception_address().~exception_ptr();
				break;
			}
			new (&value_address()) value_type();
		}

		template <class A0>
		void emplace(A0 &&a0)
		{
			switch (m_state)
			{
			case has_value:
				value_address().~value_type();
				break;

			case has_exception:
				exception_address().~exception_ptr();
				break;
			}
			new (&value_address()) value_type(std::forward<A0>(a0));
		}

		template <class A0, class A1>
		void emplace(A0 &&a0, A1 &&a1)
		{
			switch (m_state)
			{
			case has_value:
				value_address().~value_type();
				break;

			case has_exception:
				exception_address().~exception_ptr();
				break;
			}
			new (&value_address()) value_type(std::forward<A0>(a0), std::forward<A1>(a1));
		}
#endif

		bool valid() const BOOST_NOEXCEPT
		{
			switch (m_state)
			{
			case has_value: return true;
			case has_exception: return false;
			}
			SILICIUM_UNREACHABLE();
		}

	private:

		enum state
		{
			has_value,
			has_exception
		};

		union
		{
			typename std::aligned_storage<sizeof(T), boost::alignment_of<T>::value>::type m_value;
			typename std::aligned_storage<sizeof(exception_ptr), boost::alignment_of<exception_ptr>::value>::type m_exception;
		};
		state m_state;

		T &value_address()
		{
			return *reinterpret_cast<T *>(&m_value);
		}

		T const &value_address() const
		{
			return *reinterpret_cast<T const *>(&m_value);
		}

		exception_ptr &exception_address()
		{
			return *reinterpret_cast<exception_ptr *>(&m_exception);
		}

		exception_ptr const &exception_address() const
		{
			return *reinterpret_cast<exception_ptr const *>(&m_exception);
		}
	};

	BOOST_STATIC_ASSERT(sizeof(expected<void *>) <= (sizeof(boost::exception_ptr) + sizeof(void *)));
}
#endif

#endif
<|endoftext|>


<commit_before>#ifndef CAFFE_MOLGRID_DATA_LAYER_HPP_
#define CAFFE_MOLGRID_DATA_LAYER_HPP_

#include <string>
#include <utility>
#include <vector>

#include <boost/array.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/unordered_map.hpp>
#include <boost/math/quaternion.hpp>
#include <boost/multi_array/multi_array_ref.hpp>
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/proto/caffe.pb.h"

#include "/home/mtr22/gnina/src/lib/atom_constants.h"
#include "/home/mtr22/gnina/src/lib/gridmaker.h"

namespace caffe {

/**
 * @brief Provides data to the Net from n-dimension  files of raw floating point data.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class MolGridDataLayer : public BaseDataLayer<Dtype> {
 public:
  explicit MolGridDataLayer(const LayerParameter& param)
      : BaseDataLayer<Dtype>(param), actives_pos_(0),
        decoys_pos_(0), all_pos_(0), num_rotations(0), current_rotation(0),
        example_size(0),balanced(false),inmem(false),
				resolution(0.5), dimension(23.5), radiusmultiple(1.5), randtranslate(0),
				binary(false), randrotate(false), dim(0), numgridpoints(0),
				numReceptorTypes(0),numLigandTypes(0), gpu_alloc_size(0),
				gpu_gridatoms(NULL), gpu_gridwhich(NULL) {}
  virtual ~MolGridDataLayer();
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  virtual inline const char* type() const { return "MolGridData"; }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

  virtual inline void resetRotation() { current_rotation = 0; }

  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);

  //set in memory buffer
  template<typename Atom>
  void setReceptor(const vector<Atom>& receptor)
  {
    //make this a template mostly so I don't have to pull in gnina atom class
    mem_rec.atoms.clear();
    mem_rec.whichGrid.clear();

    //receptor atoms
    for(unsigned i = 0, n = receptor.size(); i < n; i++)
    {
      const Atom& a = receptor[i];
      smt t = a.sm;
      float4 ainfo;
      ainfo.x = a.coords[0];
      ainfo.y = a.coords[1];
      ainfo.z = a.coords[2];
      ainfo.w = xs_radius(t);
      mem_rec.atoms.push_back(ainfo);
      mem_rec.whichGrid.push_back(rmap[t]);
    }
  }

  //set in memory buffer
  template<typename Atom, typename Vec3>
  void setLigand(const vector<Atom>& ligand, const vector<Vec3>& coords)
  {
    mem_lig.atoms.clear();
    mem_lig.whichGrid.clear();
    //ligand atoms, grid positions offset and coordinates are specified separately
    vec center(0,0,0);
    unsigned acnt = 0;
    for(unsigned i = 0, n = ligand.size(); i < n; i++)
    {
      smt t = ligand[i].sm;
      if(lmap[t] >= 0)
      {
        const Vec3& coord = coords[i];
        float4 ainfo;
        ainfo.x = coord[0];
        ainfo.y = coord[1];
        ainfo.z = coord[2];
        ainfo.w = xs_radius(t);
        mem_lig.atoms.push_back(ainfo);
        mem_lig.whichGrid.push_back(lmap[t]+numReceptorTypes);
        center += coord;
        acnt++;
      }
    }
    center /= acnt; //not ligand.size() because of hydrogens

    mem_lig.center = center;
  }

 protected:

  typedef GridMaker::quaternion quaternion;
  typedef typename boost::multi_array_ref<Dtype, 4>  Grids;

  struct example
	{
  	string receptor;
  	string ligand;
  	Dtype label;

  	example(): label(0) {}
  	example(Dtype l, const string& r, const string& lig): receptor(r), ligand(lig), label(l) {}
	};

  virtual void Shuffle();

  vector<example> actives_;
  vector<example> decoys_;
  vector<example> all_;
  string root_folder;
  int actives_pos_, decoys_pos_, all_pos_;
  unsigned num_rotations;
  unsigned current_rotation;
  unsigned example_size; //channels*numgridpoints
  vector<int> top_shape;
  bool balanced;
  bool inmem;
  vector<Dtype> labels;

  //grid stuff
  GridMaker gmaker;
  double resolution;
  double dimension;
  double radiusmultiple; //extra to consider past vdw radius
  double randtranslate;
  bool binary; //produce binary occupancies
  bool randrotate;

  unsigned dim; //grid points on one side
  unsigned numgridpoints; //dim*dim*dim

  vector<int> rmap; //map atom types to position in grid vectors
  vector<int> lmap;
  unsigned numReceptorTypes;
  unsigned numLigandTypes;

  unsigned gpu_alloc_size;
  float4 *gpu_gridatoms;
  short *gpu_gridwhich;

  void allocateGPUMem(unsigned sz);

  struct mol_info {
    vector<float4> atoms;
    vector<float3> gradient;
    vector<short> whichGrid; //separate for better memory layout on gpu
    vec center; //precalculate centroid, includes any random translation
    boost::array< pair<float, float>, 3> dims;

    mol_info() { center[0] = center[1] = center[2] = 0;}

    void append(const mol_info& a)
    {
      atoms.insert(atoms.end(), a.atoms.begin(), a.atoms.end());
      whichGrid.insert(whichGrid.end(), a.whichGrid.begin(), a.whichGrid.end());
      gradient.insert(gradient.end(), a.gradient.begin(), a.gradient.end());
    }
  };

  struct mol_transform {
    mol_info mol;
    quaternion Q;  // rotation
    vec center; // translation

    mol_transform() {
      mol = mol_info();
      Q = quaternion(0,0,0,0);
      center[0] = center[1] = center[2] = 0;
    }
  };

  //need to remember how mols were transformed for backward pass
  vector<mol_transform> batch_transform;

  boost::unordered_map<string, mol_info> molcache;
  mol_info mem_rec; //molecular data set programmatically with setMemory
  mol_info mem_lig; //molecular data set programmatically with setMemory

  quaternion axial_quaternion();
  void set_mol_info(const string& file, const vector<int>& atommap, unsigned atomoffset, mol_info& minfo);
  void set_grid_ex(Dtype *grid, const example& ex, mol_transform& transform, bool gpu);
  void set_grid_minfo(Dtype *grid, const mol_info& recatoms, const mol_info& ligatoms, mol_transform& transform, bool gpu);

  void forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top, bool gpu);
  void backward(const vector<Blob<Dtype>*>& top, const vector<Blob<Dtype>*>& bottom, bool gpu);
};

}  // namespace caffe

#endif  // CAFFE_MOLGRID_DATA_LAYER_HPP_
<commit_msg>zero init gradient in setReceptor and setLigand<commit_after>#ifndef CAFFE_MOLGRID_DATA_LAYER_HPP_
#define CAFFE_MOLGRID_DATA_LAYER_HPP_

#include <string>
#include <utility>
#include <vector>

#include <boost/array.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/unordered_map.hpp>
#include <boost/math/quaternion.hpp>
#include <boost/multi_array/multi_array_ref.hpp>
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/proto/caffe.pb.h"

#include "/home/mtr22/gnina/src/lib/atom_constants.h"
#include "/home/mtr22/gnina/src/lib/gridmaker.h"

namespace caffe {

/**
 * @brief Provides data to the Net from n-dimension  files of raw floating point data.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class MolGridDataLayer : public BaseDataLayer<Dtype> {
 public:
  explicit MolGridDataLayer(const LayerParameter& param)
      : BaseDataLayer<Dtype>(param), actives_pos_(0),
        decoys_pos_(0), all_pos_(0), num_rotations(0), current_rotation(0),
        example_size(0),balanced(false),inmem(false),
				resolution(0.5), dimension(23.5), radiusmultiple(1.5), randtranslate(0),
				binary(false), randrotate(false), dim(0), numgridpoints(0),
				numReceptorTypes(0),numLigandTypes(0), gpu_alloc_size(0),
				gpu_gridatoms(NULL), gpu_gridwhich(NULL) {}
  virtual ~MolGridDataLayer();
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  virtual inline const char* type() const { return "MolGridData"; }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

  virtual inline void resetRotation() { current_rotation = 0; }

  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);

  //set in memory buffer
  template<typename Atom>
  void setReceptor(const vector<Atom>& receptor)
  {
    //make this a template mostly so I don't have to pull in gnina atom class
    mem_rec.atoms.clear();
    mem_rec.whichGrid.clear();
    mem_rec.gradient.clear();

    //receptor atoms
    for(unsigned i = 0, n = receptor.size(); i < n; i++)
    {
      const Atom& a = receptor[i];
      smt t = a.sm;
      float4 ainfo;
      ainfo.x = a.coords[0];
      ainfo.y = a.coords[1];
      ainfo.z = a.coords[2];
      ainfo.w = xs_radius(t);
      float3 gradient;
      gradient.x = 0.0;
      gradient.y = 0.0;
      gradient.z = 0.0;
      mem_rec.atoms.push_back(ainfo);
      mem_rec.whichGrid.push_back(rmap[t]);
      mem_rec.gradient.push_back(gradient);
    }
  }

  //set in memory buffer
  template<typename Atom, typename Vec3>
  void setLigand(const vector<Atom>& ligand, const vector<Vec3>& coords)
  {
    mem_lig.atoms.clear();
    mem_lig.whichGrid.clear();
    mem_lig.gradient.clear();

    //ligand atoms, grid positions offset and coordinates are specified separately
    vec center(0,0,0);
    unsigned acnt = 0;
    for(unsigned i = 0, n = ligand.size(); i < n; i++)
    {
      smt t = ligand[i].sm;
      if(lmap[t] >= 0)
      {
        const Vec3& coord = coords[i];
        float4 ainfo;
        ainfo.x = coord[0];
        ainfo.y = coord[1];
        ainfo.z = coord[2];
        ainfo.w = xs_radius(t);
        float3 gradient;
        gradient.x = 0.0;
        gradient.y = 0.0;
        gradient.z = 0.0;
        mem_lig.atoms.push_back(ainfo);
        mem_lig.whichGrid.push_back(lmap[t]+numReceptorTypes);
        mem_lig.gradient.push_back(gradient);
        center += coord;
        acnt++;
      }
    }
    center /= acnt; //not ligand.size() because of hydrogens

    mem_lig.center = center;
  }

 protected:

  typedef GridMaker::quaternion quaternion;
  typedef typename boost::multi_array_ref<Dtype, 4>  Grids;

  struct example
	{
  	string receptor;
  	string ligand;
  	Dtype label;

  	example(): label(0) {}
  	example(Dtype l, const string& r, const string& lig): receptor(r), ligand(lig), label(l) {}
	};

  virtual void Shuffle();

  vector<example> actives_;
  vector<example> decoys_;
  vector<example> all_;
  string root_folder;
  int actives_pos_, decoys_pos_, all_pos_;
  unsigned num_rotations;
  unsigned current_rotation;
  unsigned example_size; //channels*numgridpoints
  vector<int> top_shape;
  bool balanced;
  bool inmem;
  vector<Dtype> labels;

  //grid stuff
  GridMaker gmaker;
  double resolution;
  double dimension;
  double radiusmultiple; //extra to consider past vdw radius
  double randtranslate;
  bool binary; //produce binary occupancies
  bool randrotate;

  unsigned dim; //grid points on one side
  unsigned numgridpoints; //dim*dim*dim

  vector<int> rmap; //map atom types to position in grid vectors
  vector<int> lmap;
  unsigned numReceptorTypes;
  unsigned numLigandTypes;

  unsigned gpu_alloc_size;
  float4 *gpu_gridatoms;
  short *gpu_gridwhich;

  void allocateGPUMem(unsigned sz);

  struct mol_info {
    vector<float4> atoms;
    vector<short> whichGrid; //separate for better memory layout on gpu
    vector<float3> gradient;
    vec center; //precalculate centroid, includes any random translation
    boost::array< pair<float, float>, 3> dims;

    mol_info() { center[0] = center[1] = center[2] = 0;}

    void append(const mol_info& a)
    {
      atoms.insert(atoms.end(), a.atoms.begin(), a.atoms.end());
      whichGrid.insert(whichGrid.end(), a.whichGrid.begin(), a.whichGrid.end());
      gradient.insert(gradient.end(), a.gradient.begin(), a.gradient.end());
    }
  };

  struct mol_transform {
    mol_info mol;
    quaternion Q;  // rotation
    vec center; // translation

    mol_transform() {
      mol = mol_info();
      Q = quaternion(0,0,0,0);
      center[0] = center[1] = center[2] = 0;
    }
  };

  //need to remember how mols were transformed for backward pass
  vector<mol_transform> batch_transform;

  boost::unordered_map<string, mol_info> molcache;
  mol_info mem_rec; //molecular data set programmatically with setReceptor
  mol_info mem_lig; //molecular data set programmatically with setLigand

  quaternion axial_quaternion();
  void set_mol_info(const string& file, const vector<int>& atommap, unsigned atomoffset, mol_info& minfo);
  void set_grid_ex(Dtype *grid, const example& ex, mol_transform& transform, bool gpu);
  void set_grid_minfo(Dtype *grid, const mol_info& recatoms, const mol_info& ligatoms, mol_transform& transform, bool gpu);

  void forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top, bool gpu);
  void backward(const vector<Blob<Dtype>*>& top, const vector<Blob<Dtype>*>& bottom, bool gpu);
};

}  // namespace caffe

#endif  // CAFFE_MOLGRID_DATA_LAYER_HPP_
<|endoftext|>