<commit_before>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <utility>

#include "config.hpp"
#include "compute.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "incomes.hpp"

budget::status budget::compute_year_status(data_cache & cache) {
    auto today = budget::local_day();
    return compute_year_status(cache, today.year(), today.month());
}

budget::status budget::compute_year_status(data_cache & cache, year year) {
    return compute_year_status(cache, year, 12);
}

budget::status budget::compute_year_status(data_cache & cache, year year, month month) {
    budget::status status;

    auto sm = start_month(year);

    status.expenses = accumulate_amount(all_expenses_between(cache, year, sm, month));
    status.earnings = accumulate_amount(all_earnings_between(cache, year, sm, month));

    for (unsigned short i = sm; i <= month; ++i) {
        status.budget += accumulate_amount(all_accounts(cache, year, i));
        status.base_income += get_base_income(cache, budget::date(year, i, 1));
    }

    status.balance = status.budget + status.earnings - status.expenses;
    status.income  = status.base_income + status.earnings;
    status.savings = status.income - status.earnings;

    status.taxes = 0;
    if (config_contains("taxes_account")) {
        auto taxes_account = config_value("taxes_account");

        if (account_exists(taxes_account)) {
            auto account_id = get_account(taxes_account, year, month).id;

            status.taxes = accumulate_amount(all_expenses_between(cache, account_id, year, sm, month));
        }
    }

    return status;
}

budget::status budget::compute_month_status(data_cache & cache) {
    auto today = budget::local_day();
    return compute_month_status(cache, today.year(), today.month());
}

budget::status budget::compute_month_status(data_cache & cache, month month) {
    auto today = budget::local_day();
    return compute_month_status(cache, today.year(), month);
}

budget::status budget::compute_month_status(data_cache & cache, year year, month month) {
    budget::status status;

    status.expenses    = accumulate_amount(all_expenses_month(cache, year, month));
    status.earnings    = accumulate_amount(all_earnings_month(cache, year, month));
    status.budget      = accumulate_amount(all_accounts(cache, year, month));
    status.balance     = status.budget + status.earnings - status.expenses;
    status.base_income = get_base_income(cache, budget::date(year, month, 1));
    status.income      = status.base_income + status.earnings;
    status.savings     = status.income - status.expenses;

    status.taxes = 0;
    if (config_contains("taxes_account")) {
        auto taxes_account = config_value("taxes_account");

        if (account_exists(taxes_account)) {
            auto account_id = get_account(taxes_account, year, month).id;

            status.taxes = accumulate_amount(all_expenses_month(cache, account_id, year, month));
        }
    }

    return status;
}

budget::status budget::compute_avg_month_status(data_cache & cache) {
    auto today = budget::local_day();
    return compute_avg_month_status(cache, today.year(), today.month());
}

budget::status budget::compute_avg_month_status(data_cache & cache, month month) {
    auto today = budget::local_day();
    return compute_avg_month_status(cache, today.year(), month);
}

budget::status budget::compute_avg_month_status(data_cache & cache, year year, month month) {
    budget::status avg_status;

    for (budget::month m = 1; m < month; m = m + 1) {
        auto status = compute_month_status(cache, year, m);

        avg_status.expenses += status.expenses;
        avg_status.earnings += status.earnings;
        avg_status.budget += status.budget;
        avg_status.balance += status.balance;
        avg_status.taxes += status.taxes;
        avg_status.savings += status.savings;
    }

    if (month.value > 1) {
        avg_status.expenses /= month.value - 1;
        avg_status.taxes /= month.value - 1;
        avg_status.earnings /= month.value - 1;
        avg_status.budget /= month.value - 1;
        avg_status.balance /= month.value - 1;
        avg_status.savings /= month.value - 1;
    }

    return avg_status;
}
<commit_msg>Fix computation of savings<commit_after>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <utility>

#include "config.hpp"
#include "compute.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "incomes.hpp"

budget::status budget::compute_year_status(data_cache & cache) {
    auto today = budget::local_day();
    return compute_year_status(cache, today.year(), today.month());
}

budget::status budget::compute_year_status(data_cache & cache, year year) {
    return compute_year_status(cache, year, 12);
}

budget::status budget::compute_year_status(data_cache & cache, year year, month month) {
    budget::status status;

    auto sm = start_month(year);

    status.expenses = accumulate_amount(all_expenses_between(cache, year, sm, month));
    status.earnings = accumulate_amount(all_earnings_between(cache, year, sm, month));

    for (unsigned short i = sm; i <= month; ++i) {
        status.budget += accumulate_amount(all_accounts(cache, year, i));
        status.base_income += get_base_income(cache, budget::date(year, i, 1));
    }

    status.balance = status.budget + status.earnings - status.expenses;
    status.income  = status.base_income + status.earnings;
    status.savings = status.income - status.expenses;

    status.taxes = 0;
    if (config_contains("taxes_account")) {
        auto taxes_account = config_value("taxes_account");

        if (account_exists(taxes_account)) {
            auto account_id = get_account(taxes_account, year, month).id;

            status.taxes = accumulate_amount(all_expenses_between(cache, account_id, year, sm, month));
        }
    }

    return status;
}

budget::status budget::compute_month_status(data_cache & cache) {
    auto today = budget::local_day();
    return compute_month_status(cache, today.year(), today.month());
}

budget::status budget::compute_month_status(data_cache & cache, month month) {
    auto today = budget::local_day();
    return compute_month_status(cache, today.year(), month);
}

budget::status budget::compute_month_status(data_cache & cache, year year, month month) {
    budget::status status;

    status.expenses    = accumulate_amount(all_expenses_month(cache, year, month));
    status.earnings    = accumulate_amount(all_earnings_month(cache, year, month));
    status.budget      = accumulate_amount(all_accounts(cache, year, month));
    status.balance     = status.budget + status.earnings - status.expenses;
    status.base_income = get_base_income(cache, budget::date(year, month, 1));
    status.income      = status.base_income + status.earnings;
    status.savings     = status.income - status.expenses;

    status.taxes = 0;
    if (config_contains("taxes_account")) {
        auto taxes_account = config_value("taxes_account");

        if (account_exists(taxes_account)) {
            auto account_id = get_account(taxes_account, year, month).id;

            status.taxes = accumulate_amount(all_expenses_month(cache, account_id, year, month));
        }
    }

    return status;
}

budget::status budget::compute_avg_month_status(data_cache & cache) {
    auto today = budget::local_day();
    return compute_avg_month_status(cache, today.year(), today.month());
}

budget::status budget::compute_avg_month_status(data_cache & cache, month month) {
    auto today = budget::local_day();
    return compute_avg_month_status(cache, today.year(), month);
}

budget::status budget::compute_avg_month_status(data_cache & cache, year year, month month) {
    budget::status avg_status;

    for (budget::month m = 1; m < month; m = m + 1) {
        auto status = compute_month_status(cache, year, m);

        avg_status.expenses += status.expenses;
        avg_status.earnings += status.earnings;
        avg_status.budget += status.budget;
        avg_status.balance += status.balance;
        avg_status.taxes += status.taxes;
        avg_status.savings += status.savings;
    }

    if (month.value > 1) {
        avg_status.expenses /= month.value - 1;
        avg_status.taxes /= month.value - 1;
        avg_status.earnings /= month.value - 1;
        avg_status.budget /= month.value - 1;
        avg_status.balance /= month.value - 1;
        avg_status.savings /= month.value - 1;
    }

    return avg_status;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <future>

int evaluateSum (int a, int b)
{
	return a + b;
}

int main(int argc, char* argv[])
{
	auto result = std::async(evaluateSum,2,3);
	std::cout << "2 + 3 = " << result.get() << std::endl;
}

<commit_msg>Improve clarity<commit_after>#include <iostream>
#include <future>

int evaluateSum (int a, int b)
{
	return a + b;
}

int main(int argc, char* argv[])
{
	std::future<int> result = std::async(evaluateSum,2,3);
	std::cout << "2 + 3 = " << result.get() << std::endl;
}

<|endoftext|>


<commit_before>/*
The MIT License

Copyright (c) 2011 by Jorrit Tyberghein

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

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

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

#include <crystalspace.h>

#include "meshfactmodel.h"
#include "edcommon/tools.h"
#include "propclass/dynworld.h"

using namespace Ares;

void MeshCollectionValue::UpdateChildren ()
{
  if (!dirty) return;
  dirty = false;
  ReleaseChildren ();
  iMeshFactoryList* list = engine->GetMeshFactories ();
  for (size_t i = 0 ; i < size_t (list->GetCount ()) ; i++)
  {
    iMeshFactoryWrapper* fact = list->Get (i);
    const char* name = fact->QueryObject ()->GetName ();
    if (!dynworld->FindFactory (name))
      NewCompositeChild (VALUE_STRING, "name", name, VALUE_NONE);
  }
}

<commit_msg>The list of factories in the dynamic factory editor is now sorted for easier finding of new factories.<commit_after>/*
The MIT License

Copyright (c) 2011 by Jorrit Tyberghein

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

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

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

#include <crystalspace.h>

#include "meshfactmodel.h"
#include "edcommon/tools.h"
#include "propclass/dynworld.h"

using namespace Ares;

void MeshCollectionValue::UpdateChildren ()
{
  if (!dirty) return;
  dirty = false;
  ReleaseChildren ();
  iMeshFactoryList* list = engine->GetMeshFactories ();
  csStringArray names;
  for (size_t i = 0 ; i < size_t (list->GetCount ()) ; i++)
  {
    iMeshFactoryWrapper* fact = list->Get (i);
    const char* name = fact->QueryObject ()->GetName ();
    if (!dynworld->FindFactory (name))
      names.Push (name);
  }
  names.Sort ();

  for (size_t i = 0 ; i < names.GetSize () ; i++)
  {
    NewCompositeChild (VALUE_STRING, "name", names[i], VALUE_NONE);
  }
}

<|endoftext|>


<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013-2016 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @file
//! @brief This contains the implementation of the N-dimensional array class.

#pragma once

#include <iostream>
#include <memory>
#include <numeric>
#include <stdexcept>

#include <DO/Sara/Core/MultiArray/MultiArrayView.hpp>

namespace DO { namespace Sara {

  //! @brief The multidimensional array class.
  template <typename MultiArrayView, template <typename> class Allocator>
  class MultiArrayBase : public MultiArrayView
  {
    //! @{
    //! Convenience typedefs.
    using self_type =  MultiArrayBase;
    using base_type = MultiArrayView;
    //! @}

    using base_type::_begin;
    using base_type::_end;
    using base_type::_sizes;
    using base_type::_strides;

  public:
    using base_type::Dimension;
    using base_type::StorageOrder;

    using value_type = typename base_type::value_type;
    using pointer = typename base_type::pointer;
    using vector_type = typename base_type::vector_type;
    using allocator_type = Allocator<value_type>;

  public: /* interface */
    //! @brief Default constructor that constructs an empty ND-array.
    inline MultiArrayBase() = default;

    //! @brief Constructor that takes **ownership** of the data.
    //! The data will be cleared upon destruction of the MultiArray object.
    //! Thus ensure sure that is **really** what you want. Otherwise construct a
    //! MultiArrayView object instead.
    inline explicit MultiArrayBase(value_type *data, const vector_type& sizes)
    {
      this->base_type::operator=(base_type{ data, sizes });
    }

    //! @{
    //! @brief Constructor with specified sizes.
    inline explicit MultiArrayBase(const vector_type& sizes)
    {
      initialize(sizes);
    }

    inline explicit MultiArrayBase(int rows, int cols)
      : self_type{ vector_type{ rows, cols } }
    {
    }

    inline explicit MultiArrayBase(int rows, int cols, int depth)
      : self_type{ vector_type{ rows, cols, depth } }
    {
    }
    //! @}

    //! @brief Copy constructor.
    //! Clone the other MultiArrayView instance.
    inline MultiArrayBase(const base_type& other)
    {
      initialize(other.sizes());
      base_type::copy(other);
    }

    inline MultiArrayBase(const self_type& other)
      : self_type{ base_type(other) }
    {
    }

    //! @brief Move constructor.
    inline MultiArrayBase(self_type&& other)
    {
      base_type::swap(other);
    }

    //! @brief Destructor.
    inline ~MultiArrayBase()
    {
      deallocate();
    }

    //! @brief Assignment operator uses the copy-swap idiom.
    self_type& operator=(self_type other)
    {
      base_type::swap(other);
      return *this;
    }

    //! @{
    //! @brief Resize the MultiArray object with the specified sizes.
    inline void resize(const vector_type& sizes)
    {
      if (_sizes != sizes)
      {
        deallocate();
        initialize(sizes);
      }
    }

    inline void resize(int rows, int cols)
    {
      static_assert(Dimension == 2, "MultiArray must be 2D");
      resize(vector_type{ rows, cols });
    }

    inline void resize(int rows, int cols, int depth)
    {
      static_assert(Dimension == 3, "MultiArray must be 3D");
      resize(vector_type(rows, cols, depth));
    }
    //! @}

    //! @brief Destroy the content of the MultiArray object.
    inline void clear()
    {
      deallocate();
    }

  private: /* helper functions for offset computation. */
    //! @{
    //! @brief Allocate the internal array of the MultiArray object.
    inline void initialize(const vector_type& sizes)
    {
      _sizes = sizes;
      auto empty = (sizes == vector_type::Zero());
      _strides = empty ? sizes : base_type::compute_strides(sizes);

      auto num_elements = base_type::compute_size(sizes);
      _begin = empty ? 0 : allocate(num_elements);
      _end = empty ? 0 : _begin + num_elements;
    }

    inline pointer allocate(std::size_t count)
    {
      return allocator_type{}.allocate(count);
    }
    //! @}

    //! @brief Deallocate the MultiArray object.
    inline void deallocate()
    {
      allocator_type{}.deallocate(_begin, _end - _begin);
      _begin = nullptr;
      _end = nullptr;
      _sizes = vector_type::Zero();
      _strides = vector_type::Zero();
    }

  };

  //! @}

} /* namespace Sara */
} /* namespace DO */
<commit_msg>ENH: optimize memory allocation.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013-2016 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @file
//! @brief This contains the implementation of the N-dimensional array class.

#pragma once

#include <iostream>
#include <memory>
#include <numeric>
#include <stdexcept>

#include <DO/Sara/Core/MultiArray/MultiArrayView.hpp>

namespace DO { namespace Sara {

  //! @brief The multidimensional array class.
  template <typename MultiArrayView, template <typename> class Allocator>
  class MultiArrayBase : public MultiArrayView
  {
    //! @{
    //! Convenience typedefs.
    using self_type =  MultiArrayBase;
    using base_type = MultiArrayView;
    //! @}

    using base_type::_begin;
    using base_type::_end;
    using base_type::_sizes;
    using base_type::_strides;

  public:
    using base_type::Dimension;
    using base_type::StorageOrder;

    using value_type = typename base_type::value_type;
    using pointer = typename base_type::pointer;
    using vector_type = typename base_type::vector_type;
    using allocator_type = Allocator<value_type>;

  public: /* interface */
    //! @brief Default constructor that constructs an empty ND-array.
    inline MultiArrayBase() = default;

    //! @brief Constructor that takes **ownership** of the data.
    //! The data will be cleared upon destruction of the MultiArray object.
    //! Thus ensure sure that is **really** what you want. Otherwise construct a
    //! MultiArrayView object instead.
    inline explicit MultiArrayBase(value_type *data, const vector_type& sizes)
    {
      this->base_type::operator=(base_type{ data, sizes });
    }

    //! @{
    //! @brief Constructor with specified sizes.
    inline explicit MultiArrayBase(const vector_type& sizes)
    {
      initialize(sizes);
    }

    inline explicit MultiArrayBase(int rows, int cols)
      : self_type{ vector_type{ rows, cols } }
    {
    }

    inline explicit MultiArrayBase(int rows, int cols, int depth)
      : self_type{ vector_type{ rows, cols, depth } }
    {
    }
    //! @}

    //! @brief Copy constructor.
    //! Clone the other MultiArrayView instance.
    inline MultiArrayBase(const base_type& other)
    {
      initialize(other.sizes());
      base_type::copy(other);
    }

    inline MultiArrayBase(const self_type& other)
      : self_type{ base_type(other) }
    {
    }

    //! @brief Move constructor.
    inline MultiArrayBase(self_type&& other)
    {
      base_type::swap(other);
    }

    //! @brief Destructor.
    inline ~MultiArrayBase()
    {
      deallocate();
    }

    //! @brief Assignment operator uses the copy-swap idiom.
    self_type& operator=(self_type other)
    {
      base_type::swap(other);
      return *this;
    }

    //! @{
    //! @brief Resize the MultiArray object with the specified sizes.
    inline void resize(const vector_type& sizes)
    {
      // Boundary case: the size of the allocated memory has not changed.
      // Optimize by:
      // - not deallocating memory.
      // - only changing the sizes and recompute the strides.
      if (_end - _begin == base_type::compute_size(sizes))
      {
        _sizes = sizes;
        _strides = base_type::compute_strides(sizes());
        return;
      }

      // General case.
      if (_sizes != sizes)
      {
        deallocate();
        initialize(sizes);
      }
    }

    inline void resize(int rows, int cols)
    {
      static_assert(Dimension == 2, "MultiArray must be 2D");
      resize(vector_type{ rows, cols });
    }

    inline void resize(int rows, int cols, int depth)
    {
      static_assert(Dimension == 3, "MultiArray must be 3D");
      resize(vector_type(rows, cols, depth));
    }
    //! @}

    //! @brief Destroy the content of the MultiArray object.
    inline void clear()
    {
      deallocate();
    }

  private: /* helper functions for offset computation. */
    //! @{
    //! @brief Allocate the internal array of the MultiArray object.
    inline void initialize(const vector_type& sizes)
    {
      const auto empty = (sizes == vector_type::Zero());
      const auto num_elements = empty ? 0 : base_type::compute_size(sizes);

      _sizes = sizes;
      _strides = empty ? sizes : base_type::compute_strides(sizes);
      _begin = empty ? 0 : allocate(num_elements);
      _end = empty ? 0 : _begin + num_elements;
    }

    inline pointer allocate(std::size_t count)
    {
      return allocator_type{}.allocate(count);
    }
    //! @}

    //! @brief Deallocate the MultiArray object.
    inline void deallocate()
    {
      allocator_type{}.deallocate(_begin, _end - _begin);
      _begin = nullptr;
      _end = nullptr;
      _sizes = vector_type::Zero();
      _strides = vector_type::Zero();
    }

  };

  //! @}

} /* namespace Sara */
} /* namespace DO */
<|endoftext|>


<commit_before>/// @file
/// @author  Boris Mikic
/// @version 3.0
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php

#include <hltypes/harray.h>
#include <hltypes/hresource.h>
#include <hltypes/hstring.h>

#include "AudioManager.h"
#include "Buffer.h"
#include "Category.h"
#include "Sound.h"
#include "Source.h"
#include "xal.h"

namespace xal
{
	Sound::Sound(chstr filename, Category* category, chstr prefix)
	{
		this->filename = filename;
		this->realFilename = this->_findLinkedFile();
		this->category = category;
		this->buffer = xal::mgr->_createBuffer(this);;
		// extracting filename without extension and prepending the prefix
		this->name = prefix + filename.replace("\\", "/").rsplit("/", -1, false).remove_last().rsplit(".", 1, false).remove_first();
	}

	Sound::~Sound()
	{
		xal::mgr->_destroyBuffer(this->buffer);
	}

	hstr Sound::_findLinkedFile()
	{
		if (!this->filename.ends_with(".xln"))
		{
			return this->filename;
		}
		if (!hresource::exists(this->filename))
		{
			return this->filename;
		}
		// It's dangerous to go alone! Take this.
		return xal::mgr->findAudioFile(normalize_path(get_basedir(this->filename) + "/" + hresource::hread(this->filename)));
	}

	int Sound::getSize()
	{
		return this->buffer->getSize();
	}

	int Sound::getChannels()
	{
		return this->buffer->getChannels();
	}

	int Sound::getSamplingRate()
	{
		return this->buffer->getSamplingRate();
	}

	int Sound::getBitsPerSample()
	{
		return this->buffer->getBitsPerSample();
	}

	float Sound::getDuration()
	{
		return this->buffer->getDuration();
	}

	Format Sound::getFormat()
	{
		return this->buffer->getFormat();
	}

	bool Sound::isStreamed()
	{
		return this->buffer->isStreamed();
	}

	int Sound::readPcmData(unsigned char** output)
	{
		return Buffer(this).readPcmData(output);
	}

}
<commit_msg>- thanks, OCD<commit_after>/// @file
/// @author  Boris Mikic
/// @version 3.0
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php

#include <hltypes/harray.h>
#include <hltypes/hresource.h>
#include <hltypes/hstring.h>

#include "AudioManager.h"
#include "Buffer.h"
#include "Category.h"
#include "Sound.h"
#include "Source.h"
#include "xal.h"

namespace xal
{
	Sound::Sound(chstr filename, Category* category, chstr prefix)
	{
		this->filename = filename;
		this->realFilename = this->_findLinkedFile();
		this->category = category;
		this->buffer = xal::mgr->_createBuffer(this);
		// extracting filename without extension and prepending the prefix
		this->name = prefix + filename.replace("\\", "/").rsplit("/", -1, false).remove_last().rsplit(".", 1, false).remove_first();
	}

	Sound::~Sound()
	{
		xal::mgr->_destroyBuffer(this->buffer);
	}

	hstr Sound::_findLinkedFile()
	{
		if (!this->filename.ends_with(".xln"))
		{
			return this->filename;
		}
		if (!hresource::exists(this->filename))
		{
			return this->filename;
		}
		// It's dangerous to go alone! Take this.
		return xal::mgr->findAudioFile(normalize_path(get_basedir(this->filename) + "/" + hresource::hread(this->filename)));
	}

	int Sound::getSize()
	{
		return this->buffer->getSize();
	}

	int Sound::getChannels()
	{
		return this->buffer->getChannels();
	}

	int Sound::getSamplingRate()
	{
		return this->buffer->getSamplingRate();
	}

	int Sound::getBitsPerSample()
	{
		return this->buffer->getBitsPerSample();
	}

	float Sound::getDuration()
	{
		return this->buffer->getDuration();
	}

	Format Sound::getFormat()
	{
		return this->buffer->getFormat();
	}

	bool Sound::isStreamed()
	{
		return this->buffer->isStreamed();
	}

	int Sound::readPcmData(unsigned char** output)
	{
		return Buffer(this).readPcmData(output);
	}

}
<|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include <pdal/Stage.hpp>

#include <boost/concept_check.hpp> // ignore_unused_variable_warning

#include <iostream>

#include <pdal/exceptions.hpp>

namespace pdal
{

Stage::Stage(const Options& options)
    : StageBase(options)
    , m_numPoints(0)
    , m_pointCountType(PointCount_Fixed)
{
    return;
}

Stage::~Stage()
{
    return;
}

void Stage::initialize()
{
    StageBase::initialize();

    return;
}

const Bounds<double>& Stage::getBounds() const
{
    return m_bounds;
}

void Stage::setBounds(const Bounds<double>& bounds)
{
    m_bounds = bounds;
}

const Schema& Stage::getSchema() const
{
    return m_schema;
}

Schema& Stage::getSchemaRef()
{
    return m_schema;
}

void Stage::setSchema(const Schema& schema)
{
    m_schema = schema;
}

boost::uint64_t Stage::getNumPoints() const
{
    return m_numPoints;
}

void Stage::setNumPoints(boost::uint64_t numPoints)
{
    m_numPoints = numPoints;
}

PointCountType Stage::getPointCountType() const
{
    return m_pointCountType;
}

void Stage::setPointCountType(PointCountType pointCountType)
{
    m_pointCountType = pointCountType;
}

const SpatialReference& Stage::getSpatialReference() const
{
    return m_spatialReference;
}

void Stage::setSpatialReference(const SpatialReference& spatialReference)
{
    m_spatialReference = spatialReference;
}

int Stage::getMetadataRecordCount() const
{
    return 0;
}

const MetadataRecord& Stage::getMetadataRecord(int index) const
{
    // the default behaviour is to have no records at all...
    boost::ignore_unused_variable_warning(index);
    throw pdal_error("no such metadata record");
}

MetadataRecord& Stage::getMetadataRecordRef(int index)
{
    // the default behaviour is to have no records at all...
    boost::ignore_unused_variable_warning(index);
    throw pdal_error("no such metadata record");
}

void Stage::setCoreProperties(const Stage& stage)
{
    this->setSchema(stage.getSchema());
    this->setNumPoints(stage.getNumPoints());
    this->setPointCountType(stage.getPointCountType());
    this->setBounds(stage.getBounds());
    this->setSpatialReference(stage.getSpatialReference());

    return;
}

void Stage::dump() const
{
    std::cout << *this;
}

std::ostream& operator<<(std::ostream& ostr, const Stage& stage)
{
    ostr << "  Name: " << stage.getName() << std::endl;
    ostr << "  Num points: " << stage.getNumPoints() << std::endl;

    ostr << "  Bounds:" << std::endl;
    ostr << "    " << stage.getBounds() << std::endl;

    ostr << "  Schema: " << std::endl;
    ostr << "    Num dims: " << stage.getSchema().getDimensions().size() << std::endl;
//    ostr << "    Size in bytes: " << header.getSchema().getByteSize() << std::endl;

    ostr << "  Spatial Reference:" << std::endl;
    ostr << "    WKT: " << stage.getSpatialReference().getWKT() << std::endl;

    return ostr;
}

} // namespace pdal
<commit_msg>fetch the SpatialReference from options for the stage if it was set<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include <pdal/Stage.hpp>

#include <boost/concept_check.hpp> // ignore_unused_variable_warning

#include <iostream>

#include <pdal/exceptions.hpp>

namespace pdal
{

Stage::Stage(const Options& options)
    : StageBase(options)
    , m_numPoints(0)
    , m_pointCountType(PointCount_Fixed)
{
    return;
}

Stage::~Stage()
{
    return;
}

void Stage::initialize()
{
    StageBase::initialize();

    // Try to fetch overridden options here

    // If the user gave us an SRS via options, take that.
    try
    {
        m_spatialReference = getOptions().getValueOrThrow<pdal::SpatialReference>("spatialreference");

    } catch (pdal_error const&)
    {
        // If one wasn't set on the options, we'll ignore at this
        // point.  Maybe another stage might forward/set it later.
    }
    return;
}

const Bounds<double>& Stage::getBounds() const
{
    return m_bounds;
}

void Stage::setBounds(const Bounds<double>& bounds)
{
    m_bounds = bounds;
}

const Schema& Stage::getSchema() const
{
    return m_schema;
}

Schema& Stage::getSchemaRef()
{
    return m_schema;
}

void Stage::setSchema(const Schema& schema)
{
    m_schema = schema;
}

boost::uint64_t Stage::getNumPoints() const
{
    return m_numPoints;
}

void Stage::setNumPoints(boost::uint64_t numPoints)
{
    m_numPoints = numPoints;
}

PointCountType Stage::getPointCountType() const
{
    return m_pointCountType;
}

void Stage::setPointCountType(PointCountType pointCountType)
{
    m_pointCountType = pointCountType;
}

const SpatialReference& Stage::getSpatialReference() const
{
    return m_spatialReference;
}

void Stage::setSpatialReference(const SpatialReference& spatialReference)
{
    m_spatialReference = spatialReference;
}

int Stage::getMetadataRecordCount() const
{
    return 0;
}

const MetadataRecord& Stage::getMetadataRecord(int index) const
{
    // the default behaviour is to have no records at all...
    boost::ignore_unused_variable_warning(index);
    throw pdal_error("no such metadata record");
}

MetadataRecord& Stage::getMetadataRecordRef(int index)
{
    // the default behaviour is to have no records at all...
    boost::ignore_unused_variable_warning(index);
    throw pdal_error("no such metadata record");
}

void Stage::setCoreProperties(const Stage& stage)
{
    this->setSchema(stage.getSchema());
    this->setNumPoints(stage.getNumPoints());
    this->setPointCountType(stage.getPointCountType());
    this->setBounds(stage.getBounds());
    this->setSpatialReference(stage.getSpatialReference());

    return;
}

void Stage::dump() const
{
    std::cout << *this;
}

std::ostream& operator<<(std::ostream& ostr, const Stage& stage)
{
    ostr << "  Name: " << stage.getName() << std::endl;
    ostr << "  Num points: " << stage.getNumPoints() << std::endl;

    ostr << "  Bounds:" << std::endl;
    ostr << "    " << stage.getBounds() << std::endl;

    ostr << "  Schema: " << std::endl;
    ostr << "    Num dims: " << stage.getSchema().getDimensions().size() << std::endl;
//    ostr << "    Size in bytes: " << header.getSchema().getByteSize() << std::endl;

    ostr << "  Spatial Reference:" << std::endl;
    ostr << "    WKT: " << stage.getSpatialReference().getWKT() << std::endl;

    return ostr;
}

} // namespace pdal
<|endoftext|>


<commit_before>/*
	This file is part of the MinSG library extension ThesisPeter.
	Copyright (C) 2014 Peter Stilow

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_THESISPETER

#include "E_LightNodeManager.h"
#include <MinSG/Ext/ThesisPeter/LightNodeManager.h>

#include "../../ELibMinSG.h"

#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <E_Rendering/E_RenderingContext.h>
#include <E_MinSG/Core/E_FrameContext.h>

using namespace MinSG::ThesisPeter;

namespace E_MinSG {
namespace ThesisPeter {

//! (static)
EScript::Type * E_LightNodeManager::getTypeObject() {
	// E_LightNodeManager ---|> [Object]
//	static EScript::Type* typeObject = new EScript::Type(Object::getTypeObject());
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(Object::getTypeObject());
	return typeObject.get();
}

//! initMembers
void E_LightNodeManager::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = getTypeObject();
	initPrintableName(typeObject, getClassName());
	declareConstant(&lib, getClassName(), typeObject);
//	addFactory<MinSG::ThesisPeter::LightNodeManager, E_LightNodeManager>();

	//! [ESMF] new MinSG.ThesisPeter.LightNodeManager()
	ES_CTOR(typeObject, 0, 0, new E_LightNodeManager)

	//! [ESMF] self LightNodeManager.setSceneRootNode(Node);
	ES_MFUN(typeObject, LightNodeManager, "setSceneRootNode", 1, 1,
				 (thisObj->setSceneRootNode(parameter[0].to<MinSG::Node*>(rt)), thisEObj))

	//! [ESMF] self LightNodeManager.setRenderingContext(RenderingContext);
	ES_MFUN(typeObject, LightNodeManager, "setRenderingContext", 1, 1,
				 (thisObj->setRenderingContext(parameter[0].to<Rendering::RenderingContext&>(rt)), thisEObj))

    //! [ESMF] self LightNodeManager.setFrameContext(FrameContext);
    ES_MFUN(typeObject, LightNodeManager, "setFrameContext", 1,1,
				 (thisObj->setFrameContext(parameter[0].to<MinSG::FrameContext&>(rt)), thisEObj))

	//! [ESMF] self LightNodeManager.createLightNodes();
	ES_MFUN(typeObject, LightNodeManager, "createLightNodes", 0, 0,
				 (thisObj->createLightNodes(), thisEObj))

	//! [ESMF] self LightNodeManager.cleanUp();
	ES_MFUN(typeObject, LightNodeManager, "cleanUp", 0, 0,
				 (thisObj->cleanUp(), thisEObj))

	//! [ESMF] self LightNodeManager.activateLighting(SceneRootNode, LightRootNode, RenderingContext, FrameContext);
	ES_MFUN(typeObject, LightNodeManager, "activateLighting", 4, 4,
				 (thisObj->activateLighting(parameter[0].to<MinSG::Node*>(rt), parameter[1].to<MinSG::Node*>(rt),
												parameter[2].to<Rendering::RenderingContext&>(rt), parameter[3].to<MinSG::FrameContext&>(rt)), thisEObj))

}

//E_LightNodeManager::E_LightNodeManager(MinSG::ThesisPeter::LightNodeManager* renderer){
//
//}

E_LightNodeManager::~E_LightNodeManager() {

}

}
}

#endif /* MINSG_EXT_THESISPETER */
<commit_msg>added new function calls for the lightNodeManager<commit_after>/*
	This file is part of the MinSG library extension ThesisPeter.
	Copyright (C) 2014 Peter Stilow

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_THESISPETER

#include "E_LightNodeManager.h"
#include <MinSG/Ext/ThesisPeter/LightNodeManager.h>

#include "../../ELibMinSG.h"

#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <E_Rendering/E_RenderingContext.h>
#include <E_MinSG/Core/E_FrameContext.h>

using namespace MinSG::ThesisPeter;

namespace E_MinSG {
namespace ThesisPeter {

//! (static)
EScript::Type * E_LightNodeManager::getTypeObject() {
	// E_LightNodeManager ---|> [Object]
//	static EScript::Type* typeObject = new EScript::Type(Object::getTypeObject());
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(Object::getTypeObject());
	return typeObject.get();
}

//! initMembers
void E_LightNodeManager::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = getTypeObject();
	initPrintableName(typeObject, getClassName());
	declareConstant(&lib, getClassName(), typeObject);
//	addFactory<MinSG::ThesisPeter::LightNodeManager, E_LightNodeManager>();

	//! [ESMF] new MinSG.ThesisPeter.LightNodeManager()
	ES_CTOR(typeObject, 0, 0, new E_LightNodeManager)

	//! [ESMF] self LightNodeManager.test(Node);
	ES_MFUN(typeObject, LightNodeManager, "test", 2, 2,
				 (thisObj->test(parameter[0].to<MinSG::FrameContext&>(rt), parameter[1].to<MinSG::Node*>(rt)), thisEObj))

	//! [ESMF] self LightNodeManager.setSceneRootNode(Node);
	ES_MFUN(typeObject, LightNodeManager, "setSceneRootNode", 1, 1,
				 (thisObj->setSceneRootNode(parameter[0].to<MinSG::Node*>(rt)), thisEObj))

	//! [ESMF] self LightNodeManager.setRenderingContext(RenderingContext);
	ES_MFUN(typeObject, LightNodeManager, "setRenderingContext", 1, 1,
				 (thisObj->setRenderingContext(parameter[0].to<Rendering::RenderingContext&>(rt)), thisEObj))

    //! [ESMF] self LightNodeManager.setFrameContext(FrameContext);
    ES_MFUN(typeObject, LightNodeManager, "setFrameContext", 1,1,
				 (thisObj->setFrameContext(parameter[0].to<MinSG::FrameContext&>(rt)), thisEObj))

	//! [ESMF] self LightNodeManager.createLightNodes();
	ES_MFUN(typeObject, LightNodeManager, "createLightNodes", 0, 0,
				 (thisObj->createLightNodes(), thisEObj))

	//! [ESMF] self LightNodeManager.cleanUpDebug();
	ES_MFUN(typeObject, LightNodeManager, "cleanUpDebug", 0, 0,
				 (thisObj->cleanUpDebug(), thisEObj))

	//! [ESMF] self LightNodeManager.cleanUp();
	ES_MFUN(typeObject, LightNodeManager, "cleanUp", 0, 0,
				 (thisObj->cleanUp(), thisEObj))

	//! [ESMF] self LightNodeManager.activateLighting(SceneRootNode, LightRootNode, RenderingContext, FrameContext);
	ES_MFUN(typeObject, LightNodeManager, "activateLighting", 4, 4,
				 (thisObj->activateLighting(parameter[0].to<MinSG::Node*>(rt), parameter[1].to<MinSG::Node*>(rt),
												parameter[2].to<Rendering::RenderingContext&>(rt), parameter[3].to<MinSG::FrameContext&>(rt)), thisEObj))

}

//E_LightNodeManager::E_LightNodeManager(MinSG::ThesisPeter::LightNodeManager* renderer){
//
//}

E_LightNodeManager::~E_LightNodeManager() {

}

}
}

#endif /* MINSG_EXT_THESISPETER */
<|endoftext|>


<commit_before>#include "Utils.hpp"

#include <Log.hpp>
#include <Mesh.hpp>
#include <Model.hpp>

#include <sstream>

namespace Utils
{
	std::string _mAssetPath;

	std::vector<std::string> _mAssetPaths;

	void SetAssetPath(const std::string& path)
	{
		//LogInfo("Setting Asset Path: %s\n", path.c_str());
		_mAssetPath = path;
		_mAssetPaths.clear();
	}

	std::string GetAssetPath()
	{
		return _mAssetPath;
	}

	std::vector<std::string> GetResourcePaths()
	{
		if (_mAssetPaths.empty()) {
			std::stringstream ss(GetAssetPath());
			std::string path;
			while (std::getline(ss, path, ':')) {
				if (path.empty()) continue;
				if (path.back() != '/') path.push_back('/');

				_mAssetPaths.push_back(path);
			}
			_mAssetPaths.push_back("");
			std::reverse(_mAssetPaths.begin(), _mAssetPaths.end());
		}
		return _mAssetPaths;
	}

	void CleanSlashes(std::string& path)
	{
		for (unsigned int i = 0; i < path.size(); ++i)
		{
			if (path[i] == '\\')
			{
				path[i] = '/';
			}
		}
	}

	std::string GetBasename(std::string path)
	{
		CleanSlashes(path);
		size_t pivot = path.find_last_of('/');
		return (pivot == std::string::npos
			? std::string()
			: path.substr(pivot + 1));
	}

	std::string GetDirname(std::string path)
	{
		CleanSlashes(path);
		size_t pivot = path.find_last_of('/');
		return (pivot == std::string::npos
			? "./"
			: path.substr(0, pivot));
	}

	std::string GetExtension(std::string path)
	{
		size_t pivot = path.find_last_of('.');
		return (pivot == std::string::npos
			? std::string()
			: path.substr(pivot + 1));
	}

	Mesh* Get2DMesh(glm::vec4 screenCords, glm::vec4 textureCords)
	{
		GLuint vbos[2];
		GLuint vao;
		std::vector<glm::vec3> vertices = {
			{ screenCords[2], screenCords[1], 0 },
		{ screenCords[2], screenCords[3], 0 },
		{ screenCords[0], screenCords[3], 0 },
		{ screenCords[2], screenCords[1], 0 },
		{ screenCords[0], screenCords[3], 0 },
		{ screenCords[0], screenCords[1], 0 } };

		std::vector<glm::vec2> texCoords = {
			{ textureCords[2], textureCords[3] },
		{ textureCords[2], textureCords[1] },
		{ textureCords[0], textureCords[1] },
		{ textureCords[2], textureCords[3] },
		{ textureCords[0], textureCords[1] },
		{ textureCords[0], textureCords[3] } };

		glGenVertexArrays(1, &vao);
		glBindVertexArray(vao);

		glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
		glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size() * 3, vertices.data(), GL_STATIC_DRAW);
		glVertexAttribPointer(AttributeID::POSITION, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray(AttributeID::POSITION);

		glBindBuffer(GL_ARRAY_BUFFER, vbos[1]);
		glBufferData(GL_ARRAY_BUFFER, sizeof(float) * texCoords.size() * 2, texCoords.data(), GL_STATIC_DRAW);
		glVertexAttribPointer(AttributeID::TEXCOORD, 2, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray(AttributeID::TEXCOORD);

		glBindVertexArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		Mesh* m = new Mesh(vao, 0, 0, 0, 0, {});

		return m;
		// std::vector<glm::vec3> Vertices, {}, std::vector<glm::vec2> texCoords, {}, {}
		/*
		return new Mesh(
		{
		{screenCords[2], screenCords[1], 0},
		{screenCords[2], screenCords[3], 0},
		{screenCords[0], screenCords[3], 0},
		{screenCords[2], screenCords[1], 0},
		{screenCords[0], screenCords[3], 0},
		{screenCords[0], screenCords[1], 0} },
		{},
		{
		{textureCords[2], textureCords[3]},
		{textureCords[2], textureCords[1]},
		{textureCords[0], textureCords[1]},
		{textureCords[2], textureCords[3]},
		{textureCords[0], textureCords[1]},
		{textureCords[0], textureCords[3]} },
		{}, {});
		*/
	}
}
<commit_msg>forgot <Algorithm>.<commit_after>#include "Utils.hpp"

#include <Log.hpp>
#include <Mesh.hpp>
#include <Model.hpp>

#include <algorithm>
#include <sstream>

namespace Utils
{
	std::string _mAssetPath;

	std::vector<std::string> _mAssetPaths;

	void SetAssetPath(const std::string& path)
	{
		//LogInfo("Setting Asset Path: %s\n", path.c_str());
		_mAssetPath = path;
		_mAssetPaths.clear();
	}

	std::string GetAssetPath()
	{
		return _mAssetPath;
	}

	std::vector<std::string> GetResourcePaths()
	{
		if (_mAssetPaths.empty()) {
			std::stringstream ss(GetAssetPath());
			std::string path;
			while (std::getline(ss, path, ':')) {
				if (path.empty()) continue;
				if (path.back() != '/') path.push_back('/');

				_mAssetPaths.push_back(path);
			}
			_mAssetPaths.push_back("");
			std::reverse(_mAssetPaths.begin(), _mAssetPaths.end());
		}
		return _mAssetPaths;
	}

	void CleanSlashes(std::string& path)
	{
		for (unsigned int i = 0; i < path.size(); ++i)
		{
			if (path[i] == '\\')
			{
				path[i] = '/';
			}
		}
	}

	std::string GetBasename(std::string path)
	{
		CleanSlashes(path);
		size_t pivot = path.find_last_of('/');
		return (pivot == std::string::npos
			? std::string()
			: path.substr(pivot + 1));
	}

	std::string GetDirname(std::string path)
	{
		CleanSlashes(path);
		size_t pivot = path.find_last_of('/');
		return (pivot == std::string::npos
			? "./"
			: path.substr(0, pivot));
	}

	std::string GetExtension(std::string path)
	{
		size_t pivot = path.find_last_of('.');
		return (pivot == std::string::npos
			? std::string()
			: path.substr(pivot + 1));
	}

	Mesh* Get2DMesh(glm::vec4 screenCords, glm::vec4 textureCords)
	{
		GLuint vbos[2];
		GLuint vao;
		std::vector<glm::vec3> vertices = {
			{ screenCords[2], screenCords[1], 0 },
		{ screenCords[2], screenCords[3], 0 },
		{ screenCords[0], screenCords[3], 0 },
		{ screenCords[2], screenCords[1], 0 },
		{ screenCords[0], screenCords[3], 0 },
		{ screenCords[0], screenCords[1], 0 } };

		std::vector<glm::vec2> texCoords = {
			{ textureCords[2], textureCords[3] },
		{ textureCords[2], textureCords[1] },
		{ textureCords[0], textureCords[1] },
		{ textureCords[2], textureCords[3] },
		{ textureCords[0], textureCords[1] },
		{ textureCords[0], textureCords[3] } };

		glGenVertexArrays(1, &vao);
		glBindVertexArray(vao);

		glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
		glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size() * 3, vertices.data(), GL_STATIC_DRAW);
		glVertexAttribPointer(AttributeID::POSITION, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray(AttributeID::POSITION);

		glBindBuffer(GL_ARRAY_BUFFER, vbos[1]);
		glBufferData(GL_ARRAY_BUFFER, sizeof(float) * texCoords.size() * 2, texCoords.data(), GL_STATIC_DRAW);
		glVertexAttribPointer(AttributeID::TEXCOORD, 2, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray(AttributeID::TEXCOORD);

		glBindVertexArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		Mesh* m = new Mesh(vao, 0, 0, 0, 0, {});

		return m;
		// std::vector<glm::vec3> Vertices, {}, std::vector<glm::vec2> texCoords, {}, {}
		/*
		return new Mesh(
		{
		{screenCords[2], screenCords[1], 0},
		{screenCords[2], screenCords[3], 0},
		{screenCords[0], screenCords[3], 0},
		{screenCords[2], screenCords[1], 0},
		{screenCords[0], screenCords[3], 0},
		{screenCords[0], screenCords[1], 0} },
		{},
		{
		{textureCords[2], textureCords[3]},
		{textureCords[2], textureCords[1]},
		{textureCords[0], textureCords[1]},
		{textureCords[2], textureCords[3]},
		{textureCords[0], textureCords[1]},
		{textureCords[0], textureCords[3]} },
		{}, {});
		*/
	}
}
<|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    VFFConverter.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    December 2008
*/

#include <fstream>
#include "VFFConverter.h"
#include <Controller/Controller.h>
#include <IO/KeyValueFileParser.h>

using namespace std;

VFFConverter::VFFConverter()
{
  m_vConverterDesc = "Visualization File Format";
  m_vSupportedExt.push_back("VFF");
}

bool VFFConverter::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 VFF dataset %s", strSourceFilename.c_str());

  // Check Magic value in VFF File first
  ifstream fileData(strSourceFilename.c_str());
  string strFirstLine;

  if (fileData.is_open())
  {
    getline (fileData,strFirstLine);
    if (strFirstLine.substr(0,4) != "ncaa") {
      WARNING("The file %s is not a VFF file (missing magic)", strSourceFilename.c_str());
      return false;
    }
  } else {
    WARNING("Could not open VFF file %s", strSourceFilename.c_str());
    return false;
  }
  fileData.close();

  // init data
  strIntermediateFile = strSourceFilename;
  bDeleteIntermediateFile = false;
  iComponentSize    = 8;
  iComponentCount   = 1;
  vVolumeSize       = UINT64VECTOR3(1,1,1);
  vVolumeAspect     = FLOATVECTOR3(1,1,1);
  bConvertEndianess = EndianConvert::IsLittleEndian();
  bSigned           = true;
  eType             = UVFTables::ES_UNDEFINED;
  bIsFloat          = false; /// \todo check if VFF can store float values

  // read data
  string strHeaderEnd;
  strHeaderEnd.push_back(12);  // header end char of vffs is ^L = 0C = 12

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

  if (!parser.FileReadable()) {
    WARNING("Could not open VFF file %s", strSourceFilename.c_str());
    return false;
  }

  KeyValPair* kvp = parser.GetData("TYPE");
  if (kvp == NULL) {
    T_ERROR("Could not find token \"type\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    if (kvp->strValueUpper != "RASTER;")  {
      T_ERROR("Only raster VFFs are supported at the moment");
      return false;
     }
  }

  int iDim;
  kvp = parser.GetData("RANK");
  if (kvp == NULL) {
    T_ERROR("Could not find token \"rank\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    iDim = kvp->iValue;
  }

  kvp = parser.GetData("BANDS");
  if (kvp == NULL) {
    T_ERROR("Could not find token \"bands\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    if (kvp->iValue != 1)  {
      T_ERROR("Only scalar VFFs are supported at the moment");
      return false;
     }
  }

  kvp = parser.GetData("FORMAT");
  if (kvp == NULL) {
    T_ERROR("Could not find token \"format\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    if (kvp->strValueUpper != "SLICE;")  {
      T_ERROR("Only VFFs with slice layout are supported at the moment");
      return false;
     }
  }

  kvp = parser.GetData("BITS");
  if (kvp == NULL) {
    T_ERROR("Could not find token \"bands\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    iComponentSize = kvp->iValue;
  }

  kvp = parser.GetData("SIZE");
  if (kvp == NULL) {
    T_ERROR("Could not find token \"size\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    vVolumeSize[0] = kvp->viValue[0];
    vVolumeSize[1] = kvp->viValue[1];
    vVolumeSize[2] = 1;
    if (iDim == 3) vVolumeSize[2] = kvp->viValue[2];
    MESSAGE("%llu x %llu x %llu volume.", vVolumeSize[0], vVolumeSize[1],
            vVolumeSize[2]);
  }

  kvp = parser.GetData("SPACING");
  if (kvp == NULL) {
    T_ERROR("Could not find token \"size\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    vVolumeAspect[0] = kvp->vfValue[0];
    vVolumeAspect[1] = kvp->vfValue[1];
    if (iDim == 3) vVolumeAspect[2] = kvp->vfValue[2];
  }

  kvp = parser.GetData("TITLE");
  if (kvp == NULL) {
    strTitle = "VFF data";
  } else {
    strTitle = kvp->strValue;
  }

  iHeaderSkip = parser.GetStopPos();

  return true;
}

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

  // create header textfile from metadata
  ofstream fAsciiTarget(strTargetFilename.c_str());
  if (!fAsciiTarget.is_open()) {
    T_ERROR("Unable to open target file %s.", strTargetFilename.c_str());
    return false;
  }

  if (bFloatingPoint) {
    T_ERROR("Floating point formats are not avaliable for vff files.");
    return false;
  }

  fAsciiTarget << "ncaa" << endl;
  fAsciiTarget << "type=raster;" << endl;
  fAsciiTarget << "rank=3;" << endl;
  fAsciiTarget << "bands=" << iComponentCount << ";"<< endl;
  fAsciiTarget << "format=slice;" << endl;
  fAsciiTarget << "bits=" << iComponentSize << ";" << endl;
  fAsciiTarget << "size=" << vVolumeSize.x << " " << vVolumeSize.y << " "<< vVolumeSize.z << ";" << endl;
  fAsciiTarget << "spacing=" << vVolumeAspect.x << " " << vVolumeAspect.y << " "<< vVolumeAspect.z << ";" << endl;

  // add the ^L header delimiter
  string strHeaderEnd;
  strHeaderEnd.push_back(12);  // header end char of vffs is ^L = 0C = 12
  fAsciiTarget << strHeaderEnd << endl;
  fAsciiTarget.close();

  // append RAW data using the parent's call
  bool bRAWSuccess = AppendRAW(strRawFilename, iHeaderSkip, strTargetFilename, iComponentSize, !EndianConvert::IsBigEndian(), !bSigned, bQuantizeTo8Bit);

  if (bRAWSuccess) {
    return true;
  } else {
    T_ERROR("Error appaneding raw data to header file %s.", strTargetFilename.c_str());
    remove(strTargetFilename.c_str());
    return false;
  }
}
<commit_msg>treat empty tags (tags that only contain a ";") equal to missing tags<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    VFFConverter.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    December 2008
*/

#include <fstream>
#include "VFFConverter.h"
#include <Controller/Controller.h>
#include <IO/KeyValueFileParser.h>

using namespace std;

VFFConverter::VFFConverter()
{
  m_vConverterDesc = "Visualization File Format";
  m_vSupportedExt.push_back("VFF");
}

bool VFFConverter::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 VFF dataset %s", strSourceFilename.c_str());

  // Check Magic value in VFF File first
  ifstream fileData(strSourceFilename.c_str());
  string strFirstLine;

  if (fileData.is_open())
  {
    getline (fileData,strFirstLine);
    if (strFirstLine.substr(0,4) != "ncaa") {
      WARNING("The file %s is not a VFF file (missing magic)", strSourceFilename.c_str());
      return false;
    }
  } else {
    WARNING("Could not open VFF file %s", strSourceFilename.c_str());
    return false;
  }
  fileData.close();

  // init data
  strIntermediateFile = strSourceFilename;
  bDeleteIntermediateFile = false;
  iComponentSize    = 8;
  iComponentCount   = 1;
  vVolumeSize       = UINT64VECTOR3(1,1,1);
  vVolumeAspect     = FLOATVECTOR3(1,1,1);
  bConvertEndianess = EndianConvert::IsLittleEndian();
  bSigned           = true;
  eType             = UVFTables::ES_UNDEFINED;
  bIsFloat          = false; /// \todo check if VFF can store float values

  // read data
  string strHeaderEnd;
  strHeaderEnd.push_back(12);  // header end char of vffs is ^L = 0C = 12

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

  if (!parser.FileReadable()) {
    WARNING("Could not open VFF file %s", strSourceFilename.c_str());
    return false;
  }

  KeyValPair* kvp = parser.GetData("TYPE");
  if (kvp == NULL || kvp->strValue == ";") {
    T_ERROR("Could not find valid token \"type\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    if (kvp->strValueUpper != "RASTER;")  {
      T_ERROR("Only raster VFFs are supported at the moment");
      return false;
     }
  }

  int iDim;
  kvp = parser.GetData("RANK");
  if (kvp == NULL || kvp->strValue == ";") {
    T_ERROR("Could not find valid token \"rank\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    iDim = kvp->iValue;
  }

  kvp = parser.GetData("BANDS");
  if (kvp == NULL || kvp->strValue == ";") {
    T_ERROR("Could not find valid token \"bands\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    if (kvp->iValue != 1)  {
      T_ERROR("Only scalar VFFs are supported at the moment");
      return false;
     }
  }

  kvp = parser.GetData("FORMAT");
  if (kvp == NULL || kvp->strValue == ";") {
    T_ERROR("Could not find valid token \"format\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    if (kvp->strValueUpper != "SLICE;")  {
      T_ERROR("Only VFFs with slice layout are supported at the moment");
      return false;
     }
  }

  kvp = parser.GetData("BITS");
  if (kvp == NULL || kvp->strValue == ";") {
    T_ERROR("Could not find valid token \"bands\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    iComponentSize = kvp->iValue;
  }

  kvp = parser.GetData("SIZE");
  if (kvp == NULL || kvp->strValue == ";") {
    T_ERROR("Could not find valid token \"size\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    vVolumeSize[0] = kvp->viValue[0];
    vVolumeSize[1] = kvp->viValue[1];
    vVolumeSize[2] = 1;
    if (iDim == 3) vVolumeSize[2] = kvp->viValue[2];
    MESSAGE("%llu x %llu x %llu volume.", vVolumeSize[0], vVolumeSize[1],
            vVolumeSize[2]);
  }

  kvp = parser.GetData("SPACING");
  if (kvp == NULL || kvp->strValue == ";") {
    T_ERROR("Could not find valid token \"size\" in file %s", strSourceFilename.c_str());
    return false;
  } else {
    vVolumeAspect[0] = kvp->vfValue[0];
    vVolumeAspect[1] = kvp->vfValue[1];
    if (iDim == 3) vVolumeAspect[2] = kvp->vfValue[2];
  }

  kvp = parser.GetData("TITLE");
  if (kvp == NULL || kvp->strValue == ";") {
    strTitle = "VFF data";
  } else {
    strTitle = kvp->strValue;
  }

  iHeaderSkip = parser.GetStopPos();

  return true;
}

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

  // create header textfile from metadata
  ofstream fAsciiTarget(strTargetFilename.c_str());
  if (!fAsciiTarget.is_open()) {
    T_ERROR("Unable to open target file %s.", strTargetFilename.c_str());
    return false;
  }

  if (bFloatingPoint) {
    T_ERROR("Floating point formats are not avaliable for vff files.");
    return false;
  }

  fAsciiTarget << "ncaa" << endl;
  fAsciiTarget << "type=raster;" << endl;
  fAsciiTarget << "rank=3;" << endl;
  fAsciiTarget << "bands=" << iComponentCount << ";"<< endl;
  fAsciiTarget << "format=slice;" << endl;
  fAsciiTarget << "bits=" << iComponentSize << ";" << endl;
  fAsciiTarget << "size=" << vVolumeSize.x << " " << vVolumeSize.y << " "<< vVolumeSize.z << ";" << endl;
  fAsciiTarget << "spacing=" << vVolumeAspect.x << " " << vVolumeAspect.y << " "<< vVolumeAspect.z << ";" << endl;

  // add the ^L header delimiter
  string strHeaderEnd;
  strHeaderEnd.push_back(12);  // header end char of vffs is ^L = 0C = 12
  fAsciiTarget << strHeaderEnd << endl;
  fAsciiTarget.close();

  // append RAW data using the parent's call
  bool bRAWSuccess = AppendRAW(strRawFilename, iHeaderSkip, strTargetFilename, iComponentSize, !EndianConvert::IsBigEndian(), !bSigned, bQuantizeTo8Bit);

  if (bRAWSuccess) {
    return true;
  } else {
    T_ERROR("Error appaneding raw data to header file %s.", strTargetFilename.c_str());
    remove(strTargetFilename.c_str());
    return false;
  }
}
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/fnet/frt/frt.h>
#include <vespa/config/config.h>
#include <vespa/config/frt/frtconfigrequestfactory.h>
#include <vespa/config/frt/frtconnection.h>
#include <vespa/config/common/payload_converter.h>
#include <vespa/fastos/app.h>

#include <string>
#include <sstream>
#include <fstream>

#include <vespa/log/log.h>
LOG_SETUP("vespa-get-config");

using namespace config;

class GetConfig : public FastOS_Application
{
private:
    std::unique_ptr<fnet::frt::StandaloneFRT> _server;
    FRT_Supervisor *_supervisor;
    FRT_Target     *_target;

    GetConfig(const GetConfig &);
    GetConfig &operator=(const GetConfig &);

public:
    GetConfig() : _server(), _supervisor(nullptr), _target(nullptr) {}
    virtual ~GetConfig();
    int usage();
    void initRPC(const char *spec);
    void finiRPC();
    int Main() override;
};

GetConfig::~GetConfig()
{
    LOG_ASSERT(_supervisor == nullptr);
    LOG_ASSERT(_target == nullptr);
}

int
GetConfig::usage()
{
    fprintf(stderr, "usage: %s -n name -i configId\n", _argv[0]);
    fprintf(stderr, "-n name           (config name, including namespace, on the form <namespace>.<name>)\n");
    fprintf(stderr, "-i configId       (config id, optional)\n");
    fprintf(stderr, "-j                (output config as json, optional)\n");
    fprintf(stderr, "-l                (output config in legacy cfg format, optional)\n");
    fprintf(stderr, "-g generation     (config generation, optional)\n");
    fprintf(stderr, "-a schema         (config def schema file, optional)\n");
    fprintf(stderr, "-v defVersion     (config definition version, optional, deprecated)\n");
    fprintf(stderr, "-m defMd5         (definition md5sum, optional)\n");
    fprintf(stderr, "-c configMd5      (config md5sum, optional)\n");
    fprintf(stderr, "-t serverTimeout  (server timeout in seconds, default 3)\n");
    fprintf(stderr, "-w timeout        (timeout in seconds, default 10)\n");
    fprintf(stderr, "-s server         (server hostname, default localhost)\n");
    fprintf(stderr, "-p port           (proxy/server port number, default 19090)\n");
    fprintf(stderr, "-r traceLevel     (tracelevel to use in request, default 0\n");
    fprintf(stderr, "-V vespaVersion   (vespa version to use in request, optional\n");
    fprintf(stderr, "-d                (debug mode)\n");
    fprintf(stderr, "-h                (This help text)\n");
    return 1;
}

void
GetConfig::initRPC(const char *spec)
{
    _server = std::make_unique<fnet::frt::StandaloneFRT>();
    _supervisor = &_server->supervisor();
    _target     = _supervisor->GetTarget(spec);
}

void
GetConfig::finiRPC()
{
    if (_target != nullptr) {
        _target->SubRef();
        _target = nullptr;
    }
    if (_server) {
        _server.reset();
        _supervisor = nullptr;
    }
}

int
GetConfig::Main()
{
    bool debugging = false;
    char c = -1;

    std::vector<vespalib::string> defSchema;
    const char *schema = nullptr;
    const char *defName = nullptr;
    const char *defMD5 = "";
    std::string defNamespace("config");
    const char *serverHost = "localhost";
    const char *configId = getenv("VESPA_CONFIG_ID");
    bool printAsJson = false;
    int traceLevel = config::protocol::readTraceLevel();
    const char *vespaVersionString = nullptr;
    int64_t generation = 0;

    if (configId == nullptr) {
        configId = "";
    }
    const char *configMD5 = "";
    int serverTimeout = 3;
    int clientTimeout = 10;

    int serverPort = 19090;

    const char *optArg = nullptr;
    int optInd = 0;
    while ((c = GetOpt("a:n:v:g:i:jlm:c:t:V:w:r:s:p:dh", optArg, optInd)) != -1) {
        int retval = 1;
        switch (c) {
        case 'a':
            schema = optArg;
            break;
        case 'n':
            defName = optArg;
            break;
        case 'v':
            break;
        case 'g':
            generation = atoll(optArg);
            break;
        case 'i':
            configId = optArg;
            break;
        case 'j':
            printAsJson = true;
            break;
        case 'l':
            printAsJson = false;
            break;
        case 'm':
            defMD5 = optArg;
            break;
        case 'c':
            configMD5 = optArg;
            break;
        case 't':
            serverTimeout = atoi(optArg);
            break;
        case 'w':
            clientTimeout = atoi(optArg);
            break;
        case 'r':
            traceLevel = atoi(optArg);
            break;
        case 'V':
            vespaVersionString = optArg;
            break;
        case 's':
            serverHost = optArg;
            break;
        case 'p':
            serverPort = atoi(optArg);
            break;
        case 'd':
            debugging = true;
            break;
        case 'h':
            retval = 0;
            [[fallthrough]];
        case '?':
        default:
            usage();
            return retval;
        }
    }

    if (defName == nullptr || serverPort == 0) {
        usage();
        return 1;
    }

    if (strchr(defName, '.') != nullptr) {
        const char *tmp = defName;
        defName = strrchr(defName, '.');
        defName++;
        defNamespace = std::string(tmp, defName - tmp - 1);
    }

    if (schema != nullptr) {
        std::ifstream is;
        is.open(schema);
        std::string item;
        while (std::getline(is, item)) {
            if (item.find("namespace=") == std::string::npos) {
                defSchema.push_back(item);
            }
        }
        is.close();
    }
    std::ostringstream tmp;
    tmp << "tcp/";
    tmp << serverHost;
    tmp << ":";
    tmp << serverPort;
    std::string sspec = tmp.str();
    const char *spec = sspec.c_str();
    if (debugging) {
        printf("connecting to '%s'\n", spec);
    }
    initRPC(spec);

    auto vespaVersion = VespaVersion::getCurrentVersion();
    if (vespaVersionString != nullptr) {
        vespaVersion = VespaVersion::fromString(vespaVersionString);
    }

    int protocolVersion = config::protocol::readProtocolVersion();
    FRTConfigRequestFactory requestFactory(protocolVersion, traceLevel, vespaVersion, config::protocol::readProtocolCompressionType());
    FRTConnection connection(spec, *_supervisor, TimingValues());
    ConfigKey key(configId, defName, defNamespace, defMD5, defSchema);
    ConfigState state(configMD5, generation, false);
    FRTConfigRequest::UP request = requestFactory.createConfigRequest(key, &connection, state, serverTimeout * 1000);

    _target->InvokeSync(request->getRequest(), clientTimeout); // seconds

    ConfigResponse::UP response = request->createResponse(request->getRequest());
    response->validateResponse();
    if (response->isError()) {
        fprintf(stderr, "error %d: %s\n",
                response->errorCode(), response->errorMessage().c_str());
    } else {
        response->fill();
        ConfigKey rKey(response->getKey());
        ConfigState rState(response->getConfigState());
        ConfigValue rValue(response->getValue());
        if (debugging) {
            printf("defName    %s\n", rKey.getDefName().c_str());
            printf("defMD5     %s\n", rKey.getDefMd5().c_str());
            printf("defNamespace %s\n", rKey.getDefNamespace().c_str());

            printf("configID   %s\n", rKey.getConfigId().c_str());
            printf("configMD5  %s\n", rState.md5.c_str());

            printf("generation  %" PRId64 "\n", rState.generation);
            printf("internalRedeploy %s\n", rState.internalRedeploy == 0 ? "false" : "true");
            printf("trace       %s\n", response->getTrace().toString().c_str());
        } else if (traceLevel > 0) {
            printf("trace       %s\n", response->getTrace().toString().c_str());
        }
        // TODO: Make printAsJson default
        if (printAsJson) {
            printf("%s\n", rValue.asJson().c_str());
        } else {
            std::vector<vespalib::string> lines = rValue.getLegacyFormat();
            for (uint32_t j = 0; j < lines.size(); j++) {
                printf("%s\n",  lines[j].c_str());
            }
        }
    }
    finiRPC();
    return 0;
}

int main(int argc, char **argv)
{
    GetConfig app;
    return app.Entry(argc, argv);
}
<commit_msg>Simplify by not caching a member<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/fnet/frt/frt.h>
#include <vespa/config/config.h>
#include <vespa/config/frt/frtconfigrequestfactory.h>
#include <vespa/config/frt/frtconnection.h>
#include <vespa/config/common/payload_converter.h>
#include <vespa/fastos/app.h>

#include <string>
#include <sstream>
#include <fstream>

#include <vespa/log/log.h>
LOG_SETUP("vespa-get-config");

using namespace config;

class GetConfig : public FastOS_Application
{
private:
    std::unique_ptr<fnet::frt::StandaloneFRT> _server;
    FRT_Target     *_target;

    GetConfig(const GetConfig &);
    GetConfig &operator=(const GetConfig &);

public:
    GetConfig() : _server(), _target(nullptr) {}
    virtual ~GetConfig();
    int usage();
    void initRPC(const char *spec);
    void finiRPC();
    int Main() override;
};

GetConfig::~GetConfig()
{
    LOG_ASSERT( ! _server);
    LOG_ASSERT(_target == nullptr);
}

int
GetConfig::usage()
{
    fprintf(stderr, "usage: %s -n name -i configId\n", _argv[0]);
    fprintf(stderr, "-n name           (config name, including namespace, on the form <namespace>.<name>)\n");
    fprintf(stderr, "-i configId       (config id, optional)\n");
    fprintf(stderr, "-j                (output config as json, optional)\n");
    fprintf(stderr, "-l                (output config in legacy cfg format, optional)\n");
    fprintf(stderr, "-g generation     (config generation, optional)\n");
    fprintf(stderr, "-a schema         (config def schema file, optional)\n");
    fprintf(stderr, "-v defVersion     (config definition version, optional, deprecated)\n");
    fprintf(stderr, "-m defMd5         (definition md5sum, optional)\n");
    fprintf(stderr, "-c configMd5      (config md5sum, optional)\n");
    fprintf(stderr, "-t serverTimeout  (server timeout in seconds, default 3)\n");
    fprintf(stderr, "-w timeout        (timeout in seconds, default 10)\n");
    fprintf(stderr, "-s server         (server hostname, default localhost)\n");
    fprintf(stderr, "-p port           (proxy/server port number, default 19090)\n");
    fprintf(stderr, "-r traceLevel     (tracelevel to use in request, default 0\n");
    fprintf(stderr, "-V vespaVersion   (vespa version to use in request, optional\n");
    fprintf(stderr, "-d                (debug mode)\n");
    fprintf(stderr, "-h                (This help text)\n");
    return 1;
}

void
GetConfig::initRPC(const char *spec)
{
    _server = std::make_unique<fnet::frt::StandaloneFRT>();
    _target     = _server->supervisor().GetTarget(spec);
}

void
GetConfig::finiRPC()
{
    if (_target != nullptr) {
        _target->SubRef();
        _target = nullptr;
    }
    _server.reset();
}

int
GetConfig::Main()
{
    bool debugging = false;
    char c = -1;

    std::vector<vespalib::string> defSchema;
    const char *schema = nullptr;
    const char *defName = nullptr;
    const char *defMD5 = "";
    std::string defNamespace("config");
    const char *serverHost = "localhost";
    const char *configId = getenv("VESPA_CONFIG_ID");
    bool printAsJson = false;
    int traceLevel = config::protocol::readTraceLevel();
    const char *vespaVersionString = nullptr;
    int64_t generation = 0;

    if (configId == nullptr) {
        configId = "";
    }
    const char *configMD5 = "";
    int serverTimeout = 3;
    int clientTimeout = 10;

    int serverPort = 19090;

    const char *optArg = nullptr;
    int optInd = 0;
    while ((c = GetOpt("a:n:v:g:i:jlm:c:t:V:w:r:s:p:dh", optArg, optInd)) != -1) {
        int retval = 1;
        switch (c) {
        case 'a':
            schema = optArg;
            break;
        case 'n':
            defName = optArg;
            break;
        case 'v':
            break;
        case 'g':
            generation = atoll(optArg);
            break;
        case 'i':
            configId = optArg;
            break;
        case 'j':
            printAsJson = true;
            break;
        case 'l':
            printAsJson = false;
            break;
        case 'm':
            defMD5 = optArg;
            break;
        case 'c':
            configMD5 = optArg;
            break;
        case 't':
            serverTimeout = atoi(optArg);
            break;
        case 'w':
            clientTimeout = atoi(optArg);
            break;
        case 'r':
            traceLevel = atoi(optArg);
            break;
        case 'V':
            vespaVersionString = optArg;
            break;
        case 's':
            serverHost = optArg;
            break;
        case 'p':
            serverPort = atoi(optArg);
            break;
        case 'd':
            debugging = true;
            break;
        case 'h':
            retval = 0;
            [[fallthrough]];
        case '?':
        default:
            usage();
            return retval;
        }
    }

    if (defName == nullptr || serverPort == 0) {
        usage();
        return 1;
    }

    if (strchr(defName, '.') != nullptr) {
        const char *tmp = defName;
        defName = strrchr(defName, '.');
        defName++;
        defNamespace = std::string(tmp, defName - tmp - 1);
    }

    if (schema != nullptr) {
        std::ifstream is;
        is.open(schema);
        std::string item;
        while (std::getline(is, item)) {
            if (item.find("namespace=") == std::string::npos) {
                defSchema.push_back(item);
            }
        }
        is.close();
    }
    std::ostringstream tmp;
    tmp << "tcp/";
    tmp << serverHost;
    tmp << ":";
    tmp << serverPort;
    std::string sspec = tmp.str();
    const char *spec = sspec.c_str();
    if (debugging) {
        printf("connecting to '%s'\n", spec);
    }
    initRPC(spec);

    auto vespaVersion = VespaVersion::getCurrentVersion();
    if (vespaVersionString != nullptr) {
        vespaVersion = VespaVersion::fromString(vespaVersionString);
    }

    int protocolVersion = config::protocol::readProtocolVersion();
    FRTConfigRequestFactory requestFactory(protocolVersion, traceLevel, vespaVersion, config::protocol::readProtocolCompressionType());
    FRTConnection connection(spec, _server->supervisor(), TimingValues());
    ConfigKey key(configId, defName, defNamespace, defMD5, defSchema);
    ConfigState state(configMD5, generation, false);
    FRTConfigRequest::UP request = requestFactory.createConfigRequest(key, &connection, state, serverTimeout * 1000);

    _target->InvokeSync(request->getRequest(), clientTimeout); // seconds

    ConfigResponse::UP response = request->createResponse(request->getRequest());
    response->validateResponse();
    if (response->isError()) {
        fprintf(stderr, "error %d: %s\n",
                response->errorCode(), response->errorMessage().c_str());
    } else {
        response->fill();
        ConfigKey rKey(response->getKey());
        ConfigState rState(response->getConfigState());
        ConfigValue rValue(response->getValue());
        if (debugging) {
            printf("defName    %s\n", rKey.getDefName().c_str());
            printf("defMD5     %s\n", rKey.getDefMd5().c_str());
            printf("defNamespace %s\n", rKey.getDefNamespace().c_str());

            printf("configID   %s\n", rKey.getConfigId().c_str());
            printf("configMD5  %s\n", rState.md5.c_str());

            printf("generation  %" PRId64 "\n", rState.generation);
            printf("internalRedeploy %s\n", rState.internalRedeploy == 0 ? "false" : "true");
            printf("trace       %s\n", response->getTrace().toString().c_str());
        } else if (traceLevel > 0) {
            printf("trace       %s\n", response->getTrace().toString().c_str());
        }
        // TODO: Make printAsJson default
        if (printAsJson) {
            printf("%s\n", rValue.asJson().c_str());
        } else {
            std::vector<vespalib::string> lines = rValue.getLegacyFormat();
            for (uint32_t j = 0; j < lines.size(); j++) {
                printf("%s\n",  lines[j].c_str());
            }
        }
    }
    finiRPC();
    return 0;
}

int main(int argc, char **argv)
{
    GetConfig app;
    return app.Entry(argc, argv);
}
<|endoftext|>