<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 "components/autofill/content/browser/wallet/wallet_service_url.h"

#include <string>

#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "google_apis/gaia/gaia_urls.h"
#include "googleurl/src/gurl.h"
#include "net/base/url_util.h"

namespace autofill {
namespace {

const char kProdWalletServiceUrl[] = "https://wallet.google.com/";

// TODO(ahutter): Remove this once production is ready.
const char kSandboxWalletServiceUrl[] =
    "https://payments-form-dogfood.sandbox.google.com/";

// TODO(ahutter): Remove this once production is ready.
const char kSandboxWalletSecureServiceUrl[] =
    "https://wallet-web.sandbox.google.com/";

bool IsWalletProductionEnabled() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  return command_line.HasSwitch(switches::kWalletServiceUseProd) ||
         base::FieldTrialList::FindFullName("WalletProductionService") == "Yes";
}

GURL GetWalletHostUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string wallet_service_hostname =
      command_line.GetSwitchValueASCII(switches::kWalletServiceUrl);
  if (!wallet_service_hostname.empty())
    return GURL(wallet_service_hostname);
  if (IsWalletProductionEnabled())
    return GURL(kProdWalletServiceUrl);
  return GURL(kSandboxWalletServiceUrl);
}

GURL GetBaseWalletUrl() {
  return GetWalletHostUrl().Resolve("online/v2/");
}

GURL GetBaseAutocheckoutUrl() {
  return GetBaseWalletUrl().Resolve("wallet/autocheckout/v1/");
}

GURL GetBaseSecureUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string wallet_secure_url =
      command_line.GetSwitchValueASCII(switches::kWalletSecureServiceUrl);
  if (!wallet_secure_url.empty())
    return GURL(wallet_secure_url);
  if (IsWalletProductionEnabled())
    return GURL(kProdWalletServiceUrl);
  return GURL(kSandboxWalletSecureServiceUrl);
}

}  // namespace

namespace wallet {

GURL GetGetWalletItemsUrl() {
  return GetBaseAutocheckoutUrl().Resolve("getWalletItemsJwtless");
}

GURL GetGetFullWalletUrl() {
  return GetBaseAutocheckoutUrl().Resolve("getFullWalletJwtless");
}

GURL GetManageInstrumentsUrl() {
  return GetBaseSecureUrl().Resolve("manage/w/0/#paymentMethods:");
}

GURL GetManageAddressesUrl() {
  return GetBaseSecureUrl().Resolve("manage/w/0/#settings:addresses");
}

GURL GetAcceptLegalDocumentsUrl() {
  return GetBaseAutocheckoutUrl().Resolve("acceptLegalDocument");
}

GURL GetAuthenticateInstrumentUrl() {
  return GetBaseAutocheckoutUrl().Resolve("authenticateInstrument");
}

GURL GetSendStatusUrl() {
  return GetBaseAutocheckoutUrl().Resolve("reportStatus");
}

GURL GetSaveToWalletUrl() {
  return GetBaseAutocheckoutUrl().Resolve("saveToWallet");
}

GURL GetPassiveAuthUrl() {
  return GetBaseWalletUrl().Resolve("passiveauth?isChromePayments=true");
}

GURL GetEncryptionUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  // TODO(ahutter): Stop checking these switches once we switch over to prod.
  if (IsWalletProductionEnabled() ||
      command_line.HasSwitch(switches::kWalletServiceUrl)) {
    return GetWalletHostUrl().Resolve(
        "online-secure/temporarydata/cvv?s7e=cvv");
  } else {
    return GetBaseSecureUrl().Resolve(
        "online-secure/temporarydata/cvv?s7e=cvv");
  }
}

GURL GetEscrowUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  // TODO(ahutter): Stop checking these switches once we switch over to prod.
  if (IsWalletProductionEnabled() ||
      command_line.HasSwitch(switches::kWalletServiceUrl)) {
    return GetBaseSecureUrl().Resolve("dehEfe?s7e=cardNumber%3Bcvv");
  } else {
    return GetBaseSecureUrl().Resolve("checkout/dehEfe?s7e=cardNumber%3Bcvv");
  }
}

GURL GetSignInUrl() {
  GURL url(GaiaUrls::GetInstance()->service_login_url());
  url = net::AppendQueryParameter(url, "service", "toolbar");
  url = net::AppendQueryParameter(url, "nui", "1");
  url = net::AppendQueryParameter(url,
                                  "continue",
                                  GetSignInContinueUrl().spec());
  return url;
}

// The continue url portion of the sign-in URL.
GURL GetSignInContinueUrl() {
  return GetPassiveAuthUrl();
}

bool IsSignInContinueUrl(const GURL& url) {
  GURL final_url = wallet::GetSignInContinueUrl();
  return url.SchemeIsSecure() &&
         url.host() == final_url.host() &&
         url.path() == final_url.path();
}

bool IsUsingProd() {
  return GetWalletHostUrl() == GURL(kProdWalletServiceUrl);
}

}  // namespace wallet
}  // namespace autofill
<commit_msg>Talk to production wallet server when Autocheckout experiment is enabled<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 "components/autofill/content/browser/wallet/wallet_service_url.h"

#include <string>

#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "google_apis/gaia/gaia_urls.h"
#include "googleurl/src/gurl.h"
#include "net/base/url_util.h"

namespace autofill {
namespace {

const char kProdWalletServiceUrl[] = "https://wallet.google.com/";

// TODO(ahutter): Remove this once production is ready.
const char kSandboxWalletServiceUrl[] =
    "https://payments-form-dogfood.sandbox.google.com/";

// TODO(ahutter): Remove this once production is ready.
const char kSandboxWalletSecureServiceUrl[] =
    "https://wallet-web.sandbox.google.com/";

bool IsWalletProductionEnabled() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  return command_line.HasSwitch(switches::kWalletServiceUseProd) ||
      base::FieldTrialList::FindFullName("WalletProductionService") == "Yes" ||
      base::FieldTrialList::FindFullName("Autocheckout") == "Yes";
}

GURL GetWalletHostUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string wallet_service_hostname =
      command_line.GetSwitchValueASCII(switches::kWalletServiceUrl);
  if (!wallet_service_hostname.empty())
    return GURL(wallet_service_hostname);
  if (IsWalletProductionEnabled())
    return GURL(kProdWalletServiceUrl);
  return GURL(kSandboxWalletServiceUrl);
}

GURL GetBaseWalletUrl() {
  return GetWalletHostUrl().Resolve("online/v2/");
}

GURL GetBaseAutocheckoutUrl() {
  return GetBaseWalletUrl().Resolve("wallet/autocheckout/v1/");
}

GURL GetBaseSecureUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string wallet_secure_url =
      command_line.GetSwitchValueASCII(switches::kWalletSecureServiceUrl);
  if (!wallet_secure_url.empty())
    return GURL(wallet_secure_url);
  if (IsWalletProductionEnabled())
    return GURL(kProdWalletServiceUrl);
  return GURL(kSandboxWalletSecureServiceUrl);
}

}  // namespace

namespace wallet {

GURL GetGetWalletItemsUrl() {
  return GetBaseAutocheckoutUrl().Resolve("getWalletItemsJwtless");
}

GURL GetGetFullWalletUrl() {
  return GetBaseAutocheckoutUrl().Resolve("getFullWalletJwtless");
}

GURL GetManageInstrumentsUrl() {
  return GetBaseSecureUrl().Resolve("manage/w/0/#paymentMethods:");
}

GURL GetManageAddressesUrl() {
  return GetBaseSecureUrl().Resolve("manage/w/0/#settings:addresses");
}

GURL GetAcceptLegalDocumentsUrl() {
  return GetBaseAutocheckoutUrl().Resolve("acceptLegalDocument");
}

GURL GetAuthenticateInstrumentUrl() {
  return GetBaseAutocheckoutUrl().Resolve("authenticateInstrument");
}

GURL GetSendStatusUrl() {
  return GetBaseAutocheckoutUrl().Resolve("reportStatus");
}

GURL GetSaveToWalletUrl() {
  return GetBaseAutocheckoutUrl().Resolve("saveToWallet");
}

GURL GetPassiveAuthUrl() {
  return GetBaseWalletUrl().Resolve("passiveauth?isChromePayments=true");
}

GURL GetEncryptionUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  // TODO(ahutter): Stop checking these switches once we switch over to prod.
  if (IsWalletProductionEnabled() ||
      command_line.HasSwitch(switches::kWalletServiceUrl)) {
    return GetWalletHostUrl().Resolve(
        "online-secure/temporarydata/cvv?s7e=cvv");
  } else {
    return GetBaseSecureUrl().Resolve(
        "online-secure/temporarydata/cvv?s7e=cvv");
  }
}

GURL GetEscrowUrl() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  // TODO(ahutter): Stop checking these switches once we switch over to prod.
  if (IsWalletProductionEnabled() ||
      command_line.HasSwitch(switches::kWalletServiceUrl)) {
    return GetBaseSecureUrl().Resolve("dehEfe?s7e=cardNumber%3Bcvv");
  } else {
    return GetBaseSecureUrl().Resolve("checkout/dehEfe?s7e=cardNumber%3Bcvv");
  }
}

GURL GetSignInUrl() {
  GURL url(GaiaUrls::GetInstance()->service_login_url());
  url = net::AppendQueryParameter(url, "service", "toolbar");
  url = net::AppendQueryParameter(url, "nui", "1");
  url = net::AppendQueryParameter(url,
                                  "continue",
                                  GetSignInContinueUrl().spec());
  return url;
}

// The continue url portion of the sign-in URL.
GURL GetSignInContinueUrl() {
  return GetPassiveAuthUrl();
}

bool IsSignInContinueUrl(const GURL& url) {
  GURL final_url = wallet::GetSignInContinueUrl();
  return url.SchemeIsSecure() &&
         url.host() == final_url.host() &&
         url.path() == final_url.path();
}

bool IsUsingProd() {
  return GetWalletHostUrl() == GURL(kProdWalletServiceUrl);
}

}  // namespace wallet
}  // namespace autofill
<|endoftext|>


<commit_before>#include "nova_renderer/window.hpp"

#include <GLFW/glfw3.h>
#if NOVA_WINDOWS
#define GLFW_EXPOSE_NATIVE_WIN32
#elif NOVA_LINUX
typedef int Bool;   // Because X11 is stupid
#define GLFW_EXPOSE_NATIVE_X11
#endif
// We have to include this here so it exists before we #undef Bool, but ReSharper doesn't know the horrors of X11
// ReSharper disable once CppUnusedIncludeDirective
#include <GLFW/glfw3native.h>

#include "nova_renderer/nova_renderer.hpp"
#include "nova_renderer/util/platform.hpp"

#include "../util/logger.hpp"

void glfw_error_callback(const int error, const char* desc) { NOVA_LOG(ERROR) << "GLFW error(" << error << ") " << desc; }

void glfw_key_callback(GLFWwindow* window, const int key, int /* scancode */, const int action, int /* mods */) {
    if(action == GLFW_PRESS) {
        void* user_data = glfwGetWindowUserPointer(window);
        auto* my_window = static_cast<nova::renderer::NovaWindow*>(user_data);
        my_window->process_key(key);
    }
}

namespace nova::renderer {
    NovaWindow::NovaWindow(const NovaSettings& options) {
        if(!glfwInit()) {
            NOVA_LOG(FATAL) << "Failed to init GLFW";
            return;
        }

        glfwSetErrorCallback(glfw_error_callback);

        if(options.api == GraphicsApi::NvGl4) {
            glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
            glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

            if(options.debug.enabled) {
                glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
            }
        }

        window = glfwCreateWindow(static_cast<int>(options.window.width),
                                  static_cast<int>(options.window.height),
                                  options.window.title,
                                  nullptr,
                                  nullptr);
        if(!window) {
            NOVA_LOG(FATAL) << "Failed to create window";
            return;
        }

        if(options.api == GraphicsApi::NvGl4) {
            glfwMakeContextCurrent(window);
        }

        glfwSetWindowUserPointer(window, this);
        glfwSetKeyCallback(window, glfw_key_callback);
    }

    NovaWindow::~NovaWindow() {
        glfwDestroyWindow(window);
        glfwTerminate();
    }

    void NovaWindow::register_key_callback(std::function<void(uint32_t)>&& key_callback) { key_callbacks.push_back(key_callback); }

    void NovaWindow::process_key(const int key) {
        for(const auto& callback : key_callbacks) {
            callback(key);
        }
    }

    // This _can_ be static, but I don't want it to be
    // ReSharper disable once CppMemberFunctionMayBeStatic
    void NovaWindow::poll_input() const { glfwPollEvents(); }

    bool NovaWindow::should_close() const { return glfwWindowShouldClose(window); }

    glm::uvec2 NovaWindow::get_window_size() const {
        int width;
        int height;
        glfwGetFramebufferSize(window, &width, &height);

        return {width, height};
    }

#if NOVA_WINDOWS
    HWND NovaWindow::get_window_handle() const { return glfwGetWin32Window(window); }

#elif NOVA_LINUX
    Window NovaWindow::get_window_handle() const { return glfwGetX11Window(window); };

    Display* NovaWindow::get_display() const { return glfwGetX11Display(window); };
#endif

#if NOVA_OPENGL_RHI
    void NovaWindow::swap_backbuffer() const { glfwSwapBuffers(window); }

    void* NovaWindow::get_gl_proc_address(const char* proc_name) { return reinterpret_cast<void*>(glfwGetProcAddress(proc_name)); }
#endif
} // namespace nova::renderer
<commit_msg>[window] Whoops to omany bindings<commit_after>#include "nova_renderer/window.hpp"

#include <GLFW/glfw3.h>
#if NOVA_WINDOWS
#define GLFW_EXPOSE_NATIVE_WIN32
#elif NOVA_LINUX
typedef int Bool;   // Because X11 is stupid
#define GLFW_EXPOSE_NATIVE_X11
#endif
// We have to include this here so it exists before we #undef Bool, but ReSharper doesn't know the horrors of X11
// ReSharper disable once CppUnusedIncludeDirective
#include <GLFW/glfw3native.h>

#include "nova_renderer/nova_renderer.hpp"
#include "nova_renderer/util/platform.hpp"

#include "../util/logger.hpp"

void glfw_error_callback(const int error, const char* desc) { NOVA_LOG(ERROR) << "GLFW error(" << error << ") " << desc; }

void glfw_key_callback(GLFWwindow* window, const int key, int /* scancode */, const int action, int /* mods */) {
    if(action == GLFW_PRESS) {
        void* user_data = glfwGetWindowUserPointer(window);
        auto* my_window = static_cast<nova::renderer::NovaWindow*>(user_data);
        my_window->process_key(key);
    }
}

namespace nova::renderer {
    NovaWindow::NovaWindow(const NovaSettings& options) {
        if(!glfwInit()) {
            NOVA_LOG(FATAL) << "Failed to init GLFW";
            return;
        }

        glfwSetErrorCallback(glfw_error_callback);

        if(options.api == GraphicsApi::NvGl4) {
            glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
            glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

            if(options.debug.enabled) {
                glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
            }
        }

        window = glfwCreateWindow(static_cast<int>(options.window.width),
                                  static_cast<int>(options.window.height),
                                  options.window.title,
                                  nullptr,
                                  nullptr);
        if(!window) {
            NOVA_LOG(FATAL) << "Failed to create window";
            return;
        }

        if(options.api == GraphicsApi::NvGl4) {
            glfwMakeContextCurrent(window);
        }

        glfwSetWindowUserPointer(window, this);
        glfwSetKeyCallback(window, glfw_key_callback);
    }

    NovaWindow::~NovaWindow() {
        glfwDestroyWindow(window);
        glfwTerminate();
    }

    void NovaWindow::register_key_callback(std::function<void(uint32_t)>&& key_callback) { key_callbacks.push_back(key_callback); }

    void NovaWindow::process_key(const int key) {
        for(const auto& callback : key_callbacks) {
            callback(key);
        }
    }

    // This _can_ be static, but I don't want it to be
    // ReSharper disable once CppMemberFunctionMayBeStatic
    void NovaWindow::poll_input() const { glfwPollEvents(); }

    bool NovaWindow::should_close() const { return glfwWindowShouldClose(window); }

    glm::uvec2 NovaWindow::get_window_size() const {
        int width;
        int height;
        glfwGetFramebufferSize(window, &width, &height);

        return {width, height};
    }

#if NOVA_WINDOWS
    HWND NovaWindow::get_window_handle() const { return glfwGetWin32Window(window); }

#elif NOVA_LINUX
    Window NovaWindow::get_window_handle() const { return glfwGetX11Window(window); };

    Display* NovaWindow::get_display() const { return glfwGetX11Display(); };
#endif

#if NOVA_OPENGL_RHI
    void NovaWindow::swap_backbuffer() const { glfwSwapBuffers(window); }

    void* NovaWindow::get_gl_proc_address(const char* proc_name) { return reinterpret_cast<void*>(glfwGetProcAddress(proc_name)); }
#endif
} // namespace nova::renderer
<|endoftext|>


<commit_before>// License: MIT

#include "Unit.h"
#include "Players/Player.h"

void Unit::setCombatFlag(bool enabled)
{
    if (enabled)
    {
        SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_COMBAT);
    }
    else
    {
        RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_COMBAT);
    }
}

bool Unit::isInCombat() const
{
    return m_combatStatus.isInCombat();
}

bool Unit::isAttacking(Unit* target) const
{
    ASSERT(target);

    return m_combatStatus.isAttacking(target);
}

void Unit::enterCombat()
{
    setCombatFlag(true);

    if (!hasStateFlag(UF_ATTACKING))
    {
        addStateFlag(UF_ATTACKING);
    }
}

void Unit::leaveCombat()
{
    setCombatFlag(false);

    if (hasStateFlag(UF_ATTACKING))
    {
        clearStateFlag(UF_ATTACKING);
    }

    if (IsPlayer())
    {
        static_cast<Player*>(this)->UpdatePotionCooldown();
    }
}

void Unit::onDamageDealt(Unit* target)
{
    ASSERT(target);

    m_combatStatus.onDamageDealt(target);
}

void Unit::addHealTarget(Unit* target)
{
    ASSERT(target != nullptr);

    if (target->IsPlayer())
    {
        m_combatStatus.addHealTarget(reinterpret_cast<Player*>(target));
    }
}

void Unit::removeHealTarget(Unit* target)
{
    ASSERT(target != nullptr);

    if (target->IsPlayer())
    {
        m_combatStatus.removeHealTarget(reinterpret_cast<Player*>(target));
    }
}

void Unit::addHealer(Unit* healer)
{
    ASSERT(healer != nullptr);

    if (healer->IsPlayer())
    {
        m_combatStatus.addHealer(reinterpret_cast<Player*>(healer));
    }
}

void Unit::removeHealer(Unit* healer)
{
    ASSERT(healer != nullptr);

    if (healer->IsPlayer())
    {
        m_combatStatus.removeHealer(reinterpret_cast<Player*>(healer));
    }
}

void Unit::addAttacker(Unit* attacker)
{
    ASSERT(attacker);

    m_combatStatus.addAttacker(attacker);
}

bool Unit::hasAttacker(uint64_t guid) const
{
    return m_combatStatus.hasAttacker(guid);
}

void Unit::removeAttacker(Unit* attacker)
{
    ASSERT(attacker != nullptr);
    //ASSERT(IsInWorld());    //Zyres: unit is not in world. remove attack target only for units in world
    if (this->IsInWorld())
    {
        m_combatStatus.removeAttacker(attacker);
    }
}

void Unit::removeAttacker(uint64_t guid)
{
    m_combatStatus.removeAttacker(guid);
}

void Unit::removeAttackTarget(Unit* attackTarget)
{
    ASSERT(attackTarget != nullptr);
    //ASSERT(IsInWorld());    //Zyres: unit is not in world. remove attack target only for units in world
    if (this->IsInWorld())
    {
        m_combatStatus.removeAttackTarget(attackTarget);
    }
}

void Unit::updateCombatStatus()
{
    m_combatStatus.update();
}

void Unit::clearAllCombatTargets()
{
    m_combatStatus.clearAllCombatTargets();
}

uint64_t Unit::getPrimaryAttackTarget() const
{
    return m_combatStatus.getPrimaryAttackTarget();
}

void Unit::PlaySpellVisual(uint64_t guid, uint32_t spell_id)
{
    WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
    data << uint64_t(guid);
    data << uint32_t(spell_id);

    if (IsPlayer())
        static_cast<Player*>(this)->SendMessageToSet(&data, true);
    else
        SendMessageToSet(&data, false);
}
<commit_msg>Include headerfile Unit.cpp<commit_after>// License: MIT

#include "Unit.h"
#include "Server/Packets/Opcodes.h"
#include "Players/Player.h"

void Unit::setCombatFlag(bool enabled)
{
    if (enabled)
    {
        SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_COMBAT);
    }
    else
    {
        RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_COMBAT);
    }
}

bool Unit::isInCombat() const
{
    return m_combatStatus.isInCombat();
}

bool Unit::isAttacking(Unit* target) const
{
    ASSERT(target);

    return m_combatStatus.isAttacking(target);
}

void Unit::enterCombat()
{
    setCombatFlag(true);

    if (!hasStateFlag(UF_ATTACKING))
    {
        addStateFlag(UF_ATTACKING);
    }
}

void Unit::leaveCombat()
{
    setCombatFlag(false);

    if (hasStateFlag(UF_ATTACKING))
    {
        clearStateFlag(UF_ATTACKING);
    }

    if (IsPlayer())
    {
        static_cast<Player*>(this)->UpdatePotionCooldown();
    }
}

void Unit::onDamageDealt(Unit* target)
{
    ASSERT(target);

    m_combatStatus.onDamageDealt(target);
}

void Unit::addHealTarget(Unit* target)
{
    ASSERT(target != nullptr);

    if (target->IsPlayer())
    {
        m_combatStatus.addHealTarget(reinterpret_cast<Player*>(target));
    }
}

void Unit::removeHealTarget(Unit* target)
{
    ASSERT(target != nullptr);

    if (target->IsPlayer())
    {
        m_combatStatus.removeHealTarget(reinterpret_cast<Player*>(target));
    }
}

void Unit::addHealer(Unit* healer)
{
    ASSERT(healer != nullptr);

    if (healer->IsPlayer())
    {
        m_combatStatus.addHealer(reinterpret_cast<Player*>(healer));
    }
}

void Unit::removeHealer(Unit* healer)
{
    ASSERT(healer != nullptr);

    if (healer->IsPlayer())
    {
        m_combatStatus.removeHealer(reinterpret_cast<Player*>(healer));
    }
}

void Unit::addAttacker(Unit* attacker)
{
    ASSERT(attacker);

    m_combatStatus.addAttacker(attacker);
}

bool Unit::hasAttacker(uint64_t guid) const
{
    return m_combatStatus.hasAttacker(guid);
}

void Unit::removeAttacker(Unit* attacker)
{
    ASSERT(attacker != nullptr);
    //ASSERT(IsInWorld());    //Zyres: unit is not in world. remove attack target only for units in world
    if (this->IsInWorld())
    {
        m_combatStatus.removeAttacker(attacker);
    }
}

void Unit::removeAttacker(uint64_t guid)
{
    m_combatStatus.removeAttacker(guid);
}

void Unit::removeAttackTarget(Unit* attackTarget)
{
    ASSERT(attackTarget != nullptr);
    //ASSERT(IsInWorld());    //Zyres: unit is not in world. remove attack target only for units in world
    if (this->IsInWorld())
    {
        m_combatStatus.removeAttackTarget(attackTarget);
    }
}

void Unit::updateCombatStatus()
{
    m_combatStatus.update();
}

void Unit::clearAllCombatTargets()
{
    m_combatStatus.clearAllCombatTargets();
}

uint64_t Unit::getPrimaryAttackTarget() const
{
    return m_combatStatus.getPrimaryAttackTarget();
}

void Unit::PlaySpellVisual(uint64_t guid, uint32_t spell_id)
{
    WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);
    data << uint64_t(guid);
    data << uint32_t(spell_id);

    if (IsPlayer())
        static_cast<Player*>(this)->SendMessageToSet(&data, true);
    else
        SendMessageToSet(&data, false);
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   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    KitwareConverter.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    December 2008
*/

#include <fstream>
#include "KitwareConverter.h"
#include <Controller/Controller.h>
#include <Basics/SysTools.h>
#include <IO/KeyValueFileParser.h>

using namespace std;

KitwareConverter::KitwareConverter()
{
  m_vConverterDesc = "Kitware MHD Data";
  m_vSupportedExt.push_back("MHD");
}

bool KitwareConverter::ConvertToRAW(const std::string& strSourceFilename,
                            const std::string&, bool,
                            UINT64& iHeaderSkip, UINT64& iComponentSize, UINT64& iComponentCount,
                            bool& bConvertEndianess, bool& bSigned, bool& bIsFloat, UINT64VECTOR3& vVolumeSize,
                            FLOATVECTOR3& vVolumeAspect, std::string& strTitle,
                            UVFTables::ElementSemanticTable& eType, std::string& strIntermediateFile,
                            bool& bDeleteIntermediateFile) {

  MESSAGE("Attempting to convert Kitware MHD dataset %s", strSourceFilename.c_str());

  eType             = UVFTables::ES_UNDEFINED;
  strTitle          = "Kitware MHD data";

  KeyValueFileParser parser(strSourceFilename,false,"=");

  if (parser.FileReadable())  {
    KeyValPair* dims           = parser.GetData("NDIMS");
    KeyValPair* dimsize        = parser.GetData("DIMSIZE");
    KeyValPair* ElementSpacing = parser.GetData("ELEMENTSPACING");
    KeyValPair* BigEndianFlag  = parser.GetData("ELEMENTBYTEORDERMSB");
    if (BigEndianFlag == NULL) BigEndianFlag = parser.GetData("BINARYDATABYTEORDERMSB");
    KeyValPair* ElementType    = parser.GetData("ELEMENTTYPE");
    KeyValPair* CompressedData = parser.GetData("COMPRESSEDDATA");
    KeyValPair* BinaryData      = parser.GetData("BINARYDATA");
    KeyValPair* Position       = parser.GetData("POSITION");
    KeyValPair* ElementNumberOfChannels = parser.GetData("ELEMENTNUMBEROFCHANNELS");
    KeyValPair* ElementDataFile = parser.GetData("ELEMENTDATAFILE");
    KeyValPair* HeaderSize = parser.GetData("HEADERSIZE");
    KeyValPair* ObjectType = parser.GetData("OBJECTTYPE");

    if (ObjectType && ObjectType->strValueUpper != "IMAGE") {
      T_ERROR("Only image type MHD file are currently supported.");
      return false;
    }

    if (ElementDataFile == NULL) {
      T_ERROR("Unable to find 'ElementDataFile' tag in file %s.", strSourceFilename.c_str());
      return false;
    }

    if (dimsize == NULL) {
      T_ERROR("Unable to find 'DimSize' tag in file %s.", strSourceFilename.c_str());
      return false;
    }

    if (ElementType == NULL) {
      T_ERROR("Unable to find 'ElementType' tag in file %s.", strSourceFilename.c_str());
      return false;
    }

    if (BigEndianFlag == NULL) {
      MESSAGE("Unable to find 'ElementByteOrderMSB' or 'BinaryDataByteOrderMSB' tags in file %s assuming little endian data.", strSourceFilename.c_str());
      bConvertEndianess = EndianConvert::IsBigEndian();
    } else {
      if(BigEndianFlag->strValueUpper == "FALSE") {
        bConvertEndianess = EndianConvert::IsBigEndian();
      } else {
        bConvertEndianess = EndianConvert::IsLittleEndian();
      }
    }

    if(ElementType->strValueUpper == "MET_CHAR") {
      bSigned = true;
      iComponentSize = 8;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_UCHAR") {
      bSigned = false;
      iComponentSize = 8;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_SHORT") {
      bSigned = true;
      iComponentSize = 16;
      bIsFloat = false;
    }else if (ElementType->strValueUpper == "MET_USHORT") {
      bSigned = false;
      iComponentSize = 16;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_INT") {
      bSigned = true;
      iComponentSize = 32;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_UINT") {
      bSigned = false;
      iComponentSize = 32;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_FLOAT") {
      bSigned = true;
      iComponentSize = 32;
      bIsFloat = true;
    }

    if (ElementNumberOfChannels == NULL) {
      MESSAGE("Unable to find 'ElementNumberOfChannels ' tag in file %s assuming scalar data.", strSourceFilename.c_str());
      iComponentCount = EndianConvert::IsBigEndian();
    } else {
      iComponentCount = ElementNumberOfChannels->iValue;
    }

    strIntermediateFile = ElementDataFile->strValue;

    if (strIntermediateFile == "LIST") {
      T_ERROR("LISTS are currently not supported in MHD files.");
      return false;
    }

    UINT32 iDims = static_cast<UINT32>(dimsize->vuiValue.size());

    if (dims == NULL) {
      WARNING("Unable to find 'NDims' tag in file %s relying on 'DimSize' tag.", strSourceFilename.c_str());
    } else {
      if (iDims != dims->uiValue) {
        T_ERROR("Tags 'NDims' and 'DimSize' are incosistent in file %s.", strSourceFilename.c_str());
        return false;
      }
    }

    if (iDims > 3) {
      T_ERROR("Currently only up to 3D data supported.");
      return false;
    }

    vVolumeSize = UINT64VECTOR3(dimsize->vuiValue, 1);
    vVolumeAspect = FLOATVECTOR3(ElementSpacing->vfValue,1.0f);

    if (Position != NULL) {
      for (size_t i = 0;i<ElementSpacing->vfValue.size();i++) {
        if (ElementSpacing->vfValue[i] != 0.0f) {
          WARNING("Ignoring non zero position.");
          break;
        }
      }
    }

    // TODO: find a non binary MHD payload file and figure out its format
    if (BinaryData != NULL) {
      if(BinaryData->strValueUpper == "FALSE") {
        T_ERROR("Currently only binary MHD data supported.");
        return false;
      }
    }

    // TODO: find a compressed MHD payload file and figure out its format
    if (CompressedData != NULL) {
      if(CompressedData->strValueUpper == "TRUE") {
        T_ERROR("Currently only uncompressed MHD data supported.");
        return false;
      }
    }
    bDeleteIntermediateFile = false;

    strIntermediateFile = SysTools::GetPath(strSourceFilename) + strIntermediateFile;

    if (HeaderSize != NULL) {
      if (dimsize->iValue != -1 ) { // size -1 means compute header size automatically
        iHeaderSkip = dimsize->uiValue;
      } else {
        LargeRAWFile f(strIntermediateFile);
        if (f.Open(false)) {
          UINT64 iFileSize = f.GetCurrentSize();
          f.Close();
          iHeaderSkip = iFileSize - (iComponentSize/8)*vVolumeSize.volume()*iComponentCount;
        } else {
          T_ERROR("Unable to open paload file %s.", strIntermediateFile.c_str());
          return false;
        }
      }
    } else {
      iHeaderSkip = 0;
    }

  } else return false;

  return true;
}

bool KitwareConverter::ConvertToNative(const std::string& strRawFilename, const std::string& strTargetFilename, UINT64 iHeaderSkip,
                             UINT64 iComponentSize, UINT64 iComponentCount, bool bSigned, bool bFloatingPoint,
                             UINT64VECTOR3 vVolumeSize,FLOATVECTOR3 vVolumeAspect, bool bNoUserInteraction,
                             const bool bQuantizeTo8Bit) {

  // compute fromat string
  string strFormat;
  if (!bQuantizeTo8Bit) {
    if (bFloatingPoint && bSigned && iComponentSize == 32)
      strFormat = "MET_FLOAT";
    else
    if (!bFloatingPoint && bSigned && iComponentSize == 32)
      strFormat = "MET_INT";
    else
    if (!bFloatingPoint && !bSigned && iComponentSize == 32)
      strFormat = "MET_UINT";
    else
    if (!bFloatingPoint && bSigned && iComponentSize == 8)
      strFormat = "MET_CHAR";
    else
    if (!bFloatingPoint && !bSigned && iComponentSize == 8)
      strFormat = "MET_UCHAR";
    else
    if (!bFloatingPoint && bSigned && iComponentSize == 16)
      strFormat = "MET_SHORT";
    else
    if (!bFloatingPoint && !bSigned && iComponentSize == 16)
      strFormat = "MET_USHORT";
    else {
      T_ERROR("This data type is not supported by the MHD writer.");
      return false;
    }
  } else {
    if (bSigned)
      strFormat = "MET_CHAR";
    else
      strFormat = "MET_UCHAR";
  }

  // create textfile from metadata
  string strTargetRAWFilename = strTargetFilename+".raw";

  ofstream fTarget(strTargetFilename.c_str());
  if (!fTarget.is_open()) {
    T_ERROR("Unable to open target file %s.", strTargetFilename.c_str());
    return false;
  }

  MESSAGE("Writing MHD File");

  fTarget << "ObjectType              = Image" << endl;
  fTarget << "BinaryData              = True" << endl;
  if (EndianConvert::IsBigEndian())
    fTarget << "BinaryDataByteOrderMSB  = true" << endl;
  else
    fTarget << "BinaryDataByteOrderMSB  = false" << endl;
  fTarget << "HeaderSize              = 0" << endl;

  fTarget << "NDims                   = 3" << endl;
  fTarget << "DimSize                 = " << vVolumeSize.x << " " << vVolumeSize.y << " "<< vVolumeSize.z << endl;
  fTarget << "ElementSpacing          = " << vVolumeAspect.x << " " << vVolumeAspect.y << " "<< vVolumeAspect.z << endl;

  fTarget << "ElementNumberOfChannels = " << iComponentCount << endl;
  fTarget << "ElementType             = " << strFormat << endl;
  fTarget << "ElementDataFile         = " << SysTools::GetFilename(strTargetRAWFilename) << endl;
  fTarget.close();

  MESSAGE("Writing RAW File");

  // copy RAW file using the parent's call
  bool bRAWSuccess = RAWConverter::ConvertToNative(strRawFilename, strTargetRAWFilename, iHeaderSkip,
                                                   iComponentSize, iComponentCount, bSigned, bFloatingPoint,
                                                   vVolumeSize, vVolumeAspect, bNoUserInteraction,bQuantizeTo8Bit);

  if (bRAWSuccess) {
    return true;
  } else {
    T_ERROR("Error creating raw target file %s.", strTargetRAWFilename.c_str());
    remove(strTargetFilename.c_str());
    return false;
  }
}
<commit_msg>added DOUBLE to Kitware converter<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   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    KitwareConverter.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    December 2008
*/

#include <fstream>
#include "KitwareConverter.h"
#include <Controller/Controller.h>
#include <Basics/SysTools.h>
#include <IO/KeyValueFileParser.h>

using namespace std;

KitwareConverter::KitwareConverter()
{
  m_vConverterDesc = "Kitware MHD Data";
  m_vSupportedExt.push_back("MHD");
}

bool KitwareConverter::ConvertToRAW(const std::string& strSourceFilename,
                            const std::string&, bool,
                            UINT64& iHeaderSkip, UINT64& iComponentSize, UINT64& iComponentCount,
                            bool& bConvertEndianess, bool& bSigned, bool& bIsFloat, UINT64VECTOR3& vVolumeSize,
                            FLOATVECTOR3& vVolumeAspect, std::string& strTitle,
                            UVFTables::ElementSemanticTable& eType, std::string& strIntermediateFile,
                            bool& bDeleteIntermediateFile) {

  MESSAGE("Attempting to convert Kitware MHD dataset %s", strSourceFilename.c_str());

  eType             = UVFTables::ES_UNDEFINED;
  strTitle          = "Kitware MHD data";

  KeyValueFileParser parser(strSourceFilename,false,"=");

  if (parser.FileReadable())  {
    KeyValPair* dims           = parser.GetData("NDIMS");
    KeyValPair* dimsize        = parser.GetData("DIMSIZE");
    KeyValPair* ElementSpacing = parser.GetData("ELEMENTSPACING");
    KeyValPair* BigEndianFlag  = parser.GetData("ELEMENTBYTEORDERMSB");
    if (BigEndianFlag == NULL) BigEndianFlag = parser.GetData("BINARYDATABYTEORDERMSB");
    KeyValPair* ElementType    = parser.GetData("ELEMENTTYPE");
    KeyValPair* CompressedData = parser.GetData("COMPRESSEDDATA");
    KeyValPair* BinaryData      = parser.GetData("BINARYDATA");
    KeyValPair* Position       = parser.GetData("POSITION");
    KeyValPair* ElementNumberOfChannels = parser.GetData("ELEMENTNUMBEROFCHANNELS");
    KeyValPair* ElementDataFile = parser.GetData("ELEMENTDATAFILE");
    KeyValPair* HeaderSize = parser.GetData("HEADERSIZE");
    KeyValPair* ObjectType = parser.GetData("OBJECTTYPE");

    if (ObjectType && ObjectType->strValueUpper != "IMAGE") {
      T_ERROR("Only image type MHD file are currently supported.");
      return false;
    }

    if (ElementDataFile == NULL) {
      T_ERROR("Unable to find 'ElementDataFile' tag in file %s.", strSourceFilename.c_str());
      return false;
    }

    if (dimsize == NULL) {
      T_ERROR("Unable to find 'DimSize' tag in file %s.", strSourceFilename.c_str());
      return false;
    }

    if (ElementType == NULL) {
      T_ERROR("Unable to find 'ElementType' tag in file %s.", strSourceFilename.c_str());
      return false;
    }

    if (BigEndianFlag == NULL) {
      MESSAGE("Unable to find 'ElementByteOrderMSB' or 'BinaryDataByteOrderMSB' tags in file %s assuming little endian data.", strSourceFilename.c_str());
      bConvertEndianess = EndianConvert::IsBigEndian();
    } else {
      if(BigEndianFlag->strValueUpper == "FALSE") {
        bConvertEndianess = EndianConvert::IsBigEndian();
      } else {
        bConvertEndianess = EndianConvert::IsLittleEndian();
      }
    }

    if(ElementType->strValueUpper == "MET_CHAR") {
      bSigned = true;
      iComponentSize = 8;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_UCHAR") {
      bSigned = false;
      iComponentSize = 8;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_SHORT") {
      bSigned = true;
      iComponentSize = 16;
      bIsFloat = false;
    }else if (ElementType->strValueUpper == "MET_USHORT") {
      bSigned = false;
      iComponentSize = 16;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_INT") {
      bSigned = true;
      iComponentSize = 32;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_UINT") {
      bSigned = false;
      iComponentSize = 32;
      bIsFloat = false;
    } else if (ElementType->strValueUpper == "MET_FLOAT") {
      bSigned = true;
      iComponentSize = 32;
      bIsFloat = true;
    } else if (ElementType->strValueUpper == "MET_DOUBLE") {
      bSigned = true;
      iComponentSize = 64;
      bIsFloat = true;
    }

    if (ElementNumberOfChannels == NULL) {
      MESSAGE("Unable to find 'ElementNumberOfChannels ' tag in file %s assuming scalar data.", strSourceFilename.c_str());
      iComponentCount = EndianConvert::IsBigEndian();
    } else {
      iComponentCount = ElementNumberOfChannels->iValue;
    }

    strIntermediateFile = ElementDataFile->strValue;

    if (strIntermediateFile == "LIST") {
      T_ERROR("LISTS are currently not supported in MHD files.");
      return false;
    }

    UINT32 iDims = static_cast<UINT32>(dimsize->vuiValue.size());

    if (dims == NULL) {
      WARNING("Unable to find 'NDims' tag in file %s relying on 'DimSize' tag.", strSourceFilename.c_str());
    } else {
      if (iDims != dims->uiValue) {
        T_ERROR("Tags 'NDims' and 'DimSize' are incosistent in file %s.", strSourceFilename.c_str());
        return false;
      }
    }

    if (iDims > 3) {
      T_ERROR("Currently only up to 3D data supported.");
      return false;
    }

    vVolumeSize = UINT64VECTOR3(dimsize->vuiValue, 1);
    vVolumeAspect = FLOATVECTOR3(ElementSpacing->vfValue,1.0f);

    if (Position != NULL) {
      for (size_t i = 0;i<ElementSpacing->vfValue.size();i++) {
        if (ElementSpacing->vfValue[i] != 0.0f) {
          WARNING("Ignoring non zero position.");
          break;
        }
      }
    }

    // TODO: find a non binary MHD payload file and figure out its format
    if (BinaryData != NULL) {
      if(BinaryData->strValueUpper == "FALSE") {
        T_ERROR("Currently only binary MHD data supported.");
        return false;
      }
    }

    // TODO: find a compressed MHD payload file and figure out its format
    if (CompressedData != NULL) {
      if(CompressedData->strValueUpper == "TRUE") {
        T_ERROR("Currently only uncompressed MHD data supported.");
        return false;
      }
    }
    bDeleteIntermediateFile = false;

    strIntermediateFile = SysTools::GetPath(strSourceFilename) + strIntermediateFile;

    if (HeaderSize != NULL) {
      if (dimsize->iValue != -1 ) { // size -1 means compute header size automatically
        iHeaderSkip = dimsize->uiValue;
      } else {
        LargeRAWFile f(strIntermediateFile);
        if (f.Open(false)) {
          UINT64 iFileSize = f.GetCurrentSize();
          f.Close();
          iHeaderSkip = iFileSize - (iComponentSize/8)*vVolumeSize.volume()*iComponentCount;
        } else {
          T_ERROR("Unable to open paload file %s.", strIntermediateFile.c_str());
          return false;
        }
      }
    } else {
      iHeaderSkip = 0;
    }

  } else return false;

  return true;
}

bool KitwareConverter::ConvertToNative(const std::string& strRawFilename, const std::string& strTargetFilename, UINT64 iHeaderSkip,
                             UINT64 iComponentSize, UINT64 iComponentCount, bool bSigned, bool bFloatingPoint,
                             UINT64VECTOR3 vVolumeSize,FLOATVECTOR3 vVolumeAspect, bool bNoUserInteraction,
                             const bool bQuantizeTo8Bit) {

  // compute fromat string
  string strFormat;
  if (!bQuantizeTo8Bit) {
    if (bFloatingPoint && bSigned && iComponentSize == 64)
      strFormat = "MET_DOUBLE";
    else
    if (bFloatingPoint && bSigned && iComponentSize == 32)
      strFormat = "MET_FLOAT";
    else
    if (!bFloatingPoint && bSigned && iComponentSize == 32)
      strFormat = "MET_INT";
    else
    if (!bFloatingPoint && !bSigned && iComponentSize == 32)
      strFormat = "MET_UINT";
    else
    if (!bFloatingPoint && bSigned && iComponentSize == 8)
      strFormat = "MET_CHAR";
    else
    if (!bFloatingPoint && !bSigned && iComponentSize == 8)
      strFormat = "MET_UCHAR";
    else
    if (!bFloatingPoint && bSigned && iComponentSize == 16)
      strFormat = "MET_SHORT";
    else
    if (!bFloatingPoint && !bSigned && iComponentSize == 16)
      strFormat = "MET_USHORT";
    else {
      T_ERROR("This data type is not supported by the MHD writer.");
      return false;
    }
  } else {
    if (bSigned)
      strFormat = "MET_CHAR";
    else
      strFormat = "MET_UCHAR";
  }

  // create textfile from metadata
  string strTargetRAWFilename = strTargetFilename+".raw";

  ofstream fTarget(strTargetFilename.c_str());
  if (!fTarget.is_open()) {
    T_ERROR("Unable to open target file %s.", strTargetFilename.c_str());
    return false;
  }

  MESSAGE("Writing MHD File");

  fTarget << "ObjectType              = Image" << endl;
  fTarget << "BinaryData              = True" << endl;
  if (EndianConvert::IsBigEndian())
    fTarget << "BinaryDataByteOrderMSB  = true" << endl;
  else
    fTarget << "BinaryDataByteOrderMSB  = false" << endl;
  fTarget << "HeaderSize              = 0" << endl;

  fTarget << "NDims                   = 3" << endl;
  fTarget << "DimSize                 = " << vVolumeSize.x << " " << vVolumeSize.y << " "<< vVolumeSize.z << endl;
  fTarget << "ElementSpacing          = " << vVolumeAspect.x << " " << vVolumeAspect.y << " "<< vVolumeAspect.z << endl;

  fTarget << "ElementNumberOfChannels = " << iComponentCount << endl;
  fTarget << "ElementType             = " << strFormat << endl;
  fTarget << "ElementDataFile         = " << SysTools::GetFilename(strTargetRAWFilename) << endl;
  fTarget.close();

  MESSAGE("Writing RAW File");

  // copy RAW file using the parent's call
  bool bRAWSuccess = RAWConverter::ConvertToNative(strRawFilename, strTargetRAWFilename, iHeaderSkip,
                                                   iComponentSize, iComponentCount, bSigned, bFloatingPoint,
                                                   vVolumeSize, vVolumeAspect, bNoUserInteraction,bQuantizeTo8Bit);

  if (bRAWSuccess) {
    return true;
  } else {
    T_ERROR("Error creating raw target file %s.", strTargetRAWFilename.c_str());
    remove(strTargetFilename.c_str());
    return false;
  }
}
<|endoftext|>


<commit_before>#include <iostream>
#include "CDAP.pb.h"

using namespace std;

int main()
{
    return 0;
}
<commit_msg>cdap: added internal CDAPMessage struct<commit_after>#include <iostream>
#include <string>

#include "rinalite/rinalite-common.h"
#include "CDAP.pb.h"

using namespace std;

/* Internal representation of a CDAP message. */
struct CDAPMessage {
    int                 abs_syntax;
    gpb::authTypes_t    auth_mech;
    struct {
        string auth_name;
        string auth_password;
        string auth_other;
    }                   auth_value;
    struct rina_name    local_appl;
    struct rina_name    remote_appl;
    string              filter;
    gpb::flagValues_t   flags;
    int                 invoke_id;
    string              obj_class;
    long                obj_inst;
    string              obj_name;
    gpb::opCode_t       op_code;
    int                 result;
    string              result_reason;
    int                 scope;
    long                version;

    enum obj_value_t {
        NONE,
        I32,
        I64,
        BYTES,
        FLOAT,
        DOUBLE,
        BOOL,
        STRING,
    };

    bool is(obj_value_t tt) const { return obj_value.ty == tt; }

private:
    /* Representation of the object value. */
    struct {
        obj_value_t         ty;
        union {
            int32_t         i32; /* intval and sintval */
            int64_t         i64; /* int64val and sint64val */
            void            *bytes;
            float           fp_single;
            double          fp_double;
            bool            boolean;
        } u;
        string              str; /* strval */
    }                   obj_value;
};

int main()
{
    gpb::CDAPMessage gm;
    CDAPMessage m;

    (void)gm;
    (void)m;

    return 0;
}
<|endoftext|>


<commit_before>#include "AliVertex.h"

ClassImp(AliVertex) // Class implementation to enable ROOT I/O

AliVertex::AliVertex()
{
// Default constructor
// All variables initialised to 0
// Initial maximum number of tracks is set to the default value
// Initial maximum number of sec. vertices is set to the default value
 fNvmax=0;
 fVertices=0;
 Reset();
 SetNtinit();
 SetNvmax();
}
///////////////////////////////////////////////////////////////////////////
AliVertex::AliVertex(Int_t n)
{
// Create a vertex to hold initially a maximum of n tracks
// All variables initialised to 0
 fNvmax=0;
 fVertices=0;
 Reset();
 if (n > 0)
 {
  SetNtinit(n);
 }
 else
 {
  cout << endl;
  cout << " *AliVertex* Initial max. number of tracks entered : " << n << endl;
  cout << " This is invalid. Default initial maximum will be used." << endl;
  cout << endl;
  SetNtinit();
 }
 SetNvmax();
}
///////////////////////////////////////////////////////////////////////////
AliVertex::~AliVertex()
{
// Default destructor
 if (fVertices) delete fVertices;
 fVertices=0;
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::SetNvmax(Int_t n)
{
// Set the initial maximum number of (secondary) vertices
 if (n > 0)
 {
  fNvmax=n;
 }
 else
 {
  fNvmax=1;
 }
 if (fVertices) delete fVertices;
 fVertices=new TObjArray(fNvmax);
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::Reset()
{
// Reset all variables to 0
// The max. number of tracks is set to the initial value again
// The max. number of vertices is set to the default value again

 AliJet::Reset();

 fNvtx=0;
 if (fNvmax>0) SetNvmax(fNvmax);
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::Add(AliJet& j)
{
// Add the tracks of a jet to the vertex
 AliTrack* tj;
 for (Int_t i=1; i<=j.GetNtracks(); i++)
 {
  tj=j.GetTrack(i);
  AliJet::Add(tj);
 }
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::Add(AliVertex& v)
{
// Add a (secondary) vertex to the current vertex.
// In case the maximum number of (secondary) vertices has been reached,
// the array space will be extended automatically
//
// Note : The 4-momentum of the current (primary) vertex
//        is updated automatically, but the track connecting
//        both vertices has to be entered separately by the user.
//
 if (fNvtx == fNvmax) // Check if maximum vertex number is reached
 {
  fNvmax++;
  fVertices->Expand(fNvmax);
 }

 // Update 4-momentum for current vertex
 fNvtx++;
 fVertices->Add(&v);
 (Ali4Vector)(*this)+=v;
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::Info(TString f)
{
// Provide vertex information within the coordinate frame f
 cout << " *AliVertex::Info* Invmass : " << GetInvmass()
      << " Charge : " << GetCharge() << " Momentum : " << GetMomentum()
      << " Ntracks : " << GetNtracks() << " Nvertices : " << fNvtx << endl;
 cout << " ";
 Ali4Vector::Info(f);
 cout << "  Position";
 AliPosition::Info(f);
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::List(TString f)
{
// Provide primary track and sec. vertex information within the coordinate frame f

 Info(f); // Information of the current vertex

 // The tracks of this vertex
 AliTrack* t;
 for (Int_t it=1; it<=GetNtracks(); it++)
 {
  t=GetTrack(it);
  if (t)
  {
   cout << "  ---Track no. " << it << endl;
   cout << " ";
   t->Info(f);
  }
  else
  {
   cout << " *AliVertex::List* Error : No track present." << endl;
  }
 }

 // The secondary vertices of this vertex
 AliVertex* v;
 for (Int_t iv=1; iv<=GetNvertices(); iv++)
 {
  v=GetVertex(iv);
  if (v)
  {
   cout << "  ---Level 1 sec. vertex no. " << iv << endl;
   cout << " ";
   v->Info(f);
  }
  else
  {
   cout << " *AliVertex::List* Error : No sec. vertex present." << endl;
  }
 }
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::ListAll(TString f)
{
// Provide complete (sec) vertex and (decay) track info within the coordinate frame f

 Info(f); // Information of the current vertex

 // The tracks of this vertex
 AliTrack* t;
 for (Int_t it=1; it<=GetNtracks(); it++)
 {
  t=GetTrack(it);
  if (t)
  {
   cout << "  ---Track no. " << it << endl;
   cout << " ";
   t->ListAll(f);
  }
  else
  {
   cout << " *AliVertex::ListAll* Error : No track present." << endl;
  }
 }

 AliVertex* v=this;
 Dump(v,1,f); // Information of all sec. vertices
}
//////////////////////////////////////////////////////////////////////////
void AliVertex::Dump(AliVertex* v,Int_t n,TString f)
{
// Recursively provide the info of all secondary vertices of this vertex
 AliVertex* vs;
 for (Int_t iv=1; iv<=v->GetNvertices(); iv++)
 {
  vs=v->GetVertex(iv);
  if (vs)
  {
   cout << "  ---Level " << n << " sec. vertex no. " << iv << endl;
   cout << " ";
   vs->Info(f);

   // The tracks of this vertex
   AliTrack* t;
   for (Int_t it=1; it<=vs->GetNtracks(); it++)
   {
    t=vs->GetTrack(it);
    if (t)
    {
     cout << "  ---Track no. " << it << endl;
     cout << " ";
     t->ListAll(f);
    }
    else
    {
     cout << " *AliVertex::Dump* Error : No track present." << endl;
    }
   }

   // Go for next sec. vertex level of this sec. vertex recursively
   Dump(vs,n+1,f);
  }
  else
  {
   cout << " *AliVertex::Dump* Error : No sec. vertex present." << endl;
  }
 }
}
//////////////////////////////////////////////////////////////////////////
Int_t AliVertex::GetNvertices()
{
// Return the current number of (secondary) vertices
 return fNvtx;
}
///////////////////////////////////////////////////////////////////////////
AliVertex* AliVertex::GetVertex(Int_t i)
{
// Return the i-th (secondary) vertex of the current vertex
 return (AliVertex*)fVertices->At(i-1);
}
///////////////////////////////////////////////////////////////////////////
<commit_msg>Small syntax correction for SunOS<commit_after>#include "AliVertex.h"

ClassImp(AliVertex) // Class implementation to enable ROOT I/O

AliVertex::AliVertex()
{
// Default constructor
// All variables initialised to 0
// Initial maximum number of tracks is set to the default value
// Initial maximum number of sec. vertices is set to the default value
 fNvmax=0;
 fVertices=0;
 Reset();
 SetNtinit();
 SetNvmax();
}
///////////////////////////////////////////////////////////////////////////
AliVertex::AliVertex(Int_t n)
{
// Create a vertex to hold initially a maximum of n tracks
// All variables initialised to 0
 fNvmax=0;
 fVertices=0;
 Reset();
 if (n > 0)
 {
  SetNtinit(n);
 }
 else
 {
  cout << endl;
  cout << " *AliVertex* Initial max. number of tracks entered : " << n << endl;
  cout << " This is invalid. Default initial maximum will be used." << endl;
  cout << endl;
  SetNtinit();
 }
 SetNvmax();
}
///////////////////////////////////////////////////////////////////////////
AliVertex::~AliVertex()
{
// Default destructor
 if (fVertices) delete fVertices;
 fVertices=0;
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::SetNvmax(Int_t n)
{
// Set the initial maximum number of (secondary) vertices
 if (n > 0)
 {
  fNvmax=n;
 }
 else
 {
  fNvmax=1;
 }
 if (fVertices) delete fVertices;
 fVertices=new TObjArray(fNvmax);
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::Reset()
{
// Reset all variables to 0
// The max. number of tracks is set to the initial value again
// The max. number of vertices is set to the default value again

 AliJet::Reset();

 fNvtx=0;
 if (fNvmax>0) SetNvmax(fNvmax);
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::Add(AliJet& j)
{
// Add the tracks of a jet to the vertex
 AliTrack* tj;
 for (Int_t i=1; i<=j.GetNtracks(); i++)
 {
  tj=j.GetTrack(i);
  AliJet::Add(tj);
 }
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::Add(AliVertex& v)
{
// Add a (secondary) vertex to the current vertex.
// In case the maximum number of (secondary) vertices has been reached,
// the array space will be extended automatically
//
// Note : The 4-momentum of the current (primary) vertex
//        is updated automatically, but the track connecting
//        both vertices has to be entered separately by the user.
//
 if (fNvtx == fNvmax) // Check if maximum vertex number is reached
 {
  fNvmax++;
  fVertices->Expand(fNvmax);
 }

 // Update 4-momentum for current vertex
 fNvtx++;
 fVertices->Add(&v);
 (*(Ali4Vector*)this)+=v;
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::Info(TString f)
{
// Provide vertex information within the coordinate frame f
 cout << " *AliVertex::Info* Invmass : " << GetInvmass()
      << " Charge : " << GetCharge() << " Momentum : " << GetMomentum()
      << " Ntracks : " << GetNtracks() << " Nvertices : " << fNvtx << endl;
 cout << " ";
 Ali4Vector::Info(f);
 cout << "  Position";
 AliPosition::Info(f);
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::List(TString f)
{
// Provide primary track and sec. vertex information within the coordinate frame f

 Info(f); // Information of the current vertex

 // The tracks of this vertex
 AliTrack* t;
 for (Int_t it=1; it<=GetNtracks(); it++)
 {
  t=GetTrack(it);
  if (t)
  {
   cout << "  ---Track no. " << it << endl;
   cout << " ";
   t->Info(f);
  }
  else
  {
   cout << " *AliVertex::List* Error : No track present." << endl;
  }
 }

 // The secondary vertices of this vertex
 AliVertex* v;
 for (Int_t iv=1; iv<=GetNvertices(); iv++)
 {
  v=GetVertex(iv);
  if (v)
  {
   cout << "  ---Level 1 sec. vertex no. " << iv << endl;
   cout << " ";
   v->Info(f);
  }
  else
  {
   cout << " *AliVertex::List* Error : No sec. vertex present." << endl;
  }
 }
}
///////////////////////////////////////////////////////////////////////////
void AliVertex::ListAll(TString f)
{
// Provide complete (sec) vertex and (decay) track info within the coordinate frame f

 Info(f); // Information of the current vertex

 // The tracks of this vertex
 AliTrack* t;
 for (Int_t it=1; it<=GetNtracks(); it++)
 {
  t=GetTrack(it);
  if (t)
  {
   cout << "  ---Track no. " << it << endl;
   cout << " ";
   t->ListAll(f);
  }
  else
  {
   cout << " *AliVertex::ListAll* Error : No track present." << endl;
  }
 }

 AliVertex* v=this;
 Dump(v,1,f); // Information of all sec. vertices
}
//////////////////////////////////////////////////////////////////////////
void AliVertex::Dump(AliVertex* v,Int_t n,TString f)
{
// Recursively provide the info of all secondary vertices of this vertex
 AliVertex* vs;
 for (Int_t iv=1; iv<=v->GetNvertices(); iv++)
 {
  vs=v->GetVertex(iv);
  if (vs)
  {
   cout << "  ---Level " << n << " sec. vertex no. " << iv << endl;
   cout << " ";
   vs->Info(f);

   // The tracks of this vertex
   AliTrack* t;
   for (Int_t it=1; it<=vs->GetNtracks(); it++)
   {
    t=vs->GetTrack(it);
    if (t)
    {
     cout << "  ---Track no. " << it << endl;
     cout << " ";
     t->ListAll(f);
    }
    else
    {
     cout << " *AliVertex::Dump* Error : No track present." << endl;
    }
   }

   // Go for next sec. vertex level of this sec. vertex recursively
   Dump(vs,n+1,f);
  }
  else
  {
   cout << " *AliVertex::Dump* Error : No sec. vertex present." << endl;
  }
 }
}
//////////////////////////////////////////////////////////////////////////
Int_t AliVertex::GetNvertices()
{
// Return the current number of (secondary) vertices
 return fNvtx;
}
///////////////////////////////////////////////////////////////////////////
AliVertex* AliVertex::GetVertex(Int_t i)
{
// Return the i-th (secondary) vertex of the current vertex
 return (AliVertex*)fVertices->At(i-1);
}
///////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>#include "Modeler3D.h"

#include <cmath>
#include <iostream>

#include <boost/filesystem.hpp>
#include <GL/glew.h>

#include "GUI/AllWidgets.h"
#include "GUI/IAction.h"
#include "Math/VectorMath.h"

#include "FileIO.h"
#include "GuiRenderer.h"

using namespace std;
using namespace Core;
using namespace Core::Math;
using namespace Video;

std::string VertSource = ""
        "#version 120 \n"
        ""
        "attribute vec3 aPosition; \n"
        "attribute vec3 aNormal; \n"
        ""
        "varying vec3 vViewPosition; \n"
        "varying vec3 vNormal; \n"
        ""
        "uniform mat4 Projection; \n"
        "uniform mat4 View; \n"
        "uniform mat4 Model; \n"
        "uniform mat3 NormalMat; \n"
        ""
        "void main() \n"
        "{ \n"
        "   vNormal = normalize(NormalMat * aNormal); \n"
        "   gl_Position = View * Model * vec4(aPosition, 1.0); \n"
        "   vViewPosition = gl_Position.xyz / gl_Position.w; \n "
        "   gl_Position = Projection * gl_Position; \n"
        "} \n";

std::string FragSource = ""
        "#version 120 \n"
        ""
        "varying vec3 vViewPosition; \n"
        "varying vec3 vNormal; \n"
        ""
        "uniform vec3 LightDirection = vec3(-1, -0.5, -1); \n"
        ""
        "float Diffuse(vec3 normal, vec3 lightDir) \n"
        "{ \n"
        "   return clamp(dot(normal, -lightDir), 0.0, 1.0); \n"
        "} \n"
        ""
        "float Specular(vec3 normal, vec3 lightDir, vec3 cameraDir, float power) \n"
        "{ \n"
        "   vec3 halfVec = normalize(lightDir + cameraDir); \n"
        "   return pow(clamp(abs(dot(normal, -halfVec)), 0.0, 1.0), power); "
        "} \n"
        ""
        "void main() \n"
        "{ \n"
        "   vec3 normal = normalize(vNormal); \n"
        "   vec3 lightDir = normalize(LightDirection); \n"
        "   vec3 cameraDir = normalize(vViewPosition); \n"
        ""
        "   vec3 color = vec3(1.0); \n"
        "   float diffuse = Diffuse(normal, lightDir); \n"
        "   float specular = Specular(normal, lightDir, cameraDir, 100); \n"
        ""
        "   gl_FragColor = vec4(color * (diffuse * 0.4 + 0.4 + specular * 0.4), 1.0); \n"
        "} \n";

class LoadAction : public Gui::IAction
{
public:
    LoadAction(Modeler3D* modeler, std::string file) : mModeler(modeler), mFile(file) {}
    ~LoadAction() {}

    void OnActionPerformed(Gui::Widget* widget)
    {
        cout << "Loading file: " << mFile << endl;
        mModeler->LoadObj(mFile);
    }
private:
    Modeler3D* mModeler;
    std::string mFile;
};

class ZoomAction : public Gui::IAction
{
public:
	ZoomAction(Modeler3D* modeler, int32 zoom) : mModeler(modeler), mZoom(zoom) {}
    ~ZoomAction() {}

    void OnActionPerformed(Gui::Widget* widget)
    {
        cout << "Zoom set to: " << mZoom << endl;
        mModeler->SetZoom(mZoom);
    }
private:
    Modeler3D* mModeler;
    int32 mZoom;
};

namespace Core
{

Video::VertexFormat vboFormat = Video::VertexFormat()
        .AddElement(Video::Attribute::Position, 3)
        .AddElement(Video::Attribute::Normal, 3);

struct VertexPosition3Normal3
{
    Vector3f Position;
    Vector3f Normal;
};

Modeler3D::Modeler3D(IBackend* backend)
    : Application(backend),
      mEnv(nullptr),
      mGuiRenderer(nullptr),
      mShader(nullptr),
      mGeometry(nullptr),
      mVbo(nullptr),
      mAngle(0),
	  mMouse(backend->GetWindow()->GetMouse()),
	  mZoom(2)
{
}

Modeler3D::~Modeler3D()
{
}

void Modeler3D::LoadObj(const string& file)
{
    if (mVbo)
    {
        mGeometry->SetVertexBuffer(nullptr);
        mVbo->Release();
        delete mVbo;
    }

    boost::filesystem::path obj(file);
    FileIO objFile;
    objFile.LoadObj(obj);

//    boost::filesystem::path obj(file);
//    FileIO objFile;
//    vector<vector<double>> positionss;
//    vector<vector<double>> textureVertices;
//    vector<vector<double>> normalVertices;
//    vector<vector<vector<int>>> faces;
//    objFile.LoadObj2(obj, positionss, textureVertices, normalVertices, faces);

    vector<VertexPosition3Normal3> vertices;
    vector<vector<double>> positions = objFile.GetGeometricVertices();
    vector<vector<vector<int>>> faces = objFile.GetFaceElements();

    for (uint i = 0; i < faces.size(); i++)
    {
        VertexPosition3Normal3 verts[3];
        for (uint j = 0; j < 3; j++)
        {
            vector<double> pos = positions[faces[i][0][j] - 1];
            for (uint k = 0; k < 3; k++)
            {
                verts[j].Position[k] = pos[k] * 10;
            }
        }
        Vector3f normal = Cross(Normalize( verts[1].Position -  verts[0].Position), Normalize( verts[2].Position -  verts[0].Position));
        verts[0].Normal = normal;
        verts[1].Normal = normal;
        verts[2].Normal = normal;

        vertices.push_back(verts[0]);
        vertices.push_back(verts[1]);
        vertices.push_back(verts[2]);
    }

    mVbo = Graphics->CreateVertexBuffer(vboFormat, vertices.size(), Video::BufferHint::Static);
    mVbo->SetData((float32*)(&vertices[0]), 0, vertices.size());
    mGeometry->SetVertexBuffer(mVbo);
}

void Modeler3D::OnInit()
{
    cout << "Initializing Modeler3D" << endl;

    mGeometry = Graphics->CreateGeometry();

    mEnv = Backend->GetWindow()->GetEnvironment();
    mGuiRenderer = new GuiRenderer(Graphics);
    mShader = Graphics->CreateShader(VertSource, FragSource);

    Gui::Button* elem1 = new Gui::Button(10, 10 + 50 * 0, 80, 40, new LoadAction(this, "Assets/bunny.obj"));
    Gui::Button* elem2 = new Gui::Button(10, 10 + 50 * 1, 80, 40, new LoadAction(this, "Assets/cube.obj"));
    Gui::Button* elem3 = new Gui::Button(10, 10 + 50 * 2, 80, 40, new LoadAction(this, "Assets/dragon.obj"));
    Gui::Button* elem4 = new Gui::Button(10, 10 + 50 * 3, 80, 40, new LoadAction(this, "Assets/pencil.obj"));

    Gui::Widget* elem5 = new Gui::Button(10, 10 + 50 * 0,80,40, new ZoomAction(this, 1));
    Gui::Widget* elem6 = new Gui::Button(10, 10 + 50 * 1,80,40, new ZoomAction(this, 100));
    Gui::Widget* elem7 = new Gui::Button(10, 10 + 50 * 2,80,40, new ZoomAction(this, 1000));
    Gui::Widget* elem8 = new Gui::Button(10, 10 + 50 * 3,80,40, new ZoomAction(this, 2500));

    elem1->SetAlignment(0, 1);
    elem2->SetAlignment(0, 1);
    elem3->SetAlignment(0, 1);
    elem4->SetAlignment(0, 1);

    elem5->SetAlignment(1, 1);
    elem6->SetAlignment(1, 1);
    elem7->SetAlignment(1, 1);
    elem8->SetAlignment(1, 1);

    mEnv->AddWidget(elem1);
    mEnv->AddWidget(elem2);
    mEnv->AddWidget(elem3);
    mEnv->AddWidget(elem4);

    mEnv->AddWidget(elem5);
    mEnv->AddWidget(elem6);
    mEnv->AddWidget(elem7);
    mEnv->AddWidget(elem8);
}

void Modeler3D::OnUpdate(float64 dt)
{
    mAngle += 1.0 * dt;

    mEnv->SetSize(Window->GetWidth(), Window->GetHeight());
    mEnv->Update(dt);
}

void Modeler3D::OnRender()
{
    Graphics->SetClearColor(0.3, 0.3, 0.3);
    Graphics->Clear();

    if (mVbo)
    {
    	int32 amt = mMouse->GetWheelScroll();
    	int32 factor = (mZoom <= 50 ? 2 : (mZoom <= 200 ? 3 : (mZoom <= 1000 ? 4 : 5)));
    	if(amt != 0)
    	{
    		if(amt > 0)
    		{
    			mZoom -= pow(factor,amt);
    		}
    		else
    		{
    			mZoom += pow(factor,abs(amt));
    		}

    		if(mZoom < 1) mZoom = 1;

    		std::cout << mZoom << std::endl;
    	}

        Matrix4f projection = Matrix4f::ToPerspective(Math::ToRadians(70.0f), Graphics->GetAspectRatio(), 0.1f, 3000.0f);
        Matrix4f view = Matrix4f::ToLookAt(Vector3f(0, 1, mZoom), Vector3f::Zero, Vector3f::Up);
        Matrix4f model = Matrix4f::ToYaw(mAngle) * Matrix4f::ToPitch(mAngle * 1.3) * Matrix4f::ToRoll(mAngle * 1.7) * Matrix4f::ToTranslation(Vector3f(0.2, -0.8, 0));
        Matrix3f normalMat(Inverse(Transpose(model)));

        mShader->SetMatrix4f("Projection", projection);
        mShader->SetMatrix4f("View", view);
        mShader->SetMatrix4f("Model", model);
        mShader->SetMatrix3f("NormalMat", normalMat);

        Graphics->SetShader(mShader);
        Graphics->SetGeometry(mGeometry);
        Graphics->Draw(Video::Primitive::TriangleList, 0, mVbo->GetLength() / 3);
    }

    mGuiRenderer->Reset();
    mEnv->Draw(mGuiRenderer);
}

void Modeler3D::SetZoom(int32 zoom) { mZoom = zoom; }

void Modeler3D::OnDestroy()
{
    cout << "Destroying Modeler3D" << endl;
    mGuiRenderer->Release();
    mShader->Release();
    mGeometry->SetVertexBuffer(nullptr);
    mGeometry->Release();
    mVbo->Release();
}

}
<commit_msg>slowed down scrolling for close view<commit_after>#include "Modeler3D.h"

#include <cmath>
#include <iostream>

#include <boost/filesystem.hpp>
#include <GL/glew.h>

#include "GUI/AllWidgets.h"
#include "GUI/IAction.h"
#include "Math/VectorMath.h"

#include "FileIO.h"
#include "GuiRenderer.h"

using namespace std;
using namespace Core;
using namespace Core::Math;
using namespace Video;

std::string VertSource = ""
        "#version 120 \n"
        ""
        "attribute vec3 aPosition; \n"
        "attribute vec3 aNormal; \n"
        ""
        "varying vec3 vViewPosition; \n"
        "varying vec3 vNormal; \n"
        ""
        "uniform mat4 Projection; \n"
        "uniform mat4 View; \n"
        "uniform mat4 Model; \n"
        "uniform mat3 NormalMat; \n"
        ""
        "void main() \n"
        "{ \n"
        "   vNormal = normalize(NormalMat * aNormal); \n"
        "   gl_Position = View * Model * vec4(aPosition, 1.0); \n"
        "   vViewPosition = gl_Position.xyz / gl_Position.w; \n "
        "   gl_Position = Projection * gl_Position; \n"
        "} \n";

std::string FragSource = ""
        "#version 120 \n"
        ""
        "varying vec3 vViewPosition; \n"
        "varying vec3 vNormal; \n"
        ""
        "uniform vec3 LightDirection = vec3(-1, -0.5, -1); \n"
        ""
        "float Diffuse(vec3 normal, vec3 lightDir) \n"
        "{ \n"
        "   return clamp(dot(normal, -lightDir), 0.0, 1.0); \n"
        "} \n"
        ""
        "float Specular(vec3 normal, vec3 lightDir, vec3 cameraDir, float power) \n"
        "{ \n"
        "   vec3 halfVec = normalize(lightDir + cameraDir); \n"
        "   return pow(clamp(abs(dot(normal, -halfVec)), 0.0, 1.0), power); "
        "} \n"
        ""
        "void main() \n"
        "{ \n"
        "   vec3 normal = normalize(vNormal); \n"
        "   vec3 lightDir = normalize(LightDirection); \n"
        "   vec3 cameraDir = normalize(vViewPosition); \n"
        ""
        "   vec3 color = vec3(1.0); \n"
        "   float diffuse = Diffuse(normal, lightDir); \n"
        "   float specular = Specular(normal, lightDir, cameraDir, 100); \n"
        ""
        "   gl_FragColor = vec4(color * (diffuse * 0.4 + 0.4 + specular * 0.4), 1.0); \n"
        "} \n";

class LoadAction : public Gui::IAction
{
public:
    LoadAction(Modeler3D* modeler, std::string file) : mModeler(modeler), mFile(file) {}
    ~LoadAction() {}

    void OnActionPerformed(Gui::Widget* widget)
    {
        cout << "Loading file: " << mFile << endl;
        mModeler->LoadObj(mFile);
    }
private:
    Modeler3D* mModeler;
    std::string mFile;
};

class ZoomAction : public Gui::IAction
{
public:
	ZoomAction(Modeler3D* modeler, int32 zoom) : mModeler(modeler), mZoom(zoom) {}
    ~ZoomAction() {}

    void OnActionPerformed(Gui::Widget* widget)
    {
        cout << "Zoom set to: " << mZoom << endl;
        mModeler->SetZoom(mZoom);
    }
private:
    Modeler3D* mModeler;
    int32 mZoom;
};

namespace Core
{

Video::VertexFormat vboFormat = Video::VertexFormat()
        .AddElement(Video::Attribute::Position, 3)
        .AddElement(Video::Attribute::Normal, 3);

struct VertexPosition3Normal3
{
    Vector3f Position;
    Vector3f Normal;
};

Modeler3D::Modeler3D(IBackend* backend)
    : Application(backend),
      mEnv(nullptr),
      mGuiRenderer(nullptr),
      mShader(nullptr),
      mGeometry(nullptr),
      mVbo(nullptr),
      mAngle(0),
	  mMouse(backend->GetWindow()->GetMouse()),
	  mZoom(2)
{
}

Modeler3D::~Modeler3D()
{
}

void Modeler3D::LoadObj(const string& file)
{
    if (mVbo)
    {
        mGeometry->SetVertexBuffer(nullptr);
        mVbo->Release();
        delete mVbo;
    }

    boost::filesystem::path obj(file);
    FileIO objFile;
    objFile.LoadObj(obj);

//    boost::filesystem::path obj(file);
//    FileIO objFile;
//    vector<vector<double>> positionss;
//    vector<vector<double>> textureVertices;
//    vector<vector<double>> normalVertices;
//    vector<vector<vector<int>>> faces;
//    objFile.LoadObj2(obj, positionss, textureVertices, normalVertices, faces);

    vector<VertexPosition3Normal3> vertices;
    vector<vector<double>> positions = objFile.GetGeometricVertices();
    vector<vector<vector<int>>> faces = objFile.GetFaceElements();

    for (uint i = 0; i < faces.size(); i++)
    {
        VertexPosition3Normal3 verts[3];
        for (uint j = 0; j < 3; j++)
        {
            vector<double> pos = positions[faces[i][0][j] - 1];
            for (uint k = 0; k < 3; k++)
            {
                verts[j].Position[k] = pos[k] * 10;
            }
        }
        Vector3f normal = Cross(Normalize( verts[1].Position -  verts[0].Position), Normalize( verts[2].Position -  verts[0].Position));
        verts[0].Normal = normal;
        verts[1].Normal = normal;
        verts[2].Normal = normal;

        vertices.push_back(verts[0]);
        vertices.push_back(verts[1]);
        vertices.push_back(verts[2]);
    }

    mVbo = Graphics->CreateVertexBuffer(vboFormat, vertices.size(), Video::BufferHint::Static);
    mVbo->SetData((float32*)(&vertices[0]), 0, vertices.size());
    mGeometry->SetVertexBuffer(mVbo);
}

void Modeler3D::OnInit()
{
    cout << "Initializing Modeler3D" << endl;

    mGeometry = Graphics->CreateGeometry();

    mEnv = Backend->GetWindow()->GetEnvironment();
    mGuiRenderer = new GuiRenderer(Graphics);
    mShader = Graphics->CreateShader(VertSource, FragSource);

    Gui::Button* elem1 = new Gui::Button(10, 10 + 50 * 0, 80, 40, new LoadAction(this, "Assets/bunny.obj"));
    Gui::Button* elem2 = new Gui::Button(10, 10 + 50 * 1, 80, 40, new LoadAction(this, "Assets/cube.obj"));
    Gui::Button* elem3 = new Gui::Button(10, 10 + 50 * 2, 80, 40, new LoadAction(this, "Assets/dragon.obj"));
    Gui::Button* elem4 = new Gui::Button(10, 10 + 50 * 3, 80, 40, new LoadAction(this, "Assets/pencil.obj"));

    Gui::Widget* elem5 = new Gui::Button(10, 10 + 50 * 0,80,40, new ZoomAction(this, 1));
    Gui::Widget* elem6 = new Gui::Button(10, 10 + 50 * 1,80,40, new ZoomAction(this, 100));
    Gui::Widget* elem7 = new Gui::Button(10, 10 + 50 * 2,80,40, new ZoomAction(this, 1000));
    Gui::Widget* elem8 = new Gui::Button(10, 10 + 50 * 3,80,40, new ZoomAction(this, 2500));

    elem1->SetAlignment(0, 1);
    elem2->SetAlignment(0, 1);
    elem3->SetAlignment(0, 1);
    elem4->SetAlignment(0, 1);

    elem5->SetAlignment(1, 1);
    elem6->SetAlignment(1, 1);
    elem7->SetAlignment(1, 1);
    elem8->SetAlignment(1, 1);

    mEnv->AddWidget(elem1);
    mEnv->AddWidget(elem2);
    mEnv->AddWidget(elem3);
    mEnv->AddWidget(elem4);

    mEnv->AddWidget(elem5);
    mEnv->AddWidget(elem6);
    mEnv->AddWidget(elem7);
    mEnv->AddWidget(elem8);
}

void Modeler3D::OnUpdate(float64 dt)
{
    mAngle += 1.0 * dt;

    mEnv->SetSize(Window->GetWidth(), Window->GetHeight());
    mEnv->Update(dt);
}

void Modeler3D::OnRender()
{
    Graphics->SetClearColor(0.3, 0.3, 0.3);
    Graphics->Clear();

    if (mVbo)
    {
    	int32 amt = mMouse->GetWheelScroll();
    	if(amt != 0)
    	{
        	amt = (amt > 4 ? 4 : amt);
        	amt = (amt < -4 ? -4 : amt);
        	int32 factor = (mZoom <= 50 ? 1 : (mZoom <= 200 ? 2 : (mZoom <= 1000 ? 3 : 4)));
    		if(amt > 0)
    		{
    			mZoom -= pow(factor,amt);
    		}
    		else
    		{
    			mZoom += pow(factor,abs(amt));
    		}

    		if(mZoom < 1) mZoom = 1;
    	}

        Matrix4f projection = Matrix4f::ToPerspective(Math::ToRadians(70.0f), Graphics->GetAspectRatio(), 0.1f, 3000.0f);
        Matrix4f view = Matrix4f::ToLookAt(Vector3f(0, 1, mZoom), Vector3f::Zero, Vector3f::Up);
        Matrix4f model = Matrix4f::ToYaw(mAngle) * Matrix4f::ToPitch(mAngle * 1.3) * Matrix4f::ToRoll(mAngle * 1.7) * Matrix4f::ToTranslation(Vector3f(0.2, -0.8, 0));
        Matrix3f normalMat(Inverse(Transpose(model)));

        mShader->SetMatrix4f("Projection", projection);
        mShader->SetMatrix4f("View", view);
        mShader->SetMatrix4f("Model", model);
        mShader->SetMatrix3f("NormalMat", normalMat);

        Graphics->SetShader(mShader);
        Graphics->SetGeometry(mGeometry);
        Graphics->Draw(Video::Primitive::TriangleList, 0, mVbo->GetLength() / 3);
    }

    mGuiRenderer->Reset();
    mEnv->Draw(mGuiRenderer);
}

void Modeler3D::SetZoom(int32 zoom) { mZoom = zoom; }

void Modeler3D::OnDestroy()
{
    cout << "Destroying Modeler3D" << endl;
    mGuiRenderer->Release();
    mShader->Release();
    mGeometry->SetVertexBuffer(nullptr);
    mGeometry->Release();
    mVbo->Release();
}

}
<|endoftext|>


<commit_before>#include "SF2Reader.h"
#include "SF2Sound.h"
#include "SFZSample.h"
#include "RIFF.h"
#include "SF2.h"
#include "SF2Generator.h"
#include "SFZDebug.h"

SF2Reader::SF2Reader(SF2Sound* soundIn, const File& fileIn)
	: sound(soundIn)
{
	file = fileIn.createInputStream();
}

SF2Reader::~SF2Reader()
{
	delete file;
}

void SF2Reader::read()
{
	if (file == NULL) {
		sound->addError("Couldn't open file.");
		return;
		}

	// Read the hydra.
	SF2::Hydra hydra;
	file->setPosition(0);
	RIFFChunk riffChunk;
	riffChunk.ReadFrom(file);
	while (file->getPosition() < riffChunk.End()) {
		RIFFChunk chunk;
		chunk.ReadFrom(file);
		if (FourCCEquals(chunk.id, "pdta")) {
			hydra.ReadFrom(file, chunk.End());
			break;
			}
		chunk.SeekAfter(file);
		}
	if (!hydra.IsComplete()) {
		sound->addError("Invalid SF2 file (missing or incomplete hydra).");
		return;
		}

	// Read each preset.
	for (int whichPreset = 0; whichPreset < hydra.phdrNumItems - 1; ++whichPreset) {
		SF2::phdr* phdr = &hydra.phdrItems[whichPreset];
		SF2Sound::Preset* preset = new SF2Sound::Preset(phdr->presetName, phdr->preset);
		sound->addPreset(preset);

		// Zones.
		//*** TODO: Handle global zone.
		int zoneEnd = phdr[1].presetBagNdx;
		for (int whichZone = phdr->presetBagNdx; whichZone < zoneEnd; ++whichZone) {
			SF2::pbag* pbag = &hydra.pbagItems[whichZone];
			SFZRegion presetRegion;
			presetRegion.clearForSF2();

			// Generators.
			int genEnd = pbag[1].genNdx;
			for (int whichGen = pbag->genNdx; whichGen < genEnd; ++whichGen) {
				SF2::pgen* pgen = &hydra.pgenItems[whichGen];

				// Instrument.
				if (pgen->genOper == SF2Generator::instrument) {
					word whichInst = pgen->genAmount.wordAmount;
					if (whichInst < hydra.instNumItems) {
						SFZRegion instRegion = presetRegion;
						SF2::inst* inst = &hydra.instItems[whichInst];
						int zoneEnd = inst[1].instBagNdx;
						for (int whichZone = inst->instBagNdx; whichZone < zoneEnd; ++whichZone) {
							SF2::ibag* ibag = &hydra.ibagItems[whichZone];

							// Generators.
							SFZRegion zoneRegion = instRegion;
							int genEnd = ibag[1].instGenNdx;
							for (int whichGen = ibag->instGenNdx; whichGen < genEnd; ++whichGen) {
								SF2::igen* igen = &hydra.igenItems[whichGen];
								if (igen->genOper == SF2Generator::sampleID) {
									int whichSample = igen->genAmount.wordAmount;
									SF2::shdr* shdr = &hydra.shdrItems[whichSample];
									zoneRegion.offset += shdr->start;
									zoneRegion.end += shdr->end;
									zoneRegion.loop_start += shdr->startLoop;
									zoneRegion.loop_end += shdr->endLoop;
									if (shdr->endLoop > 0)
										zoneRegion.loop_end -= 1;
									if (zoneRegion.pitch_keycenter == -1)
										zoneRegion.pitch_keycenter = shdr->originalPitch;
									zoneRegion.tune += shdr->pitchCorrection;

									SFZRegion* newRegion = new SFZRegion();
									*newRegion = zoneRegion;
									preset->addRegion(newRegion);
									}
								else
									addGeneratorToRegion(igen->genOper, &igen->genAmount, &zoneRegion);
								}

							// Modulators.
							int modEnd = ibag[1].instModNdx;
							int whichMod = ibag->instModNdx;
							if (whichMod < modEnd)
								sound->addUnsupportedOpcode("any modulator");
							}
						}
					else
						sound->addError("Instrument out of range.");
					}

				// Other generators.
				else
					addGeneratorToRegion(pgen->genOper, &pgen->genAmount, &presetRegion);
				}

			// Modulators.
			int modEnd = pbag[1].modNdx;
			int whichMod = pbag->modNdx;
			if (whichMod < modEnd)
				sound->addUnsupportedOpcode("any modulator");
			}
		}

	// Check the samples for the sample rate.
	dword sampleRate = 0;
	for (int whichSample = 0; whichSample < hydra.shdrNumItems - 1; ++whichSample) {
		SF2::shdr* shdr = &hydra.shdrItems[whichSample];
		if (whichSample == 0)
			sampleRate = shdr->sampleRate;
		else if (shdr->sampleRate != sampleRate)
			sound->addError("SFZero doesn't support SF2's that use multiple sample rates.");
		}
	this->sampleRate = sampleRate;
}

SFZSample* SF2Reader::readSamples(double sampleRate, double* progressVar, Thread* thread)
{
	static const unsigned long bufferSize = 32768;

	if (file == NULL) {
		sound->addError("Couldn't open file.");
		return NULL;
		}

	// Find the "sdta" chunk.
	file->setPosition(0);
	RIFFChunk riffChunk;
	riffChunk.ReadFrom(file);
	bool found = false;
	RIFFChunk chunk;
	while (file->getPosition() < riffChunk.End()) {
		chunk.ReadFrom(file);
		if (FourCCEquals(chunk.id, "sdta")) {
			found = true;
			break;
			}
		chunk.SeekAfter(file);
		}
	if (!found) {
		sound->addError("SF2 is missing its \"smpl\" chunk.");
		return NULL;
		}

	// Allocate the AudioSampleBuffer.
	unsigned long numSamples = chunk.size / sizeof(short);
	AudioSampleBuffer* sampleBuffer = new AudioSampleBuffer(1, numSamples);

	// Read and convert.
	short* buffer = new short[bufferSize];
	unsigned long samplesLeft = numSamples;
	float* out = sampleBuffer->getSampleData(0);
	while (samplesLeft > 0) {
		// Read the buffer.
		unsigned long samplesToRead = bufferSize;
		if (samplesToRead > samplesLeft)
			samplesToRead = samplesLeft;
		file->read(buffer, samplesToRead * sizeof(short));

		// Convert from signed 16-bit to float.
		unsigned long samplesToConvert = samplesToRead;
		short* in = buffer;
		for (; samplesToConvert > 0; --samplesToConvert) {
			// If we ever need to compile for big-endian platforms, we'll need to
			// byte-swap here.
			*out++ = *in++ / 32767.0;
			}

		samplesLeft -= samplesToRead;

		if (progressVar)
			*progressVar = (float) (numSamples - samplesLeft) / numSamples;
		if (thread && thread->threadShouldExit()) {
			delete buffer;
			delete sampleBuffer;
			return NULL;
			}
		}
	delete buffer;

	if (progressVar)
		*progressVar = 1.0;

	return new SFZSample(sampleBuffer, sampleRate);
}

void SF2Reader::addGeneratorToRegion(
	word genOper, SF2::genAmountType* amount, SFZRegion* region)
{
	switch (genOper) {
		case SF2Generator::startAddrsOffset:
			region->offset += amount->shortAmount;
			break;
		case SF2Generator::endAddrsOffset:
			region->end += amount->shortAmount;
			break;
		case SF2Generator::startloopAddrsOffset:
			region->loop_start += amount->shortAmount;
			break;
		case SF2Generator::endloopAddrsOffset:
			region->loop_end += amount->shortAmount;
			break;
		case SF2Generator::startAddrsCoarseOffset:
			region->offset += amount->shortAmount * 32768;
			break;
		case SF2Generator::endAddrsCoarseOffset:
			region->end += amount->shortAmount * 32768;
			break;
		case SF2Generator::pan:
			region->pan  = amount->shortAmount * (2.0 / 10.0);
			break;
		case SF2Generator::delayVolEnv:
			region->ampeg.delay = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::attackVolEnv:
			region->ampeg.attack = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::holdVolEnv:
			region->ampeg.hold = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::decayVolEnv:
			region->ampeg.decay = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::sustainVolEnv:
			region->ampeg.sustain = 100.0 - amount->shortAmount / 10.0;
			break;
		case SF2Generator::releaseVolEnv:
			region->ampeg.release = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::keyRange:
			region->lokey = amount->range.lo;
			region->hikey = amount->range.hi;
			break;
		case SF2Generator::velRange:
			region->lovel = amount->range.lo;
			region->hivel = amount->range.hi;
			break;
		case SF2Generator::startloopAddrsCoarseOffset:
			region->loop_start += amount->shortAmount * 32768;
			break;
		case SF2Generator::initialAttenuation:
			region->volume = -amount->shortAmount / 10.0;
			break;
		case SF2Generator::endloopAddrsCoarseOffset:
			region->loop_end += amount->shortAmount * 32768;
			break;
		case SF2Generator::coarseTune:
			region->transpose = amount->shortAmount;
			break;
		case SF2Generator::fineTune:
			region->tune = amount->shortAmount;
			break;
		case SF2Generator::sampleModes:
			{
				SFZRegion::LoopMode loopModes[] = {
					SFZRegion::no_loop, SFZRegion::loop_continuous,
					SFZRegion::no_loop, SFZRegion::loop_sustain };
				region->loop_mode = loopModes[amount->wordAmount & 0x03];
			}
			break;
		case SF2Generator::scaleTuning:
			region->pitch_keytrack = amount->shortAmount;
			break;
		case SF2Generator::exclusiveClass:
			region->group = region->off_by = amount->wordAmount;
			break;
		case SF2Generator::overridingRootKey:
			region->pitch_keycenter = amount->shortAmount;
			break;
		case SF2Generator::endOper:
			// Ignore.
			break;

		case SF2Generator::modLfoToPitch:
		case SF2Generator::vibLfoToPitch:
		case SF2Generator::modEnvToPitch:
		case SF2Generator::initialFilterFc:
		case SF2Generator::initialFilterQ:
		case SF2Generator::modLfoToFilterFc:
		case SF2Generator::modEnvToFilterFc:
		case SF2Generator::modLfoToVolume:
		case SF2Generator::unused1:
		case SF2Generator::chorusEffectsSend:
		case SF2Generator::reverbEffectsSend:
		case SF2Generator::unused2:
		case SF2Generator::unused3:
		case SF2Generator::unused4:
		case SF2Generator::delayModLFO:
		case SF2Generator::freqModLFO:
		case SF2Generator::delayVibLFO:
		case SF2Generator::freqVibLFO:
		case SF2Generator::delayModEnv:
		case SF2Generator::attackModEnv:
		case SF2Generator::holdModEnv:
		case SF2Generator::decayModEnv:
		case SF2Generator::sustainModEnv:
		case SF2Generator::releaseModEnv:
		case SF2Generator::keynumToModEnvHold:
		case SF2Generator::keynumToModEnvDecay:
		case SF2Generator::keynumToVolEnvHold:
		case SF2Generator::keynumToVolEnvDecay:
		case SF2Generator::instrument:
			// Only allowed in certain places, where we already special-case it.
		case SF2Generator::reserved1:
		case SF2Generator::keynum:
		case SF2Generator::velocity:
		case SF2Generator::reserved2:
		case SF2Generator::sampleID:
			// Only allowed in certain places, where we already special-case it.
		case SF2Generator::reserved3:
		case SF2Generator::unused5:
			{
				const SF2Generator* generator = GeneratorFor(genOper);
				sound->addUnsupportedOpcode(generator->name);
			}
			break;
		}
}

float SF2Reader::timecents2Secs(short timecents)
{
	return pow(2.0, timecents / 1200.0);
}

<commit_msg>SF2: Only one message for multiple sample rates.<commit_after>#include "SF2Reader.h"
#include "SF2Sound.h"
#include "SFZSample.h"
#include "RIFF.h"
#include "SF2.h"
#include "SF2Generator.h"
#include "SFZDebug.h"

SF2Reader::SF2Reader(SF2Sound* soundIn, const File& fileIn)
	: sound(soundIn)
{
	file = fileIn.createInputStream();
}

SF2Reader::~SF2Reader()
{
	delete file;
}

void SF2Reader::read()
{
	if (file == NULL) {
		sound->addError("Couldn't open file.");
		return;
		}

	// Read the hydra.
	SF2::Hydra hydra;
	file->setPosition(0);
	RIFFChunk riffChunk;
	riffChunk.ReadFrom(file);
	while (file->getPosition() < riffChunk.End()) {
		RIFFChunk chunk;
		chunk.ReadFrom(file);
		if (FourCCEquals(chunk.id, "pdta")) {
			hydra.ReadFrom(file, chunk.End());
			break;
			}
		chunk.SeekAfter(file);
		}
	if (!hydra.IsComplete()) {
		sound->addError("Invalid SF2 file (missing or incomplete hydra).");
		return;
		}

	// Read each preset.
	for (int whichPreset = 0; whichPreset < hydra.phdrNumItems - 1; ++whichPreset) {
		SF2::phdr* phdr = &hydra.phdrItems[whichPreset];
		SF2Sound::Preset* preset = new SF2Sound::Preset(phdr->presetName, phdr->preset);
		sound->addPreset(preset);

		// Zones.
		//*** TODO: Handle global zone.
		int zoneEnd = phdr[1].presetBagNdx;
		for (int whichZone = phdr->presetBagNdx; whichZone < zoneEnd; ++whichZone) {
			SF2::pbag* pbag = &hydra.pbagItems[whichZone];
			SFZRegion presetRegion;
			presetRegion.clearForSF2();

			// Generators.
			int genEnd = pbag[1].genNdx;
			for (int whichGen = pbag->genNdx; whichGen < genEnd; ++whichGen) {
				SF2::pgen* pgen = &hydra.pgenItems[whichGen];

				// Instrument.
				if (pgen->genOper == SF2Generator::instrument) {
					word whichInst = pgen->genAmount.wordAmount;
					if (whichInst < hydra.instNumItems) {
						SFZRegion instRegion = presetRegion;
						SF2::inst* inst = &hydra.instItems[whichInst];
						int zoneEnd = inst[1].instBagNdx;
						for (int whichZone = inst->instBagNdx; whichZone < zoneEnd; ++whichZone) {
							SF2::ibag* ibag = &hydra.ibagItems[whichZone];

							// Generators.
							SFZRegion zoneRegion = instRegion;
							int genEnd = ibag[1].instGenNdx;
							for (int whichGen = ibag->instGenNdx; whichGen < genEnd; ++whichGen) {
								SF2::igen* igen = &hydra.igenItems[whichGen];
								if (igen->genOper == SF2Generator::sampleID) {
									int whichSample = igen->genAmount.wordAmount;
									SF2::shdr* shdr = &hydra.shdrItems[whichSample];
									zoneRegion.offset += shdr->start;
									zoneRegion.end += shdr->end;
									zoneRegion.loop_start += shdr->startLoop;
									zoneRegion.loop_end += shdr->endLoop;
									if (shdr->endLoop > 0)
										zoneRegion.loop_end -= 1;
									if (zoneRegion.pitch_keycenter == -1)
										zoneRegion.pitch_keycenter = shdr->originalPitch;
									zoneRegion.tune += shdr->pitchCorrection;

									SFZRegion* newRegion = new SFZRegion();
									*newRegion = zoneRegion;
									preset->addRegion(newRegion);
									}
								else
									addGeneratorToRegion(igen->genOper, &igen->genAmount, &zoneRegion);
								}

							// Modulators.
							int modEnd = ibag[1].instModNdx;
							int whichMod = ibag->instModNdx;
							if (whichMod < modEnd)
								sound->addUnsupportedOpcode("any modulator");
							}
						}
					else
						sound->addError("Instrument out of range.");
					}

				// Other generators.
				else
					addGeneratorToRegion(pgen->genOper, &pgen->genAmount, &presetRegion);
				}

			// Modulators.
			int modEnd = pbag[1].modNdx;
			int whichMod = pbag->modNdx;
			if (whichMod < modEnd)
				sound->addUnsupportedOpcode("any modulator");
			}
		}

	// Check the samples for the sample rate.
	dword sampleRate = 0;
	bool multipleSampleRates = false;
	for (int whichSample = 0; whichSample < hydra.shdrNumItems - 1; ++whichSample) {
		SF2::shdr* shdr = &hydra.shdrItems[whichSample];
		if (whichSample == 0)
			sampleRate = shdr->sampleRate;
		else if (shdr->sampleRate != sampleRate)
			multipleSampleRates = true;
		}
	this->sampleRate = sampleRate;
	if (multipleSampleRates)
		sound->addError("SFZero doesn't support SF2's that use multiple sample rates.");
}

SFZSample* SF2Reader::readSamples(double sampleRate, double* progressVar, Thread* thread)
{
	static const unsigned long bufferSize = 32768;

	if (file == NULL) {
		sound->addError("Couldn't open file.");
		return NULL;
		}

	// Find the "sdta" chunk.
	file->setPosition(0);
	RIFFChunk riffChunk;
	riffChunk.ReadFrom(file);
	bool found = false;
	RIFFChunk chunk;
	while (file->getPosition() < riffChunk.End()) {
		chunk.ReadFrom(file);
		if (FourCCEquals(chunk.id, "sdta")) {
			found = true;
			break;
			}
		chunk.SeekAfter(file);
		}
	if (!found) {
		sound->addError("SF2 is missing its \"smpl\" chunk.");
		return NULL;
		}

	// Allocate the AudioSampleBuffer.
	unsigned long numSamples = chunk.size / sizeof(short);
	AudioSampleBuffer* sampleBuffer = new AudioSampleBuffer(1, numSamples);

	// Read and convert.
	short* buffer = new short[bufferSize];
	unsigned long samplesLeft = numSamples;
	float* out = sampleBuffer->getSampleData(0);
	while (samplesLeft > 0) {
		// Read the buffer.
		unsigned long samplesToRead = bufferSize;
		if (samplesToRead > samplesLeft)
			samplesToRead = samplesLeft;
		file->read(buffer, samplesToRead * sizeof(short));

		// Convert from signed 16-bit to float.
		unsigned long samplesToConvert = samplesToRead;
		short* in = buffer;
		for (; samplesToConvert > 0; --samplesToConvert) {
			// If we ever need to compile for big-endian platforms, we'll need to
			// byte-swap here.
			*out++ = *in++ / 32767.0;
			}

		samplesLeft -= samplesToRead;

		if (progressVar)
			*progressVar = (float) (numSamples - samplesLeft) / numSamples;
		if (thread && thread->threadShouldExit()) {
			delete buffer;
			delete sampleBuffer;
			return NULL;
			}
		}
	delete buffer;

	if (progressVar)
		*progressVar = 1.0;

	return new SFZSample(sampleBuffer, sampleRate);
}

void SF2Reader::addGeneratorToRegion(
	word genOper, SF2::genAmountType* amount, SFZRegion* region)
{
	switch (genOper) {
		case SF2Generator::startAddrsOffset:
			region->offset += amount->shortAmount;
			break;
		case SF2Generator::endAddrsOffset:
			region->end += amount->shortAmount;
			break;
		case SF2Generator::startloopAddrsOffset:
			region->loop_start += amount->shortAmount;
			break;
		case SF2Generator::endloopAddrsOffset:
			region->loop_end += amount->shortAmount;
			break;
		case SF2Generator::startAddrsCoarseOffset:
			region->offset += amount->shortAmount * 32768;
			break;
		case SF2Generator::endAddrsCoarseOffset:
			region->end += amount->shortAmount * 32768;
			break;
		case SF2Generator::pan:
			region->pan  = amount->shortAmount * (2.0 / 10.0);
			break;
		case SF2Generator::delayVolEnv:
			region->ampeg.delay = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::attackVolEnv:
			region->ampeg.attack = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::holdVolEnv:
			region->ampeg.hold = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::decayVolEnv:
			region->ampeg.decay = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::sustainVolEnv:
			region->ampeg.sustain = 100.0 - amount->shortAmount / 10.0;
			break;
		case SF2Generator::releaseVolEnv:
			region->ampeg.release = timecents2Secs(amount->shortAmount);
			break;
		case SF2Generator::keyRange:
			region->lokey = amount->range.lo;
			region->hikey = amount->range.hi;
			break;
		case SF2Generator::velRange:
			region->lovel = amount->range.lo;
			region->hivel = amount->range.hi;
			break;
		case SF2Generator::startloopAddrsCoarseOffset:
			region->loop_start += amount->shortAmount * 32768;
			break;
		case SF2Generator::initialAttenuation:
			region->volume = -amount->shortAmount / 10.0;
			break;
		case SF2Generator::endloopAddrsCoarseOffset:
			region->loop_end += amount->shortAmount * 32768;
			break;
		case SF2Generator::coarseTune:
			region->transpose = amount->shortAmount;
			break;
		case SF2Generator::fineTune:
			region->tune = amount->shortAmount;
			break;
		case SF2Generator::sampleModes:
			{
				SFZRegion::LoopMode loopModes[] = {
					SFZRegion::no_loop, SFZRegion::loop_continuous,
					SFZRegion::no_loop, SFZRegion::loop_sustain };
				region->loop_mode = loopModes[amount->wordAmount & 0x03];
			}
			break;
		case SF2Generator::scaleTuning:
			region->pitch_keytrack = amount->shortAmount;
			break;
		case SF2Generator::exclusiveClass:
			region->group = region->off_by = amount->wordAmount;
			break;
		case SF2Generator::overridingRootKey:
			region->pitch_keycenter = amount->shortAmount;
			break;
		case SF2Generator::endOper:
			// Ignore.
			break;

		case SF2Generator::modLfoToPitch:
		case SF2Generator::vibLfoToPitch:
		case SF2Generator::modEnvToPitch:
		case SF2Generator::initialFilterFc:
		case SF2Generator::initialFilterQ:
		case SF2Generator::modLfoToFilterFc:
		case SF2Generator::modEnvToFilterFc:
		case SF2Generator::modLfoToVolume:
		case SF2Generator::unused1:
		case SF2Generator::chorusEffectsSend:
		case SF2Generator::reverbEffectsSend:
		case SF2Generator::unused2:
		case SF2Generator::unused3:
		case SF2Generator::unused4:
		case SF2Generator::delayModLFO:
		case SF2Generator::freqModLFO:
		case SF2Generator::delayVibLFO:
		case SF2Generator::freqVibLFO:
		case SF2Generator::delayModEnv:
		case SF2Generator::attackModEnv:
		case SF2Generator::holdModEnv:
		case SF2Generator::decayModEnv:
		case SF2Generator::sustainModEnv:
		case SF2Generator::releaseModEnv:
		case SF2Generator::keynumToModEnvHold:
		case SF2Generator::keynumToModEnvDecay:
		case SF2Generator::keynumToVolEnvHold:
		case SF2Generator::keynumToVolEnvDecay:
		case SF2Generator::instrument:
			// Only allowed in certain places, where we already special-case it.
		case SF2Generator::reserved1:
		case SF2Generator::keynum:
		case SF2Generator::velocity:
		case SF2Generator::reserved2:
		case SF2Generator::sampleID:
			// Only allowed in certain places, where we already special-case it.
		case SF2Generator::reserved3:
		case SF2Generator::unused5:
			{
				const SF2Generator* generator = GeneratorFor(genOper);
				sound->addUnsupportedOpcode(generator->name);
			}
			break;
		}
}

float SF2Reader::timecents2Secs(short timecents)
{
	return pow(2.0, timecents / 1200.0);
}

<|endoftext|>