<commit_before>// Copyright 2013 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 "device/bluetooth/bluetooth_profile_chromeos.h"

#include <string>

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_util.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "chromeos/dbus/bluetooth_profile_manager_client.h"
#include "chromeos/dbus/bluetooth_profile_service_provider.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "dbus/bus.h"
#include "dbus/file_descriptor.h"
#include "dbus/object_path.h"
#include "device/bluetooth/bluetooth_adapter_chromeos.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_device_chromeos.h"
#include "device/bluetooth/bluetooth_profile.h"
#include "device/bluetooth/bluetooth_socket.h"
#include "device/bluetooth/bluetooth_socket_chromeos.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

using device::BluetoothAdapter;
using device::BluetoothAdapterFactory;
using device::BluetoothDevice;
using device::BluetoothProfile;
using device::BluetoothSocket;

namespace {

// Check the validity of a file descriptor received from D-Bus. Must be run
// on a thread where i/o is permitted.
scoped_ptr<dbus::FileDescriptor> CheckValidity(
    scoped_ptr<dbus::FileDescriptor> fd) {
  base::ThreadRestrictions::AssertIOAllowed();
  fd->CheckValidity();
  return fd.Pass();
}

}  // namespace

namespace chromeos {

BluetoothProfileChromeOS::BluetoothProfileChromeOS()
    : weak_ptr_factory_(this) {
}

BluetoothProfileChromeOS::~BluetoothProfileChromeOS() {
  DCHECK(object_path_.value().empty());
  DCHECK(profile_.get() == NULL);

  if (adapter_.get()) {
    adapter_->RemoveObserver(this);
    adapter_ = NULL;
  }
}

void BluetoothProfileChromeOS::Init(
    const std::string& uuid,
    const device::BluetoothProfile::Options& options,
    const ProfileCallback& callback) {
  DCHECK(object_path_.value().empty());
  DCHECK(profile_.get() == NULL);

  if (!BluetoothDevice::IsUUIDValid(uuid)) {
    callback.Run(NULL);
    return;
  }

  uuid_ = uuid;

  options_.name = options.name;
  options_.service = uuid;
  options_.channel = options.channel;
  options_.psm = options.psm;
  options_.require_authentication = options.require_authentication;
  options_.require_authorization = options.require_authorization;
  options_.auto_connect = options.auto_connect;
  options_.version = options.version;
  options_.features = options.features;

  // The object path is relatively meaningless, but has to be unique, so we
  // use the UUID of the profile.
  std::string uuid_path;
  base::ReplaceChars(uuid, ":-", "_", &uuid_path);

  object_path_ = dbus::ObjectPath("/org/chromium/bluetooth_profile/" +
                                  uuid_path);

  dbus::Bus* system_bus = DBusThreadManager::Get()->GetSystemBus();
  profile_.reset(BluetoothProfileServiceProvider::Create(
      system_bus, object_path_, this));
  DCHECK(profile_.get());

  // Now the profile object is registered we need an adapter to register it
  // with.
  BluetoothAdapterFactory::GetAdapter(
      base::Bind(&BluetoothProfileChromeOS::OnGetAdapter,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback));
}

void BluetoothProfileChromeOS::Unregister() {
  DCHECK(!object_path_.value().empty());
  DCHECK(profile_.get());

  profile_.reset();

  VLOG(1) << object_path_.value() << ": Unregister profile";
  DBusThreadManager::Get()->GetBluetoothProfileManagerClient()->
      UnregisterProfile(
          object_path_,
          base::Bind(&BluetoothProfileChromeOS::OnUnregisterProfile,
                     weak_ptr_factory_.GetWeakPtr()),
          base::Bind(&BluetoothProfileChromeOS::OnUnregisterProfileError,
                     weak_ptr_factory_.GetWeakPtr()));
}

void BluetoothProfileChromeOS::SetConnectionCallback(
    const ConnectionCallback& callback) {
  connection_callback_ = callback;
}

void BluetoothProfileChromeOS::AdapterPresentChanged(BluetoothAdapter* adapter,
                                                     bool present) {
  if (!present)
    return;

  VLOG(1) << object_path_.value() << ": Register profile";
  DBusThreadManager::Get()->GetBluetoothProfileManagerClient()->
      RegisterProfile(
          object_path_,
          uuid_,
          options_,
          base::Bind(&BluetoothProfileChromeOS::OnInternalRegisterProfile,
                     weak_ptr_factory_.GetWeakPtr()),
          base::Bind(&BluetoothProfileChromeOS::OnInternalRegisterProfileError,
                     weak_ptr_factory_.GetWeakPtr()));
}

void BluetoothProfileChromeOS::OnGetAdapter(
    const ProfileCallback& callback,
    scoped_refptr<device::BluetoothAdapter> adapter) {
  DCHECK(!adapter_.get());
  adapter_ = adapter;
  adapter_->AddObserver(this);

  VLOG(1) << object_path_.value() << ": Register profile";
  DBusThreadManager::Get()->GetBluetoothProfileManagerClient()->
      RegisterProfile(
          object_path_,
          uuid_,
          options_,
          base::Bind(&BluetoothProfileChromeOS::OnRegisterProfile,
                     weak_ptr_factory_.GetWeakPtr(),
                     callback),
          base::Bind(&BluetoothProfileChromeOS::OnRegisterProfileError,
                     weak_ptr_factory_.GetWeakPtr(),
                     callback));
}

void BluetoothProfileChromeOS::Release() {
  VLOG(1) << object_path_.value() << ": Release";
}

void BluetoothProfileChromeOS::NewConnection(
    const dbus::ObjectPath& device_path,
    scoped_ptr<dbus::FileDescriptor> fd,
    const BluetoothProfileServiceProvider::Delegate::Options& options,
    const ConfirmationCallback& callback) {
  VLOG(1) << object_path_.value() << ": New connection from device: "
          << device_path.value();
  if (connection_callback_.is_null()) {
    callback.Run(REJECTED);
    return;
  }

  // Punt descriptor validity check to a worker thread where i/o is permitted;
  // on return we'll call the connection callback.
  //
  // base::Passed is used to take ownership of the file descriptor during the
  // CheckValidity() call and pass that ownership to callback.
  base::PostTaskAndReplyWithResult(
      base::WorkerPool::GetTaskRunner(false).get(),
      FROM_HERE,
      base::Bind(&CheckValidity, base::Passed(&fd)),
      base::Bind(&BluetoothProfileChromeOS::OnCheckValidity,
                 weak_ptr_factory_.GetWeakPtr(),
                 device_path,
                 options,
                 callback));
}

void BluetoothProfileChromeOS::RequestDisconnection(
    const dbus::ObjectPath& device_path,
    const ConfirmationCallback& callback) {
  VLOG(1) << object_path_.value() << ": Request disconnection";
  callback.Run(SUCCESS);
}

void BluetoothProfileChromeOS::Cancel() {
  VLOG(1) << object_path_.value() << ": Cancel";
}

void BluetoothProfileChromeOS::OnInternalRegisterProfile() {
  VLOG(1) << object_path_.value() << ": Profile registered";
}

void BluetoothProfileChromeOS::OnInternalRegisterProfileError(
    const std::string& error_name,
    const std::string& error_message) {
  // It's okay if the profile already exists, it means we registered it on
  // initialization.
  if (error_name == bluetooth_profile_manager::kErrorAlreadyExists)
    return;

  LOG(WARNING) << object_path_.value() << ": Failed to register profile: "
               << error_name << ": " << error_message;
}

void BluetoothProfileChromeOS::OnRegisterProfile(
    const ProfileCallback& callback) {
  VLOG(1) << object_path_.value() << ": Profile registered";
  callback.Run(this);
}

void BluetoothProfileChromeOS::OnRegisterProfileError(
    const ProfileCallback& callback,
    const std::string& error_name,
    const std::string& error_message) {
  // It's okay if the profile already exists, it means we registered it when
  // we first saw the adapter.
  if (error_name == bluetooth_profile_manager::kErrorAlreadyExists)
    return;

  LOG(WARNING) << object_path_.value() << ": Failed to register profile: "
               << error_name << ": " << error_message;
  callback.Run(NULL);
}

void BluetoothProfileChromeOS::OnUnregisterProfile() {
  VLOG(1) << object_path_.value() << ": Profile unregistered";
  object_path_ = dbus::ObjectPath("");
  adapter_ = NULL;
  delete this;
}

void BluetoothProfileChromeOS::OnUnregisterProfileError(
    const std::string& error_name,
    const std::string& error_message) {
  // It's okay if the profile didn't exist, it means we never saw an adapter.
  if (error_name == bluetooth_profile_manager::kErrorDoesNotExist)
    return;

  LOG(WARNING) << object_path_.value() << ": Failed to unregister profile: "
               << error_name << ": " << error_message;
  object_path_ = dbus::ObjectPath("");
  adapter_ = NULL;
  delete this;
}

void BluetoothProfileChromeOS::OnCheckValidity(
      const dbus::ObjectPath& device_path,
      const BluetoothProfileServiceProvider::Delegate::Options& options,
      const ConfirmationCallback& callback,
      scoped_ptr<dbus::FileDescriptor> fd) {
  VLOG(1) << object_path_.value() << ": Validity check complete";
  if (!fd->is_valid()) {
    callback.Run(REJECTED);
    return;
  }

  callback.Run(SUCCESS);

  BluetoothDeviceChromeOS* device =
      static_cast<BluetoothAdapterChromeOS*>(adapter_.get())->
          GetDeviceWithPath(device_path);
  DCHECK(device);

  scoped_refptr<BluetoothSocket> socket((
      BluetoothSocketChromeOS::Create(fd.get())));
  connection_callback_.Run(device, socket);
}

}  // namespace chromeos
<commit_msg>Fix crash after Bluetooth profile is unregistered on ChromeOS.<commit_after>// Copyright 2013 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 "device/bluetooth/bluetooth_profile_chromeos.h"

#include <string>

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_util.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "chromeos/dbus/bluetooth_profile_manager_client.h"
#include "chromeos/dbus/bluetooth_profile_service_provider.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "dbus/bus.h"
#include "dbus/file_descriptor.h"
#include "dbus/object_path.h"
#include "device/bluetooth/bluetooth_adapter_chromeos.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_device_chromeos.h"
#include "device/bluetooth/bluetooth_profile.h"
#include "device/bluetooth/bluetooth_socket.h"
#include "device/bluetooth/bluetooth_socket_chromeos.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

using device::BluetoothAdapter;
using device::BluetoothAdapterFactory;
using device::BluetoothDevice;
using device::BluetoothProfile;
using device::BluetoothSocket;

namespace {

// Check the validity of a file descriptor received from D-Bus. Must be run
// on a thread where i/o is permitted.
scoped_ptr<dbus::FileDescriptor> CheckValidity(
    scoped_ptr<dbus::FileDescriptor> fd) {
  base::ThreadRestrictions::AssertIOAllowed();
  fd->CheckValidity();
  return fd.Pass();
}

}  // namespace

namespace chromeos {

BluetoothProfileChromeOS::BluetoothProfileChromeOS()
    : weak_ptr_factory_(this) {
}

BluetoothProfileChromeOS::~BluetoothProfileChromeOS() {
  DCHECK(object_path_.value().empty());
  DCHECK(profile_.get() == NULL);

  if (adapter_.get()) {
    adapter_->RemoveObserver(this);
    adapter_ = NULL;
  }
}

void BluetoothProfileChromeOS::Init(
    const std::string& uuid,
    const device::BluetoothProfile::Options& options,
    const ProfileCallback& callback) {
  DCHECK(object_path_.value().empty());
  DCHECK(profile_.get() == NULL);

  if (!BluetoothDevice::IsUUIDValid(uuid)) {
    callback.Run(NULL);
    return;
  }

  uuid_ = uuid;

  options_.name = options.name;
  options_.service = uuid;
  options_.channel = options.channel;
  options_.psm = options.psm;
  options_.require_authentication = options.require_authentication;
  options_.require_authorization = options.require_authorization;
  options_.auto_connect = options.auto_connect;
  options_.version = options.version;
  options_.features = options.features;

  // The object path is relatively meaningless, but has to be unique, so we
  // use the UUID of the profile.
  std::string uuid_path;
  base::ReplaceChars(uuid, ":-", "_", &uuid_path);

  object_path_ = dbus::ObjectPath("/org/chromium/bluetooth_profile/" +
                                  uuid_path);

  dbus::Bus* system_bus = DBusThreadManager::Get()->GetSystemBus();
  profile_.reset(BluetoothProfileServiceProvider::Create(
      system_bus, object_path_, this));
  DCHECK(profile_.get());

  // Now the profile object is registered we need an adapter to register it
  // with.
  BluetoothAdapterFactory::GetAdapter(
      base::Bind(&BluetoothProfileChromeOS::OnGetAdapter,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback));
}

void BluetoothProfileChromeOS::Unregister() {
  DCHECK(!object_path_.value().empty());
  DCHECK(profile_.get());

  profile_.reset();

  VLOG(1) << object_path_.value() << ": Unregister profile";
  DBusThreadManager::Get()->GetBluetoothProfileManagerClient()->
      UnregisterProfile(
          object_path_,
          base::Bind(&BluetoothProfileChromeOS::OnUnregisterProfile,
                     weak_ptr_factory_.GetWeakPtr()),
          base::Bind(&BluetoothProfileChromeOS::OnUnregisterProfileError,
                     weak_ptr_factory_.GetWeakPtr()));
}

void BluetoothProfileChromeOS::SetConnectionCallback(
    const ConnectionCallback& callback) {
  connection_callback_ = callback;
}

void BluetoothProfileChromeOS::AdapterPresentChanged(BluetoothAdapter* adapter,
                                                     bool present) {
  if (!present)
    return;

  VLOG(1) << object_path_.value() << ": Register profile";
  DBusThreadManager::Get()->GetBluetoothProfileManagerClient()->
      RegisterProfile(
          object_path_,
          uuid_,
          options_,
          base::Bind(&BluetoothProfileChromeOS::OnInternalRegisterProfile,
                     weak_ptr_factory_.GetWeakPtr()),
          base::Bind(&BluetoothProfileChromeOS::OnInternalRegisterProfileError,
                     weak_ptr_factory_.GetWeakPtr()));
}

void BluetoothProfileChromeOS::OnGetAdapter(
    const ProfileCallback& callback,
    scoped_refptr<device::BluetoothAdapter> adapter) {
  DCHECK(!adapter_.get());
  adapter_ = adapter;
  adapter_->AddObserver(this);

  VLOG(1) << object_path_.value() << ": Register profile";
  DBusThreadManager::Get()->GetBluetoothProfileManagerClient()->
      RegisterProfile(
          object_path_,
          uuid_,
          options_,
          base::Bind(&BluetoothProfileChromeOS::OnRegisterProfile,
                     weak_ptr_factory_.GetWeakPtr(),
                     callback),
          base::Bind(&BluetoothProfileChromeOS::OnRegisterProfileError,
                     weak_ptr_factory_.GetWeakPtr(),
                     callback));
}

void BluetoothProfileChromeOS::Release() {
  VLOG(1) << object_path_.value() << ": Release";
}

void BluetoothProfileChromeOS::NewConnection(
    const dbus::ObjectPath& device_path,
    scoped_ptr<dbus::FileDescriptor> fd,
    const BluetoothProfileServiceProvider::Delegate::Options& options,
    const ConfirmationCallback& callback) {
  VLOG(1) << object_path_.value() << ": New connection from device: "
          << device_path.value();
  if (connection_callback_.is_null()) {
    callback.Run(REJECTED);
    return;
  }

  // Punt descriptor validity check to a worker thread where i/o is permitted;
  // on return we'll call the connection callback.
  //
  // base::Passed is used to take ownership of the file descriptor during the
  // CheckValidity() call and pass that ownership to callback.
  base::PostTaskAndReplyWithResult(
      base::WorkerPool::GetTaskRunner(false).get(),
      FROM_HERE,
      base::Bind(&CheckValidity, base::Passed(&fd)),
      base::Bind(&BluetoothProfileChromeOS::OnCheckValidity,
                 weak_ptr_factory_.GetWeakPtr(),
                 device_path,
                 options,
                 callback));
}

void BluetoothProfileChromeOS::RequestDisconnection(
    const dbus::ObjectPath& device_path,
    const ConfirmationCallback& callback) {
  VLOG(1) << object_path_.value() << ": Request disconnection";
  callback.Run(SUCCESS);
}

void BluetoothProfileChromeOS::Cancel() {
  VLOG(1) << object_path_.value() << ": Cancel";
}

void BluetoothProfileChromeOS::OnInternalRegisterProfile() {
  VLOG(1) << object_path_.value() << ": Profile registered";
}

void BluetoothProfileChromeOS::OnInternalRegisterProfileError(
    const std::string& error_name,
    const std::string& error_message) {
  // It's okay if the profile already exists, it means we registered it on
  // initialization.
  if (error_name == bluetooth_profile_manager::kErrorAlreadyExists)
    return;

  LOG(WARNING) << object_path_.value() << ": Failed to register profile: "
               << error_name << ": " << error_message;
}

void BluetoothProfileChromeOS::OnRegisterProfile(
    const ProfileCallback& callback) {
  VLOG(1) << object_path_.value() << ": Profile registered";
  callback.Run(this);
}

void BluetoothProfileChromeOS::OnRegisterProfileError(
    const ProfileCallback& callback,
    const std::string& error_name,
    const std::string& error_message) {
  // It's okay if the profile already exists, it means we registered it when
  // we first saw the adapter.
  if (error_name == bluetooth_profile_manager::kErrorAlreadyExists)
    return;

  LOG(WARNING) << object_path_.value() << ": Failed to register profile: "
               << error_name << ": " << error_message;
  callback.Run(NULL);
}

void BluetoothProfileChromeOS::OnUnregisterProfile() {
  VLOG(1) << object_path_.value() << ": Profile unregistered";
  object_path_ = dbus::ObjectPath("");
  delete this;
}

void BluetoothProfileChromeOS::OnUnregisterProfileError(
    const std::string& error_name,
    const std::string& error_message) {
  // It's okay if the profile didn't exist, it means we never saw an adapter.
  if (error_name == bluetooth_profile_manager::kErrorDoesNotExist)
    return;

  LOG(WARNING) << object_path_.value() << ": Failed to unregister profile: "
               << error_name << ": " << error_message;
  object_path_ = dbus::ObjectPath("");
  delete this;
}

void BluetoothProfileChromeOS::OnCheckValidity(
      const dbus::ObjectPath& device_path,
      const BluetoothProfileServiceProvider::Delegate::Options& options,
      const ConfirmationCallback& callback,
      scoped_ptr<dbus::FileDescriptor> fd) {
  VLOG(1) << object_path_.value() << ": Validity check complete";
  if (!fd->is_valid()) {
    callback.Run(REJECTED);
    return;
  }

  callback.Run(SUCCESS);

  BluetoothDeviceChromeOS* device =
      static_cast<BluetoothAdapterChromeOS*>(adapter_.get())->
          GetDeviceWithPath(device_path);
  DCHECK(device);

  scoped_refptr<BluetoothSocket> socket((
      BluetoothSocketChromeOS::Create(fd.get())));
  connection_callback_.Run(device, socket);
}

}  // namespace chromeos
<|endoftext|>


<commit_before>#include "RaZ/Render/Camera.hpp"

namespace Raz {

Camera::Camera(unsigned int frameWidth, unsigned int frameHeight,
               float fieldOfViewDegrees,
               float nearPlane, float farPlane) : m_frameRatio{ static_cast<float>(frameWidth) / static_cast<float>(frameHeight) },
                                                  m_nearPlane{ nearPlane }, m_farPlane{ farPlane } {
  setFieldOfView(fieldOfViewDegrees);
}

void Camera::setFieldOfView(float fieldOfViewDegrees) {
  m_fieldOfView = fieldOfViewDegrees * PI<float> / 180;

  computePerspectiveMatrix();
  computeInverseProjectionMatrix();
}

const Mat4f& Camera::computeViewMatrix(const Mat4f& translationMatrix, const Mat4f& inverseRotation) {
  m_viewMat = translationMatrix * inverseRotation;
  return m_viewMat;
}

const Mat4f& Camera::computeLookAt(const Vec3f& position, const Vec3f& target, const Vec3f& upDirection) {
  const Vec3f zAxis((position - target).normalize());
  const Vec3f xAxis(zAxis.cross(upDirection).normalize());
  const Vec3f yAxis(xAxis.cross(zAxis));

  m_viewMat = Mat4f({{             xAxis[0],             yAxis[0],           -zAxis[0], 0.f },
                     {             xAxis[1],             yAxis[1],           -zAxis[1], 0.f },
                     {             xAxis[2],             yAxis[2],           -zAxis[2], 0.f },
                     { xAxis.dot(-position), yAxis.dot(-position), zAxis.dot(position), 1.f }});

  return m_viewMat;
}

const Mat4f& Camera::computeInverseViewMatrix() {
  m_invViewMat = m_viewMat.inverse();
  return m_invViewMat;
}

const Mat4f& Camera::computePerspectiveMatrix() {
  const float halfFovTangent = std::tan(m_fieldOfView / 2.f);
  const float planeDist      = m_farPlane - m_nearPlane;
  const float planeMult      = m_farPlane * m_nearPlane;
  const float fovRatio       = m_frameRatio * halfFovTangent;

  m_projMat = Mat4f({{ 1 / fovRatio,                0.f,                    0.f, 0.f },
                     {          0.f, 1 / halfFovTangent,                    0.f, 0.f },
                     {          0.f,                0.f, m_farPlane / planeDist, 1.f },
                     {          0.f,                0.f, -planeMult / planeDist, 1.f }});

  return m_projMat;
}

const Mat4f& Camera::computeInverseProjectionMatrix() {
  m_invProjMat = m_projMat.inverse();
  return m_invProjMat;
}

} // namespace Raz
<commit_msg>[Fix] Finally fixed the perspective matrix, displaying cubemap correctly [skip ci]<commit_after>#include "RaZ/Render/Camera.hpp"

namespace Raz {

Camera::Camera(unsigned int frameWidth, unsigned int frameHeight,
               float fieldOfViewDegrees,
               float nearPlane, float farPlane) : m_frameRatio{ static_cast<float>(frameWidth) / static_cast<float>(frameHeight) },
                                                  m_nearPlane{ nearPlane }, m_farPlane{ farPlane } {
  setFieldOfView(fieldOfViewDegrees);
}

void Camera::setFieldOfView(float fieldOfViewDegrees) {
  m_fieldOfView = fieldOfViewDegrees * PI<float> / 180;

  computePerspectiveMatrix();
  computeInverseProjectionMatrix();
}

const Mat4f& Camera::computeViewMatrix(const Mat4f& translationMatrix, const Mat4f& inverseRotation) {
  m_viewMat = translationMatrix * inverseRotation;
  return m_viewMat;
}

const Mat4f& Camera::computeLookAt(const Vec3f& position, const Vec3f& target, const Vec3f& upDirection) {
  const Vec3f zAxis((position - target).normalize());
  const Vec3f xAxis(zAxis.cross(upDirection).normalize());
  const Vec3f yAxis(xAxis.cross(zAxis));

  m_viewMat = Mat4f({{             xAxis[0],             yAxis[0],           -zAxis[0], 0.f },
                     {             xAxis[1],             yAxis[1],           -zAxis[1], 0.f },
                     {             xAxis[2],             yAxis[2],           -zAxis[2], 0.f },
                     { xAxis.dot(-position), yAxis.dot(-position), zAxis.dot(position), 1.f }});

  return m_viewMat;
}

const Mat4f& Camera::computeInverseViewMatrix() {
  m_invViewMat = m_viewMat.inverse();
  return m_invViewMat;
}

const Mat4f& Camera::computePerspectiveMatrix() {
  const float halfFovTangent = std::tan(m_fieldOfView / 2.f);
  const float planeDist      = m_farPlane - m_nearPlane;
  const float planeMult      = m_farPlane * m_nearPlane;
  const float fovRatio       = m_frameRatio * halfFovTangent;

  m_projMat = Mat4f({{ 1 / fovRatio,                0.f,                    0.f, 0.f },
                     {          0.f, 1 / halfFovTangent,                    0.f, 0.f },
                     {          0.f,                0.f, m_farPlane / planeDist, 1.f },
                     {          0.f,                0.f, -planeMult / planeDist, 0.f }});

  return m_projMat;
}

const Mat4f& Camera::computeInverseProjectionMatrix() {
  m_invProjMat = m_projMat.inverse();
  return m_invProjMat;
}

} // namespace Raz
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-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.                                           //
// ======================================================================== //

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundefined-func-template"

#include "rawToAMR.h"

#include <errno.h>
#include <stdio.h>
#include <sstream>

namespace ospray {
  namespace amr {

    void makeAMR(const std::vector<float> &in,
                 const vec3i inGridDims,
                 const int numLevels,
                 const int blockSize,
                 const int refinementLevel,
                 const float threshold,
                 std::vector<box3i> &blockBounds,
                 std::vector<int> &refinementLevels,
                 std::vector<float> &cellWidths,
                 std::vector<std::vector<float>> &brickData)
    {
      int minWidth = blockSize;
      std::cout << "building AMR model out of RAW volume. blockSize = "
                << blockSize << ", refinementLevel = " << refinementLevel
                << std::endl;

      for (int i = 1; i < numLevels; i++)
        minWidth *= refinementLevel;

      if (minWidth >= refinementLevel * reduce_max(inGridDims)) {
        throw std::runtime_error(
            "too many levels, or too fine a refinement factor."
            "do not have a single brick at the root...");
      }
      vec3i finestLevelSize = ospcommon::vec3i(minWidth);
      while (finestLevelSize.x < inGridDims.x) {
        finestLevelSize.x += minWidth;
      }
      while (finestLevelSize.y < inGridDims.y) {
        finestLevelSize.y += minWidth;
      }
      while (finestLevelSize.z < inGridDims.z) {
        finestLevelSize.z += minWidth;
      }

      std::cout << "logical finest level size is " << finestLevelSize
                << std::endl;
      std::cout << "(note: input size was " << inGridDims << ")" << std::endl;

      // create container for current level so we don't use in
      std::vector<float> &currentLevel = const_cast<std::vector<float> &>(in);

      size_t numWritten = 0;
      size_t numRemoved = 0;
      std::mutex fileMutex;

      // create and write the bricks
      vec3i levelSize = finestLevelSize;
      for (int level = numLevels - 1; level >= 0; --level) {
        std::cout << "-------------------------------------------------------"
                  << std::endl;
        std::cout << "logical size of level " << level << " is " << levelSize
                  << std::endl;
        const vec3i nextLevelSize = levelSize / refinementLevel;
        std::cout << "reducing to next level of " << nextLevelSize << std::endl;
        // create container for next level down
        std::vector<float> nextLevel =
            std::vector<float>(nextLevelSize.product(), 0);

        const vec3i numBricks = levelSize / blockSize;
        ospcommon::tasking::parallel_for(
            numBricks.product(), [&](int brickIdx) {
              // dt == cellWidth in osp_amr_brick_info
              float dt = 1.f / powf(refinementLevel, level);
              // get 3D brick index from flat brickIdx
              const vec3i brickID(brickIdx % numBricks.x,
                                  (brickIdx / numBricks.x) % numBricks.y,
                                  brickIdx / (numBricks.x * numBricks.y));
              // set upper and lower bounds of brick based on 3D index and
              // brick size in input data space
              box3i box;
              box.lower = brickID * blockSize;
              box.upper = box.lower + (blockSize - 1);
              // current brick data
              std::vector<float> data(blockSize * blockSize * blockSize);
              size_t out = 0;
              ospcommon::range1f brickRange;
              // traverse the data by brick index
              for (int iz = box.lower.z; iz <= box.upper.z; iz++) {
                for (int iy = box.lower.y; iy <= box.upper.y;
                     iy++) {
                  for (int ix = box.lower.x; ix <= box.upper.x;
                       ix++) {
                    const size_t thisLevelCoord =
                        ix + levelSize.y * (iy + iz * levelSize.z);
                    const size_t nextLevelCoord =
                        ix / refinementLevel +
                        nextLevelSize.y *
                            (iy / refinementLevel +
                             iz / refinementLevel * nextLevelSize.z);
                    // get the actual data at current coordinates
                    const float v = currentLevel[thisLevelCoord];
                    // insert the data into the current brick
                    data[out++] = v;
                    nextLevel[nextLevelCoord] +=
                        v /
                        (refinementLevel * refinementLevel * refinementLevel);
                    // extend the value range of this brick (min/max) as needed
                    brickRange.extend(v);
                  }
                }
              }

              std::lock_guard<std::mutex> lock(fileMutex);
              if ((level > 0) &&
                  ((brickRange.upper - brickRange.lower) <= threshold)) {
                numRemoved++;
              } else {
                blockBounds.push_back(box);
                refinementLevels.push_back(level);
                cellWidths.reserve(level + 1);
                cellWidths[level] = dt;
                brickData.push_back(data);
                numWritten++;
              }
            });  // end parallel for
        currentLevel = nextLevel;
        levelSize    = nextLevelSize;
        std::cout << "done level " << level << ", written " << numWritten
                  << " bricks, removed " << numRemoved << std::endl;
        numWritten = 0;
        numRemoved = 0;
      }  // end for loop on levels
    }

    void outputAMR(const FileName outFileBase,
                   const std::vector<box3i> &blockBounds,
                   const std::vector<int> &refinementLevels,
                   const std::vector<float> &cellWidths,
                   const std::vector<std::vector<float>> &brickData,
                   const int blockSize)
    {
      // ALOK: .info is brick metadata
      FILE *infoOut = fopen(outFileBase.addExt(".info").c_str(), "wb");
      if (!infoOut) {
        throw std::runtime_error("could not open info output file!");
      }

      // ALOK: .data is actual data
      FILE *dataOut = fopen(outFileBase.addExt(".data").c_str(), "wb");
      if (!dataOut) {
        throw std::runtime_error("could not open data output file!");
      }

      std::ofstream osp(outFileBase + ".osp");
      osp << "<?xml?>" << std::endl;
      osp << "<AMRVolume>" << std::endl;
      osp << "  <fileName>" << ospcommon::FileName(outFileBase).base()
          << "</fileName>" << std::endl;
      osp << "  <brickSize>" << blockSize << "</brickSize>" << std::endl;
      osp << "  <clamp>0 100000</clamp>" << std::endl;
      osp << "</AMRVolume>" << std::endl;

      fwrite(blockBounds.data(), sizeof(box3i), blockBounds.size(), infoOut);
      fwrite(refinementLevels.data(),
             sizeof(int),
             refinementLevels.size(),
             infoOut);
      fwrite(cellWidths.data(), sizeof(float), cellWidths.size(), infoOut);

      for (auto &data : brickData) {
        fwrite(data.data(), sizeof(float), data.size(), dataOut);
      }

      fclose(infoOut);
      fclose(dataOut);
    }

    template <typename T>
    std::vector<T> loadRAW(const std::string &fileName, const vec3i &dims)
    {
      const size_t num = dims.product();
      std::vector<T> volume(num);
      FILE *file = fopen(fileName.c_str(), "rb");
      if (!file)
        throw std::runtime_error("ospray::amr::loadRaw(): could not open '" +
                                 fileName + "'");
      size_t numRead = fread(volume.data(), sizeof(T), num, file);
      if (num != numRead)
        throw std::runtime_error(
            "ospray::amr::loadRaw(): read incomplete data ...");
      fclose(file);

      return volume;
    }

  }  // namespace amr
}  // namespace ospray

#pragma clang diagnostic pop
<commit_msg>fix cellWidths bug and write array sizes to disk<commit_after>// ======================================================================== //
// Copyright 2009-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.                                           //
// ======================================================================== //

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundefined-func-template"

#include "rawToAMR.h"

#include <errno.h>
#include <stdio.h>
#include <sstream>

namespace ospray {
  namespace amr {

    void makeAMR(const std::vector<float> &in,
                 const vec3i inGridDims,
                 const int numLevels,
                 const int blockSize,
                 const int refinementLevel,
                 const float threshold,
                 std::vector<box3i> &blockBounds,
                 std::vector<int> &refinementLevels,
                 std::vector<float> &cellWidths,
                 std::vector<std::vector<float>> &brickData)
    {
      int minWidth = blockSize;
      std::cout << "building AMR model out of RAW volume. blockSize = "
                << blockSize << ", refinementLevel = " << refinementLevel
                << std::endl;

      for (int i = 1; i < numLevels; i++)
        minWidth *= refinementLevel;

      if (minWidth >= refinementLevel * reduce_max(inGridDims)) {
        throw std::runtime_error(
            "too many levels, or too fine a refinement factor."
            "do not have a single brick at the root...");
      }
      vec3i finestLevelSize = ospcommon::vec3i(minWidth);
      while (finestLevelSize.x < inGridDims.x) {
        finestLevelSize.x += minWidth;
      }
      while (finestLevelSize.y < inGridDims.y) {
        finestLevelSize.y += minWidth;
      }
      while (finestLevelSize.z < inGridDims.z) {
        finestLevelSize.z += minWidth;
      }

      std::cout << "logical finest level size is " << finestLevelSize
                << std::endl;
      std::cout << "(note: input size was " << inGridDims << ")" << std::endl;

      // create container for current level so we don't use in
      std::vector<float> &currentLevel = const_cast<std::vector<float> &>(in);

      size_t numWritten = 0;
      size_t numRemoved = 0;
      std::mutex fileMutex;

      // create and write the bricks
      vec3i levelSize = finestLevelSize;
      for (int level = numLevels - 1; level >= 0; --level) {
        std::cout << "-------------------------------------------------------"
                  << std::endl;
        std::cout << "logical size of level " << level << " is " << levelSize
                  << std::endl;
        const vec3i nextLevelSize = levelSize / refinementLevel;
        std::cout << "reducing to next level of " << nextLevelSize << std::endl;
        // create container for next level down
        std::vector<float> nextLevel =
            std::vector<float>(nextLevelSize.product(), 0);

        const vec3i numBricks = levelSize / blockSize;
        ospcommon::tasking::parallel_for(
            numBricks.product(), [&](int brickIdx) {
              // dt == cellWidth in osp_amr_brick_info
              float dt = 1.f / powf(refinementLevel, level);
              // get 3D brick index from flat brickIdx
              const vec3i brickID(brickIdx % numBricks.x,
                                  (brickIdx / numBricks.x) % numBricks.y,
                                  brickIdx / (numBricks.x * numBricks.y));
              // set upper and lower bounds of brick based on 3D index and
              // brick size in input data space
              box3i box;
              box.lower = brickID * blockSize;
              box.upper = box.lower + (blockSize - 1);
              // current brick data
              std::vector<float> data(blockSize * blockSize * blockSize);
              size_t out = 0;
              ospcommon::range1f brickRange;
              // traverse the data by brick index
              for (int iz = box.lower.z; iz <= box.upper.z; iz++) {
                for (int iy = box.lower.y; iy <= box.upper.y;
                     iy++) {
                  for (int ix = box.lower.x; ix <= box.upper.x;
                       ix++) {
                    const size_t thisLevelCoord =
                        ix + levelSize.y * (iy + iz * levelSize.z);
                    const size_t nextLevelCoord =
                        ix / refinementLevel +
                        nextLevelSize.y *
                            (iy / refinementLevel +
                             iz / refinementLevel * nextLevelSize.z);
                    // get the actual data at current coordinates
                    const float v = currentLevel[thisLevelCoord];
                    // insert the data into the current brick
                    data[out++] = v;
                    nextLevel[nextLevelCoord] +=
                        v /
                        (refinementLevel * refinementLevel * refinementLevel);
                    // extend the value range of this brick (min/max) as needed
                    brickRange.extend(v);
                  }
                }
              }

              std::lock_guard<std::mutex> lock(fileMutex);
              if ((level > 0) &&
                  ((brickRange.upper - brickRange.lower) <= threshold)) {
                numRemoved++;
              } else {
                blockBounds.push_back(box);
                refinementLevels.push_back(level);
                cellWidths.resize(std::max(cellWidths.size(), (size_t)level + 1));
                cellWidths[level] = dt;
                brickData.push_back(data);
                numWritten++;
              }
            });  // end parallel for
        currentLevel = nextLevel;
        levelSize    = nextLevelSize;
        std::cout << "done level " << level << ", written " << numWritten
                  << " bricks, removed " << numRemoved << std::endl;
        numWritten = 0;
        numRemoved = 0;
      }  // end for loop on levels
    }

    void outputAMR(const FileName outFileBase,
                   const std::vector<box3i> &blockBounds,
                   const std::vector<int> &refinementLevels,
                   const std::vector<float> &cellWidths,
                   const std::vector<std::vector<float>> &brickData,
                   const int blockSize)
    {
      // ALOK: .info is brick metadata
      FILE *infoOut = fopen(outFileBase.addExt(".info").c_str(), "wb");
      if (!infoOut) {
        throw std::runtime_error("could not open info output file!");
      }

      // ALOK: .data is actual data
      FILE *dataOut = fopen(outFileBase.addExt(".data").c_str(), "wb");
      if (!dataOut) {
        throw std::runtime_error("could not open data output file!");
      }

      std::ofstream osp(outFileBase + ".osp");
      osp << "<?xml?>" << std::endl;
      osp << "<AMRVolume>" << std::endl;
      osp << "  <fileName>" << ospcommon::FileName(outFileBase).base()
          << "</fileName>" << std::endl;
      osp << "  <brickSize>" << blockSize << "</brickSize>" << std::endl;
      osp << "  <clamp>0 100000</clamp>" << std::endl;
      osp << "</AMRVolume>" << std::endl;

      size_t numBlockBounds      = blockBounds.size(),
             numRefinementLevels = refinementLevels.size(),
             numCellWidths       = cellWidths.size();
      fwrite(&numBlockBounds, sizeof(size_t), 1, infoOut);
      fwrite(blockBounds.data(), sizeof(box3i), blockBounds.size(), infoOut);
      fwrite(&numRefinementLevels, sizeof(size_t), 1, infoOut);
      fwrite(refinementLevels.data(),
             sizeof(int),
             refinementLevels.size(),
             infoOut);
      fwrite(&numCellWidths, sizeof(size_t), 1, infoOut);
      fwrite(cellWidths.data(), sizeof(float), cellWidths.size(), infoOut);

      for (auto &data : brickData) {
        fwrite(data.data(), sizeof(float), data.size(), dataOut);
      }

      fclose(infoOut);
      fclose(dataOut);
    }

    template <typename T>
    std::vector<T> loadRAW(const std::string &fileName, const vec3i &dims)
    {
      const size_t num = dims.product();
      std::vector<T> volume(num);
      FILE *file = fopen(fileName.c_str(), "rb");
      if (!file)
        throw std::runtime_error("ospray::amr::loadRaw(): could not open '" +
                                 fileName + "'");
      size_t numRead = fread(volume.data(), sizeof(T), num, file);
      if (num != numRead)
        throw std::runtime_error(
            "ospray::amr::loadRaw(): read incomplete data ...");
      fclose(file);

      return volume;
    }

  }  // namespace amr
}  // namespace ospray

#pragma clang diagnostic pop
<|endoftext|>


<commit_before>#ifndef Magnum_SceneGraph_Object_hpp
#define Magnum_SceneGraph_Object_hpp
/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

/** @file
 * @brief @ref compilation-speedup-hpp "Template implementation" for Object.h
 */

#include "AbstractTransformation.h"
#include "Object.h"

#include <algorithm>
#include <stack>

#include "Scene.h"

namespace Magnum { namespace SceneGraph {

template<UnsignedInt dimensions, class T> AbstractObject<dimensions, T>::AbstractObject() {}
template<UnsignedInt dimensions, class T> AbstractObject<dimensions, T>::~AbstractObject() {}

template<UnsignedInt dimensions, class T> inline AbstractTransformation<dimensions, T>::AbstractTransformation() {}
template<UnsignedInt dimensions, class T> inline AbstractTransformation<dimensions, T>::~AbstractTransformation() {}

template<class Transformation> Scene<Transformation>* Object<Transformation>::scene() {
    return static_cast<Scene<Transformation>*>(sceneObject());
}

template<class Transformation> const Scene<Transformation>* Object<Transformation>::scene() const {
    return static_cast<const Scene<Transformation>*>(sceneObject());
}

template<class Transformation> Object<Transformation>* Object<Transformation>::sceneObject() {
    Object<Transformation>* p(this);
    while(p && !p->isScene()) p = p->parent();
    return p;
}

template<class Transformation> const Object<Transformation>* Object<Transformation>::sceneObject() const {
    const Object<Transformation>* p(this);
    while(p && !p->isScene()) p = p->parent();
    return p;
}

template<class Transformation> Object<Transformation>* Object<Transformation>::setParent(Object<Transformation>* parent) {
    /* Skip if parent is already parent or this is scene (which cannot have parent) */
    /** @todo Assert for setting parent to scene */
    if(this->parent() == parent || isScene()) return this;

    /* Object cannot be parented to its child */
    Object<Transformation>* p = parent;
    while(p) {
        /** @todo Assert for this */
        if(p == this) return this;
        p = p->parent();
    }

    /* Remove the object from old parent children list */
    if(this->parent()) this->parent()->Corrade::Containers::template LinkedList<Object<Transformation>>::cut(this);

    /* Add the object to list of new parent */
    if(parent) parent->Corrade::Containers::LinkedList<Object<Transformation>>::insert(this);

    setDirty();
    return this;
}

template<class Transformation> typename Transformation::DataType Object<Transformation>::absoluteTransformation() const {
    if(!parent()) return Transformation::transformation();
    return Transformation::compose(parent()->absoluteTransformation(), Transformation::transformation());
}

template<class Transformation> void Object<Transformation>::setDirty() {
    /* The transformation of this object (and all children) is already dirty,
       nothing to do */
    if(flags & Flag::Dirty) return;

    Object<Transformation>* self = static_cast<Object<Transformation>*>(this);

    /* Make all features dirty */
    for(AbstractFeature<Transformation::Dimensions, typename Transformation::Type>* i = self->firstFeature(); i; i = i->nextFeature())
        i->markDirty();

    /* Make all children dirty */
    for(Object<Transformation>* i = self->firstChild(); i; i = i->nextSibling())
        i->setDirty();

    /* Mark object as dirty */
    flags |= Flag::Dirty;
}

template<class Transformation> void Object<Transformation>::setClean() {
    /* The object (and all its parents) are already clean, nothing to do */
    if(!(flags & Flag::Dirty)) return;

    /* Collect all parents, compute base transformation */
    std::stack<Object<Transformation>*> objects;
    typename Transformation::DataType absoluteTransformation;
    Object<Transformation>* p = static_cast<Object<Transformation>*>(this);
    for(;;) {
        objects.push(p);

        p = p->parent();

        /* On root object, base transformation is identity */
        if(!p) break;

        /* Parent object is clean, base transformation is its absolute
           transformation */
        if(!p->isDirty()) {
            absoluteTransformation = p->absoluteTransformation();
            break;
        }
    }

    /* Clean features on every collected object, going down from root object */
    while(!objects.empty()) {
        Object<Transformation>* o = objects.top();
        objects.pop();

        /* Compose transformation and clean object */
        absoluteTransformation = Transformation::compose(absoluteTransformation, o->transformation());
        o->setClean(absoluteTransformation);
    }
}

template<class Transformation> std::vector<typename DimensionTraits<Transformation::Dimensions, typename Transformation::Type>::MatrixType> Object<Transformation>::transformationMatrices(const std::vector<AbstractObject<Transformation::Dimensions, typename Transformation::Type>*>& objects, const typename DimensionTraits<Transformation::Dimensions, typename Transformation::Type>::MatrixType& initialTransformationMatrix) const {
    std::vector<Object<Transformation>*> castObjects(objects.size());
    for(std::size_t i = 0; i != objects.size(); ++i)
        /** @todo Ensure this doesn't crash, somehow */
        castObjects[i] = static_cast<Object<Transformation>*>(objects[i]);

    std::vector<typename Transformation::DataType> transformations = this->transformations(std::move(castObjects), Transformation::fromMatrix(initialTransformationMatrix));
    std::vector<typename DimensionTraits<Transformation::Dimensions, typename Transformation::Type>::MatrixType> transformationMatrices(transformations.size());
    for(std::size_t i = 0; i != objects.size(); ++i)
        transformationMatrices[i] = Transformation::toMatrix(transformations[i]);

    return transformationMatrices;
}

/*
Computing absolute transformations for given list of objects

The goal is to compute absolute transformation only once for each object
involved. Objects contained in the subtree specified by `object` list are
divided into two groups:
 - "joints", which are either part of `object` list or they have more than one
   child in the subtree
 - "non-joints", i.e. paths between joints

Then for all joints their transformation (relative to parent joint) is
computed and recursively concatenated together. Resulting transformations for
joints which were originally in `object` list is then returned.
*/
template<class Transformation> std::vector<typename Transformation::DataType> Object<Transformation>::transformations(std::vector<Object<Transformation>*> objects, const typename Transformation::DataType& initialTransformation) const {
    CORRADE_ASSERT(objects.size() < 0xFFFFu, "SceneGraph::Object::transformations(): too large scene", {});

    /* Remember object count for later */
    std::size_t objectCount = objects.size();

    /* Mark all original objects as joints and create initial list of joints
       from them */
    for(std::size_t i = 0; i != objects.size(); ++i) {
        /* Multiple occurences of one object in the array, don't overwrite it
           with different counter */
        if(objects[i]->counter != 0xFFFFu) continue;

        objects[i]->counter = i;
        objects[i]->flags |= Flag::Joint;
    }
    std::vector<Object<Transformation>*> jointObjects(objects);

    /* Scene object */
    const Scene<Transformation>* scene = this->scene();

    /* Nearest common ancestor not yet implemented - assert this is done on scene */
    CORRADE_ASSERT(scene == this, "SceneGraph::Object::transformationMatrices(): currently implemented only for Scene", {});

    /* Mark all objects up the hierarchy as visited */
    auto it = objects.begin();
    while(!objects.empty()) {
        /* Already visited, remove and continue to next (duplicate occurence) */
        if((*it)->flags & Flag::Visited) {
            it = objects.erase(it);
            continue;
        }

        /* Mark the object as visited */
        (*it)->flags |= Flag::Visited;

        Object<Transformation>* parent = (*it)->parent();

        /* If this is root object, remove from list */
        if(!parent) {
            CORRADE_ASSERT(*it == scene, "SceneGraph::Object::transformations(): the objects are not part of the same tree", {});
            it = objects.erase(it);

        /* Parent is an joint or already visited - remove current from list */
        } else if(parent->flags & (Flag::Visited|Flag::Joint)) {
            it = objects.erase(it);

            /* If not already marked as joint, mark it as such and add it to
               list of joint objects */
            if(!(parent->flags & Flag::Joint)) {
                CORRADE_ASSERT(jointObjects.size() < 0xFFFFu,
                               "SceneGraph::Object::transformations(): too large scene", {});
                CORRADE_INTERNAL_ASSERT(parent->counter == 0xFFFFu);
                parent->counter = jointObjects.size();
                parent->flags |= Flag::Joint;
                jointObjects.push_back(parent);
            }

        /* Else go up the hierarchy */
        } else *it = parent;

        /* Cycle if reached end */
        if(it == objects.end()) it = objects.begin();
    }

    /* Array of absolute transformations in joints */
    std::vector<typename Transformation::DataType> jointTransformations(jointObjects.size());

    /* Compute transformations for all joints */
    for(std::size_t i = 0; i != jointTransformations.size(); ++i)
        computeJointTransformation(jointObjects, jointTransformations, i, initialTransformation);

    /* Copy transformation for second or next occurences from first occurence
       of duplicate object */
    for(std::size_t i = 0; i != objectCount; ++i) {
        if(jointObjects[i]->counter != i)
            jointTransformations[i] = jointTransformations[jointObjects[i]->counter];
    }

    /* All visited marks are now cleaned, clean joint marks and counters */
    for(auto i: jointObjects) {
        /* All not-already cleaned objects (...duplicate occurences) should
           have joint mark */
        CORRADE_INTERNAL_ASSERT(i->counter = 0xFFFFu || i->flags & Flag::Joint);
        i->flags &= ~Flag::Joint;
        i->counter = 0xFFFFu;
    }

    /* Shrink the array to contain only transformations of requested objects and return */
    jointTransformations.resize(objectCount);
    return jointTransformations;
}

template<class Transformation> typename Transformation::DataType Object<Transformation>::computeJointTransformation(const std::vector<Object<Transformation>*>& jointObjects, std::vector<typename Transformation::DataType>& jointTransformations, const std::size_t joint, const typename Transformation::DataType& initialTransformation) const {
    Object<Transformation>* o = jointObjects[joint];

    /* Transformation already computed ("unvisited" by this function before
       either due to recursion or duplicate object occurences), done */
    if(!(o->flags & Flag::Visited)) return jointTransformations[joint];

    /* Initialize transformation */
    jointTransformations[joint] = o->transformation();

    /* Go up until next joint or root */
    for(;;) {
        /* Clean visited mark */
        CORRADE_INTERNAL_ASSERT(o->flags & Flag::Visited);
        o->flags &= ~Flag::Visited;

        Object<Transformation>* parent = o->parent();

        /* Root object, compose transformation with initial, done */
        if(!parent) {
            CORRADE_INTERNAL_ASSERT(o->isScene());
            return (jointTransformations[joint] =
                Transformation::compose(initialTransformation, jointTransformations[joint]));

        /* Joint object, compose transformation with the joint, done */
        } else if(parent->flags & Flag::Joint) {
            return (jointTransformations[joint] =
                Transformation::compose(computeJointTransformation(jointObjects, jointTransformations, parent->counter, initialTransformation), jointTransformations[joint]));

        /* Else compose transformation with parent, go up the hierarchy */
        } else {
            jointTransformations[joint] = Transformation::compose(parent->transformation(), jointTransformations[joint]);
            o = parent;
        }
    }
}

template<class Transformation> void Object<Transformation>::setClean(const std::vector<AbstractObject<Transformation::Dimensions, typename Transformation::Type>*>& objects) const {
    std::vector<Object<Transformation>*> castObjects(objects.size());
    for(std::size_t i = 0; i != objects.size(); ++i)
        /** @todo Ensure this doesn't crash, somehow */
        castObjects[i] = static_cast<Object<Transformation>*>(objects[i]);

    setClean(std::move(castObjects));
}

template<class Transformation> void Object<Transformation>::setClean(std::vector<Object<Transformation>*> objects) {
    /* Remove all clean objects from the list */
    auto firstClean = std::remove_if(objects.begin(), objects.end(), [](Object<Transformation>* o) { return !o->isDirty(); });
    objects.erase(firstClean, objects.end());

    /* No dirty objects left, done */
    if(objects.empty()) return;

    /* Compute absolute transformations */
    Scene<Transformation>* scene = objects[0]->scene();
    CORRADE_ASSERT(scene, "Object::setClean(): objects must be part of some scene", );
    std::vector<typename Transformation::DataType> transformations(scene->transformations(objects));

    /* Go through all objects and clean them */
    for(std::size_t i = 0; i != objects.size(); ++i)
        objects[i]->setClean(transformations[i]);
}

template<class Transformation> void Object<Transformation>::setClean(const typename Transformation::DataType& absoluteTransformation) {
    /* "Lazy storage" for transformation matrix and inverted transformation matrix */
    typedef typename AbstractFeature<Transformation::Dimensions, typename Transformation::Type>::CachedTransformation CachedTransformation;
    typename AbstractFeature<Transformation::Dimensions, typename Transformation::Type>::CachedTransformations cached;
    typename DimensionTraits<Transformation::Dimensions, typename Transformation::Type>::MatrixType
        matrix, invertedMatrix;

    /* Clean all features */
    for(AbstractFeature<Transformation::Dimensions, typename Transformation::Type>* i = this->firstFeature(); i; i = i->nextFeature()) {
        /* Cached absolute transformation, compute it if it wasn't
            computed already */
        if(i->cachedTransformations() & CachedTransformation::Absolute) {
            if(!(cached & CachedTransformation::Absolute)) {
                cached |= CachedTransformation::Absolute;
                matrix = Transformation::toMatrix(absoluteTransformation);
            }

            i->clean(matrix);
        }

        /* Cached inverse absolute transformation, compute it if it wasn't
            computed already */
        if(i->cachedTransformations() & CachedTransformation::InvertedAbsolute) {
            if(!(cached & CachedTransformation::InvertedAbsolute)) {
                cached |= CachedTransformation::InvertedAbsolute;
                invertedMatrix = Transformation::toMatrix(Transformation::inverted(absoluteTransformation));
            }

            i->cleanInverted(invertedMatrix);
        }
    }

    /* Mark object as clean */
    flags &= ~Flag::Dirty;
}

}}

#endif
<commit_msg>SceneGraph: fixed Object::setClean().<commit_after>#ifndef Magnum_SceneGraph_Object_hpp
#define Magnum_SceneGraph_Object_hpp
/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

/** @file
 * @brief @ref compilation-speedup-hpp "Template implementation" for Object.h
 */

#include "AbstractTransformation.h"
#include "Object.h"

#include <algorithm>
#include <stack>

#include "Scene.h"

namespace Magnum { namespace SceneGraph {

template<UnsignedInt dimensions, class T> AbstractObject<dimensions, T>::AbstractObject() {}
template<UnsignedInt dimensions, class T> AbstractObject<dimensions, T>::~AbstractObject() {}

template<UnsignedInt dimensions, class T> inline AbstractTransformation<dimensions, T>::AbstractTransformation() {}
template<UnsignedInt dimensions, class T> inline AbstractTransformation<dimensions, T>::~AbstractTransformation() {}

template<class Transformation> Scene<Transformation>* Object<Transformation>::scene() {
    return static_cast<Scene<Transformation>*>(sceneObject());
}

template<class Transformation> const Scene<Transformation>* Object<Transformation>::scene() const {
    return static_cast<const Scene<Transformation>*>(sceneObject());
}

template<class Transformation> Object<Transformation>* Object<Transformation>::sceneObject() {
    Object<Transformation>* p(this);
    while(p && !p->isScene()) p = p->parent();
    return p;
}

template<class Transformation> const Object<Transformation>* Object<Transformation>::sceneObject() const {
    const Object<Transformation>* p(this);
    while(p && !p->isScene()) p = p->parent();
    return p;
}

template<class Transformation> Object<Transformation>* Object<Transformation>::setParent(Object<Transformation>* parent) {
    /* Skip if parent is already parent or this is scene (which cannot have parent) */
    /** @todo Assert for setting parent to scene */
    if(this->parent() == parent || isScene()) return this;

    /* Object cannot be parented to its child */
    Object<Transformation>* p = parent;
    while(p) {
        /** @todo Assert for this */
        if(p == this) return this;
        p = p->parent();
    }

    /* Remove the object from old parent children list */
    if(this->parent()) this->parent()->Corrade::Containers::template LinkedList<Object<Transformation>>::cut(this);

    /* Add the object to list of new parent */
    if(parent) parent->Corrade::Containers::LinkedList<Object<Transformation>>::insert(this);

    setDirty();
    return this;
}

template<class Transformation> typename Transformation::DataType Object<Transformation>::absoluteTransformation() const {
    if(!parent()) return Transformation::transformation();
    return Transformation::compose(parent()->absoluteTransformation(), Transformation::transformation());
}

template<class Transformation> void Object<Transformation>::setDirty() {
    /* The transformation of this object (and all children) is already dirty,
       nothing to do */
    if(flags & Flag::Dirty) return;

    Object<Transformation>* self = static_cast<Object<Transformation>*>(this);

    /* Make all features dirty */
    for(AbstractFeature<Transformation::Dimensions, typename Transformation::Type>* i = self->firstFeature(); i; i = i->nextFeature())
        i->markDirty();

    /* Make all children dirty */
    for(Object<Transformation>* i = self->firstChild(); i; i = i->nextSibling())
        i->setDirty();

    /* Mark object as dirty */
    flags |= Flag::Dirty;
}

template<class Transformation> void Object<Transformation>::setClean() {
    /* The object (and all its parents) are already clean, nothing to do */
    if(!(flags & Flag::Dirty)) return;

    /* Collect all parents, compute base transformation */
    std::stack<Object<Transformation>*> objects;
    typename Transformation::DataType absoluteTransformation;
    Object<Transformation>* p = static_cast<Object<Transformation>*>(this);
    for(;;) {
        objects.push(p);

        p = p->parent();

        /* On root object, base transformation is identity */
        if(!p) break;

        /* Parent object is clean, base transformation is its absolute
           transformation */
        if(!p->isDirty()) {
            absoluteTransformation = p->absoluteTransformation();
            break;
        }
    }

    /* Clean features on every collected object, going down from root object */
    while(!objects.empty()) {
        Object<Transformation>* o = objects.top();
        objects.pop();

        /* Compose transformation and clean object */
        absoluteTransformation = Transformation::compose(absoluteTransformation, o->transformation());
        o->setClean(absoluteTransformation);
    }
}

template<class Transformation> std::vector<typename DimensionTraits<Transformation::Dimensions, typename Transformation::Type>::MatrixType> Object<Transformation>::transformationMatrices(const std::vector<AbstractObject<Transformation::Dimensions, typename Transformation::Type>*>& objects, const typename DimensionTraits<Transformation::Dimensions, typename Transformation::Type>::MatrixType& initialTransformationMatrix) const {
    std::vector<Object<Transformation>*> castObjects(objects.size());
    for(std::size_t i = 0; i != objects.size(); ++i)
        /** @todo Ensure this doesn't crash, somehow */
        castObjects[i] = static_cast<Object<Transformation>*>(objects[i]);

    std::vector<typename Transformation::DataType> transformations = this->transformations(std::move(castObjects), Transformation::fromMatrix(initialTransformationMatrix));
    std::vector<typename DimensionTraits<Transformation::Dimensions, typename Transformation::Type>::MatrixType> transformationMatrices(transformations.size());
    for(std::size_t i = 0; i != objects.size(); ++i)
        transformationMatrices[i] = Transformation::toMatrix(transformations[i]);

    return transformationMatrices;
}

/*
Computing absolute transformations for given list of objects

The goal is to compute absolute transformation only once for each object
involved. Objects contained in the subtree specified by `object` list are
divided into two groups:
 - "joints", which are either part of `object` list or they have more than one
   child in the subtree
 - "non-joints", i.e. paths between joints

Then for all joints their transformation (relative to parent joint) is
computed and recursively concatenated together. Resulting transformations for
joints which were originally in `object` list is then returned.
*/
template<class Transformation> std::vector<typename Transformation::DataType> Object<Transformation>::transformations(std::vector<Object<Transformation>*> objects, const typename Transformation::DataType& initialTransformation) const {
    CORRADE_ASSERT(objects.size() < 0xFFFFu, "SceneGraph::Object::transformations(): too large scene", {});

    /* Remember object count for later */
    std::size_t objectCount = objects.size();

    /* Mark all original objects as joints and create initial list of joints
       from them */
    for(std::size_t i = 0; i != objects.size(); ++i) {
        /* Multiple occurences of one object in the array, don't overwrite it
           with different counter */
        if(objects[i]->counter != 0xFFFFu) continue;

        objects[i]->counter = i;
        objects[i]->flags |= Flag::Joint;
    }
    std::vector<Object<Transformation>*> jointObjects(objects);

    /* Scene object */
    const Scene<Transformation>* scene = this->scene();

    /* Nearest common ancestor not yet implemented - assert this is done on scene */
    CORRADE_ASSERT(scene == this, "SceneGraph::Object::transformationMatrices(): currently implemented only for Scene", {});

    /* Mark all objects up the hierarchy as visited */
    auto it = objects.begin();
    while(!objects.empty()) {
        /* Already visited, remove and continue to next (duplicate occurence) */
        if((*it)->flags & Flag::Visited) {
            it = objects.erase(it);
            continue;
        }

        /* Mark the object as visited */
        (*it)->flags |= Flag::Visited;

        Object<Transformation>* parent = (*it)->parent();

        /* If this is root object, remove from list */
        if(!parent) {
            CORRADE_ASSERT(*it == scene, "SceneGraph::Object::transformations(): the objects are not part of the same tree", {});
            it = objects.erase(it);

        /* Parent is an joint or already visited - remove current from list */
        } else if(parent->flags & (Flag::Visited|Flag::Joint)) {
            it = objects.erase(it);

            /* If not already marked as joint, mark it as such and add it to
               list of joint objects */
            if(!(parent->flags & Flag::Joint)) {
                CORRADE_ASSERT(jointObjects.size() < 0xFFFFu,
                               "SceneGraph::Object::transformations(): too large scene", {});
                CORRADE_INTERNAL_ASSERT(parent->counter == 0xFFFFu);
                parent->counter = jointObjects.size();
                parent->flags |= Flag::Joint;
                jointObjects.push_back(parent);
            }

        /* Else go up the hierarchy */
        } else *it = parent;

        /* Cycle if reached end */
        if(it == objects.end()) it = objects.begin();
    }

    /* Array of absolute transformations in joints */
    std::vector<typename Transformation::DataType> jointTransformations(jointObjects.size());

    /* Compute transformations for all joints */
    for(std::size_t i = 0; i != jointTransformations.size(); ++i)
        computeJointTransformation(jointObjects, jointTransformations, i, initialTransformation);

    /* Copy transformation for second or next occurences from first occurence
       of duplicate object */
    for(std::size_t i = 0; i != objectCount; ++i) {
        if(jointObjects[i]->counter != i)
            jointTransformations[i] = jointTransformations[jointObjects[i]->counter];
    }

    /* All visited marks are now cleaned, clean joint marks and counters */
    for(auto i: jointObjects) {
        /* All not-already cleaned objects (...duplicate occurences) should
           have joint mark */
        CORRADE_INTERNAL_ASSERT(i->counter = 0xFFFFu || i->flags & Flag::Joint);
        i->flags &= ~Flag::Joint;
        i->counter = 0xFFFFu;
    }

    /* Shrink the array to contain only transformations of requested objects and return */
    jointTransformations.resize(objectCount);
    return jointTransformations;
}

template<class Transformation> typename Transformation::DataType Object<Transformation>::computeJointTransformation(const std::vector<Object<Transformation>*>& jointObjects, std::vector<typename Transformation::DataType>& jointTransformations, const std::size_t joint, const typename Transformation::DataType& initialTransformation) const {
    Object<Transformation>* o = jointObjects[joint];

    /* Transformation already computed ("unvisited" by this function before
       either due to recursion or duplicate object occurences), done */
    if(!(o->flags & Flag::Visited)) return jointTransformations[joint];

    /* Initialize transformation */
    jointTransformations[joint] = o->transformation();

    /* Go up until next joint or root */
    for(;;) {
        /* Clean visited mark */
        CORRADE_INTERNAL_ASSERT(o->flags & Flag::Visited);
        o->flags &= ~Flag::Visited;

        Object<Transformation>* parent = o->parent();

        /* Root object, compose transformation with initial, done */
        if(!parent) {
            CORRADE_INTERNAL_ASSERT(o->isScene());
            return (jointTransformations[joint] =
                Transformation::compose(initialTransformation, jointTransformations[joint]));

        /* Joint object, compose transformation with the joint, done */
        } else if(parent->flags & Flag::Joint) {
            return (jointTransformations[joint] =
                Transformation::compose(computeJointTransformation(jointObjects, jointTransformations, parent->counter, initialTransformation), jointTransformations[joint]));

        /* Else compose transformation with parent, go up the hierarchy */
        } else {
            jointTransformations[joint] = Transformation::compose(parent->transformation(), jointTransformations[joint]);
            o = parent;
        }
    }
}

template<class Transformation> void Object<Transformation>::setClean(const std::vector<AbstractObject<Transformation::Dimensions, typename Transformation::Type>*>& objects) const {
    std::vector<Object<Transformation>*> castObjects(objects.size());
    for(std::size_t i = 0; i != objects.size(); ++i)
        /** @todo Ensure this doesn't crash, somehow */
        castObjects[i] = static_cast<Object<Transformation>*>(objects[i]);

    setClean(std::move(castObjects));
}

template<class Transformation> void Object<Transformation>::setClean(std::vector<Object<Transformation>*> objects) {
    /* Remove all clean objects from the list */
    auto firstClean = std::remove_if(objects.begin(), objects.end(), [](Object<Transformation>* o) { return !o->isDirty(); });
    objects.erase(firstClean, objects.end());

    /* No dirty objects left, done */
    if(objects.empty()) return;

    /* Add non-clean parents to the list. Mark each added object as visited, so
       they aren't added more than once */
    for(std::size_t end = objects.size(), i = 0; i != end; ++i) {
        Object<Transformation>* o = objects[i];
        o->flags |= Flag::Visited;

        Object<Transformation>* parent = o->parent();
        while(parent && !(parent->flags & Flag::Visited) && parent->isDirty()) {
            objects.push_back(parent);
            parent = parent->parent();
        }
    }

    /* Cleanup all marks */
    for(auto o: objects) o->flags &= ~Flag::Visited;

    /* Compute absolute transformations */
    Scene<Transformation>* scene = objects[0]->scene();
    CORRADE_ASSERT(scene, "Object::setClean(): objects must be part of some scene", );
    std::vector<typename Transformation::DataType> transformations(scene->transformations(objects));

    /* Go through all objects and clean them */
    for(std::size_t i = 0; i != objects.size(); ++i)
        objects[i]->setClean(transformations[i]);
}

template<class Transformation> void Object<Transformation>::setClean(const typename Transformation::DataType& absoluteTransformation) {
    /* "Lazy storage" for transformation matrix and inverted transformation matrix */
    typedef typename AbstractFeature<Transformation::Dimensions, typename Transformation::Type>::CachedTransformation CachedTransformation;
    typename AbstractFeature<Transformation::Dimensions, typename Transformation::Type>::CachedTransformations cached;
    typename DimensionTraits<Transformation::Dimensions, typename Transformation::Type>::MatrixType
        matrix, invertedMatrix;

    /* Clean all features */
    for(AbstractFeature<Transformation::Dimensions, typename Transformation::Type>* i = this->firstFeature(); i; i = i->nextFeature()) {
        /* Cached absolute transformation, compute it if it wasn't
            computed already */
        if(i->cachedTransformations() & CachedTransformation::Absolute) {
            if(!(cached & CachedTransformation::Absolute)) {
                cached |= CachedTransformation::Absolute;
                matrix = Transformation::toMatrix(absoluteTransformation);
            }

            i->clean(matrix);
        }

        /* Cached inverse absolute transformation, compute it if it wasn't
            computed already */
        if(i->cachedTransformations() & CachedTransformation::InvertedAbsolute) {
            if(!(cached & CachedTransformation::InvertedAbsolute)) {
                cached |= CachedTransformation::InvertedAbsolute;
                invertedMatrix = Transformation::toMatrix(Transformation::inverted(absoluteTransformation));
            }

            i->cleanInverted(invertedMatrix);
        }
    }

    /* Mark object as clean */
    flags &= ~Flag::Dirty;
}

}}

#endif
<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include <array>
#include <vector>
#include <Containers/Array.h>

#include "Buffer.h"
#include "Context.h"
#include "Extensions.h"
#include "Test/AbstractOpenGLTester.h"

namespace Magnum { namespace Test {

class BufferGLTest: public AbstractOpenGLTester {
    public:
        explicit BufferGLTest();

        void construct();
        void label();
        void data();
        void map();
        #ifdef MAGNUM_TARGET_GLES2
        void mapSub();
        #endif
        void mapRange();
        void mapRangeExplicitFlush();
        #ifndef MAGNUM_TARGET_GLES2
        void copy();
        #endif
        #ifndef MAGNUM_TARGET_GLES2
        void invalidate();
        #endif
};

BufferGLTest::BufferGLTest() {
    addTests({&BufferGLTest::construct,
              &BufferGLTest::label,
              &BufferGLTest::data,
              &BufferGLTest::map,
              #ifdef MAGNUM_TARGET_GLES2
              &BufferGLTest::mapSub,
              #endif
              &BufferGLTest::mapRange,
              &BufferGLTest::mapRangeExplicitFlush,
              #ifndef MAGNUM_TARGET_GLES2
              &BufferGLTest::copy,
              #endif
              #ifndef MAGNUM_TARGET_GLES
              &BufferGLTest::invalidate
              #endif
              });
}

void BufferGLTest::construct() {
    Buffer buffer;
    MAGNUM_VERIFY_NO_ERROR();

    CORRADE_COMPARE(buffer.targetHint(), Buffer::Target::Array);

    CORRADE_COMPARE(buffer.size(), 0);
    MAGNUM_VERIFY_NO_ERROR();
}

void BufferGLTest::label() {
    /* No-Op version is tested in AbstractObjectGLTest */
    if(!Context::current()->isExtensionSupported<Extensions::GL::KHR::debug>() &&
       !Context::current()->isExtensionSupported<Extensions::GL::EXT::debug_label>())
        CORRADE_SKIP("Required extension is not available");

    Buffer buffer;
    CORRADE_COMPARE(buffer.label(), "");

    buffer.setLabel("MyBuffer");
    CORRADE_COMPARE(buffer.label(), "MyBuffer");

    MAGNUM_VERIFY_NO_ERROR();
}

void BufferGLTest::data() {
    Buffer buffer;

    /* Plain array */
    constexpr Int data[] = {2, 7, 5, 13, 25};
    buffer.setData({data, 5}, BufferUsage::StaticDraw);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /* STL vector */
    std::vector<Int> data2{2, 7, 5, 13, 25};
    buffer.setData(data2, BufferUsage::StaticDraw);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /* STL array */
    std::array<Int, 5> data3{{2, 7, 5, 13, 25}};
    buffer.setData(data3, BufferUsage::StaticDraw);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    const Containers::Array<Int> contents = buffer.data<Int>();
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(contents.size(), 5);
    CORRADE_COMPARE(contents[0], 2);
    CORRADE_COMPARE(contents[1], 7);
    CORRADE_COMPARE(contents[2], 5);
    CORRADE_COMPARE(contents[3], 13);
    CORRADE_COMPARE(contents[4], 25);
    #endif

    /* Plain array */
    constexpr Int subData[] = {125, 3, 15};
    buffer.setSubData(4, {subData, 3});
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /* STL vector */
    std::vector<Int> subData2{125, 3, 15};
    buffer.setSubData(4, subData2);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /* STL array */
    std::array<Int, 3> subData3{{125, 3, 15}};
    buffer.setSubData(4, subData3);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    const Containers::Array<Int> subContents = buffer.subData<Int>(4, 3);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(subContents.size(), 3);
    CORRADE_COMPARE(subContents[0], 125);
    CORRADE_COMPARE(subContents[1], 3);
    CORRADE_COMPARE(subContents[2], 15);
    #endif
}

void BufferGLTest::map() {
    #ifdef MAGNUM_TARGET_GLES2
    if(!Context::current()->isExtensionSupported<Extensions::GL::OES::mapbuffer>())
        CORRADE_SKIP(Extensions::GL::OES::mapbuffer::string() + std::string(" is not supported"));
    #endif
    Buffer buffer;

    constexpr char data[] = {2, 7, 5, 13, 25};
    buffer.setData(data, BufferUsage::StaticDraw);

    #ifndef MAGNUM_TARGET_GLES2
    char* contents = reinterpret_cast<char*>(buffer.map(Buffer::MapAccess::ReadWrite));
    #else
    char* contents = reinterpret_cast<char*>(buffer.map(Buffer::MapAccess::WriteOnly));
    #endif
    MAGNUM_VERIFY_NO_ERROR();

    CORRADE_VERIFY(contents);
    #ifndef MAGNUM_TARGET_GLES2
    CORRADE_COMPARE(contents[2], 5);
    #endif
    contents[3] = 107;

    CORRADE_VERIFY(buffer.unmap());
    MAGNUM_VERIFY_NO_ERROR();

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    Containers::Array<char> changedContents = buffer.data<char>();
    CORRADE_COMPARE(changedContents.size(), 5);
    CORRADE_COMPARE(changedContents[3], 107);
    #endif
}

#ifdef MAGNUM_TARGET_GLES2
void BufferGLTest::mapSub() {
    if(!Context::current()->isExtensionSupported<Extensions::GL::CHROMIUM::map_sub>())
        CORRADE_SKIP(Extensions::GL::CHROMIUM::map_sub::string() + std::string(" is not supported"));

    Buffer buffer;

    constexpr char data[] = {2, 7, 5, 13, 25};
    buffer.setData(data, BufferUsage::StaticDraw);

    char* contents = reinterpret_cast<char*>(buffer.mapSub(1, 4, Buffer::MapAccess::WriteOnly));
    MAGNUM_VERIFY_NO_ERROR();

    CORRADE_VERIFY(contents);
    contents[3] = 107;

    buffer.unmapSub();
    MAGNUM_VERIFY_NO_ERROR();

    /** @todo How to verify the contents in ES? */
}
#endif

void BufferGLTest::mapRange() {
    #ifndef MAGNUM_TARGET_GLES2
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::map_buffer_range>())
        CORRADE_SKIP(Extensions::GL::ARB::map_buffer_range::string() + std::string(" is not supported"));
    #else
    if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::map_buffer_range>())
        CORRADE_SKIP(Extensions::GL::EXT::map_buffer_range::string() + std::string(" is not supported"));
    #endif

    constexpr char data[] = {2, 7, 5, 13, 25};
    Buffer buffer;
    buffer.setData(data, BufferUsage::StaticDraw);

    char* contents = reinterpret_cast<char*>(buffer.map(1, 4, Buffer::MapFlag::Read|Buffer::MapFlag::Write));
    MAGNUM_VERIFY_NO_ERROR();

    CORRADE_VERIFY(contents);
    CORRADE_COMPARE(contents[2], 13);
    contents[3] = 107;

    CORRADE_VERIFY(buffer.unmap());
    MAGNUM_VERIFY_NO_ERROR();

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    Containers::Array<char> changedContents = buffer.data<char>();
    CORRADE_COMPARE(changedContents.size(), 5);
    CORRADE_COMPARE(changedContents[4], 107);
    #endif
}

void BufferGLTest::mapRangeExplicitFlush() {
    #ifndef MAGNUM_TARGET_GLES2
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::map_buffer_range>())
        CORRADE_SKIP(Extensions::GL::ARB::map_buffer_range::string() + std::string(" is not supported"));
    #else
    if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::map_buffer_range>())
        CORRADE_SKIP(Extensions::GL::EXT::map_buffer_range::string() + std::string(" is not supported"));
    #endif

    constexpr char data[] = {2, 7, 5, 13, 25};
    Buffer buffer;
    buffer.setData(data, BufferUsage::StaticDraw);

    /* Map, set byte, don't flush and unmap */
    char* contents = reinterpret_cast<char*>(buffer.map(1, 4, Buffer::MapFlag::Write|Buffer::MapFlag::FlushExplicit));
    CORRADE_VERIFY(contents);
    contents[2] = 99;
    CORRADE_VERIFY(buffer.unmap());
    MAGNUM_VERIFY_NO_ERROR();

    /* Unflushed range _might_ not be changed, thus nothing to test */

    /* Map, set byte, flush and unmap */
    contents = reinterpret_cast<char*>(buffer.map(1, 4, Buffer::MapFlag::Write|Buffer::MapFlag::FlushExplicit));
    CORRADE_VERIFY(contents);
    contents[3] = 107;
    buffer.flushMappedRange(3, 1);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_VERIFY(buffer.unmap());
    MAGNUM_VERIFY_NO_ERROR();

    /* Flushed range should be changed */
    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    Containers::Array<char> changedContents = buffer.data<char>();
    CORRADE_COMPARE(changedContents.size(), 5);
    CORRADE_COMPARE(changedContents[4], 107);
    #endif
}

#ifndef MAGNUM_TARGET_GLES2
void BufferGLTest::copy() {
    Buffer buffer1;
    constexpr char data[] = {2, 7, 5, 13, 25};
    buffer1.setData(data, BufferUsage::StaticDraw);

    Buffer buffer2;
    buffer2.setData({nullptr, 5}, BufferUsage::StaticDraw);

    Buffer::copy(buffer1, buffer2, 1, 2, 3);
    MAGNUM_VERIFY_NO_ERROR();

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    const Containers::Array<char> subContents = buffer2.subData<char>(2, 3);
    CORRADE_COMPARE(subContents.size(), 3);
    CORRADE_COMPARE(subContents[0], 7);
    CORRADE_COMPARE(subContents[1], 5);
    CORRADE_COMPARE(subContents[2], 13);
    #endif
}
#endif

#ifndef MAGNUM_TARGET_GLES
void BufferGLTest::invalidate() {
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::invalidate_subdata>())
        CORRADE_SKIP(Extensions::GL::ARB::invalidate_subdata::string() + std::string(" is not supported"));

    Buffer buffer;
    constexpr char data[] = {2, 7, 5, 13, 25};
    buffer.setData(data, BufferUsage::StaticDraw);

    /* Just test that no errors are emitted */

    buffer.invalidateSubData(3, 2);
    MAGNUM_VERIFY_NO_ERROR();

    buffer.invalidateData();
    MAGNUM_VERIFY_NO_ERROR();
}
#endif

}}

CORRADE_TEST_MAIN(Magnum::Test::BufferGLTest)
<commit_msg>Testing Buffer move construction and assignment.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include <array>
#include <vector>
#include <Containers/Array.h>

#include "Buffer.h"
#include "Context.h"
#include "Extensions.h"
#include "Test/AbstractOpenGLTester.h"

namespace Magnum { namespace Test {

class BufferGLTest: public AbstractOpenGLTester {
    public:
        explicit BufferGLTest();

        void construct();
        void constructCopy();
        void constructMove();

        void label();
        void data();
        void map();
        #ifdef MAGNUM_TARGET_GLES2
        void mapSub();
        #endif
        void mapRange();
        void mapRangeExplicitFlush();
        #ifndef MAGNUM_TARGET_GLES2
        void copy();
        #endif
        #ifndef MAGNUM_TARGET_GLES2
        void invalidate();
        #endif
};

BufferGLTest::BufferGLTest() {
    addTests({&BufferGLTest::construct,
              &BufferGLTest::label,
              &BufferGLTest::data,
              &BufferGLTest::map,
              #ifdef MAGNUM_TARGET_GLES2
              &BufferGLTest::mapSub,
              #endif
              &BufferGLTest::mapRange,
              &BufferGLTest::mapRangeExplicitFlush,
              #ifndef MAGNUM_TARGET_GLES2
              &BufferGLTest::copy,
              #endif
              #ifndef MAGNUM_TARGET_GLES
              &BufferGLTest::invalidate
              #endif
              });
}

void BufferGLTest::construct() {
    {
        Buffer buffer;

        MAGNUM_VERIFY_NO_ERROR();
        CORRADE_VERIFY(buffer.id() > 0);
        CORRADE_COMPARE(buffer.targetHint(), Buffer::Target::Array);
        CORRADE_COMPARE(buffer.size(), 0);
    }

    MAGNUM_VERIFY_NO_ERROR();
}

void BufferGLTest::constructCopy() {
     CORRADE_VERIFY(!(std::is_constructible<Buffer, const Buffer&>{}));
     CORRADE_VERIFY(!(std::is_assignable<Buffer, const Buffer&>{}));
}

void BufferGLTest::constructMove() {
    Buffer a;
    const Int id = a.id();

    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_VERIFY(id > 0);

    Buffer b(std::move(a));

    CORRADE_COMPARE(a.id(), 0);
    CORRADE_COMPARE(b.id(), id);

    Buffer c;
    const Int cId = c.id();
    c = std::move(b);

    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_VERIFY(cId > 0);
    CORRADE_COMPARE(b.id(), cId);
    CORRADE_COMPARE(c.id(), id);
}

void BufferGLTest::label() {
    /* No-Op version is tested in AbstractObjectGLTest */
    if(!Context::current()->isExtensionSupported<Extensions::GL::KHR::debug>() &&
       !Context::current()->isExtensionSupported<Extensions::GL::EXT::debug_label>())
        CORRADE_SKIP("Required extension is not available");

    Buffer buffer;
    CORRADE_COMPARE(buffer.label(), "");

    buffer.setLabel("MyBuffer");
    CORRADE_COMPARE(buffer.label(), "MyBuffer");

    MAGNUM_VERIFY_NO_ERROR();
}

void BufferGLTest::data() {
    Buffer buffer;

    /* Plain array */
    constexpr Int data[] = {2, 7, 5, 13, 25};
    buffer.setData({data, 5}, BufferUsage::StaticDraw);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /* STL vector */
    std::vector<Int> data2{2, 7, 5, 13, 25};
    buffer.setData(data2, BufferUsage::StaticDraw);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /* STL array */
    std::array<Int, 5> data3{{2, 7, 5, 13, 25}};
    buffer.setData(data3, BufferUsage::StaticDraw);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    const Containers::Array<Int> contents = buffer.data<Int>();
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(contents.size(), 5);
    CORRADE_COMPARE(contents[0], 2);
    CORRADE_COMPARE(contents[1], 7);
    CORRADE_COMPARE(contents[2], 5);
    CORRADE_COMPARE(contents[3], 13);
    CORRADE_COMPARE(contents[4], 25);
    #endif

    /* Plain array */
    constexpr Int subData[] = {125, 3, 15};
    buffer.setSubData(4, {subData, 3});
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /* STL vector */
    std::vector<Int> subData2{125, 3, 15};
    buffer.setSubData(4, subData2);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /* STL array */
    std::array<Int, 3> subData3{{125, 3, 15}};
    buffer.setSubData(4, subData3);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(buffer.size(), 5*4);

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    const Containers::Array<Int> subContents = buffer.subData<Int>(4, 3);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_COMPARE(subContents.size(), 3);
    CORRADE_COMPARE(subContents[0], 125);
    CORRADE_COMPARE(subContents[1], 3);
    CORRADE_COMPARE(subContents[2], 15);
    #endif
}

void BufferGLTest::map() {
    #ifdef MAGNUM_TARGET_GLES2
    if(!Context::current()->isExtensionSupported<Extensions::GL::OES::mapbuffer>())
        CORRADE_SKIP(Extensions::GL::OES::mapbuffer::string() + std::string(" is not supported"));
    #endif
    Buffer buffer;

    constexpr char data[] = {2, 7, 5, 13, 25};
    buffer.setData(data, BufferUsage::StaticDraw);

    #ifndef MAGNUM_TARGET_GLES2
    char* contents = reinterpret_cast<char*>(buffer.map(Buffer::MapAccess::ReadWrite));
    #else
    char* contents = reinterpret_cast<char*>(buffer.map(Buffer::MapAccess::WriteOnly));
    #endif
    MAGNUM_VERIFY_NO_ERROR();

    CORRADE_VERIFY(contents);
    #ifndef MAGNUM_TARGET_GLES2
    CORRADE_COMPARE(contents[2], 5);
    #endif
    contents[3] = 107;

    CORRADE_VERIFY(buffer.unmap());
    MAGNUM_VERIFY_NO_ERROR();

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    Containers::Array<char> changedContents = buffer.data<char>();
    CORRADE_COMPARE(changedContents.size(), 5);
    CORRADE_COMPARE(changedContents[3], 107);
    #endif
}

#ifdef MAGNUM_TARGET_GLES2
void BufferGLTest::mapSub() {
    if(!Context::current()->isExtensionSupported<Extensions::GL::CHROMIUM::map_sub>())
        CORRADE_SKIP(Extensions::GL::CHROMIUM::map_sub::string() + std::string(" is not supported"));

    Buffer buffer;

    constexpr char data[] = {2, 7, 5, 13, 25};
    buffer.setData(data, BufferUsage::StaticDraw);

    char* contents = reinterpret_cast<char*>(buffer.mapSub(1, 4, Buffer::MapAccess::WriteOnly));
    MAGNUM_VERIFY_NO_ERROR();

    CORRADE_VERIFY(contents);
    contents[3] = 107;

    buffer.unmapSub();
    MAGNUM_VERIFY_NO_ERROR();

    /** @todo How to verify the contents in ES? */
}
#endif

void BufferGLTest::mapRange() {
    #ifndef MAGNUM_TARGET_GLES2
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::map_buffer_range>())
        CORRADE_SKIP(Extensions::GL::ARB::map_buffer_range::string() + std::string(" is not supported"));
    #else
    if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::map_buffer_range>())
        CORRADE_SKIP(Extensions::GL::EXT::map_buffer_range::string() + std::string(" is not supported"));
    #endif

    constexpr char data[] = {2, 7, 5, 13, 25};
    Buffer buffer;
    buffer.setData(data, BufferUsage::StaticDraw);

    char* contents = reinterpret_cast<char*>(buffer.map(1, 4, Buffer::MapFlag::Read|Buffer::MapFlag::Write));
    MAGNUM_VERIFY_NO_ERROR();

    CORRADE_VERIFY(contents);
    CORRADE_COMPARE(contents[2], 13);
    contents[3] = 107;

    CORRADE_VERIFY(buffer.unmap());
    MAGNUM_VERIFY_NO_ERROR();

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    Containers::Array<char> changedContents = buffer.data<char>();
    CORRADE_COMPARE(changedContents.size(), 5);
    CORRADE_COMPARE(changedContents[4], 107);
    #endif
}

void BufferGLTest::mapRangeExplicitFlush() {
    #ifndef MAGNUM_TARGET_GLES2
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::map_buffer_range>())
        CORRADE_SKIP(Extensions::GL::ARB::map_buffer_range::string() + std::string(" is not supported"));
    #else
    if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::map_buffer_range>())
        CORRADE_SKIP(Extensions::GL::EXT::map_buffer_range::string() + std::string(" is not supported"));
    #endif

    constexpr char data[] = {2, 7, 5, 13, 25};
    Buffer buffer;
    buffer.setData(data, BufferUsage::StaticDraw);

    /* Map, set byte, don't flush and unmap */
    char* contents = reinterpret_cast<char*>(buffer.map(1, 4, Buffer::MapFlag::Write|Buffer::MapFlag::FlushExplicit));
    CORRADE_VERIFY(contents);
    contents[2] = 99;
    CORRADE_VERIFY(buffer.unmap());
    MAGNUM_VERIFY_NO_ERROR();

    /* Unflushed range _might_ not be changed, thus nothing to test */

    /* Map, set byte, flush and unmap */
    contents = reinterpret_cast<char*>(buffer.map(1, 4, Buffer::MapFlag::Write|Buffer::MapFlag::FlushExplicit));
    CORRADE_VERIFY(contents);
    contents[3] = 107;
    buffer.flushMappedRange(3, 1);
    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_VERIFY(buffer.unmap());
    MAGNUM_VERIFY_NO_ERROR();

    /* Flushed range should be changed */
    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    Containers::Array<char> changedContents = buffer.data<char>();
    CORRADE_COMPARE(changedContents.size(), 5);
    CORRADE_COMPARE(changedContents[4], 107);
    #endif
}

#ifndef MAGNUM_TARGET_GLES2
void BufferGLTest::copy() {
    Buffer buffer1;
    constexpr char data[] = {2, 7, 5, 13, 25};
    buffer1.setData(data, BufferUsage::StaticDraw);

    Buffer buffer2;
    buffer2.setData({nullptr, 5}, BufferUsage::StaticDraw);

    Buffer::copy(buffer1, buffer2, 1, 2, 3);
    MAGNUM_VERIFY_NO_ERROR();

    /** @todo How to verify the contents in ES? */
    #ifndef MAGNUM_TARGET_GLES
    const Containers::Array<char> subContents = buffer2.subData<char>(2, 3);
    CORRADE_COMPARE(subContents.size(), 3);
    CORRADE_COMPARE(subContents[0], 7);
    CORRADE_COMPARE(subContents[1], 5);
    CORRADE_COMPARE(subContents[2], 13);
    #endif
}
#endif

#ifndef MAGNUM_TARGET_GLES
void BufferGLTest::invalidate() {
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::invalidate_subdata>())
        CORRADE_SKIP(Extensions::GL::ARB::invalidate_subdata::string() + std::string(" is not supported"));

    Buffer buffer;
    constexpr char data[] = {2, 7, 5, 13, 25};
    buffer.setData(data, BufferUsage::StaticDraw);

    /* Just test that no errors are emitted */

    buffer.invalidateSubData(3, 2);
    MAGNUM_VERIFY_NO_ERROR();

    buffer.invalidateData();
    MAGNUM_VERIFY_NO_ERROR();
}
#endif

}}

CORRADE_TEST_MAIN(Magnum::Test::BufferGLTest)
<|endoftext|>