<commit_before>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
//    following disclaimer.
// 2. 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.
//
// 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 HOLDER 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.

/** \file splindex.hpp
 *
 *  \brief Contains definition of splindex_base and specialization of splindex classes.
 */

#ifndef __SPLINDEX_HPP__
#define __SPLINDEX_HPP__

#include <algorithm>
#include <vector>
#include <sstream>
#include <limits>

namespace sddk {

enum splindex_t
{
    block,
    block_cyclic
};

/// Base class for split index.
template <typename T>
class splindex_base
{
  protected:
    /// Rank of the block with local fraction of the global index.
    int rank_{-1};

    /// Number of ranks over which the global index is distributed.
    int num_ranks_{-1};

    /// size of the global index
    T global_index_size_;

    /// Default constructor.
    splindex_base()
    {
    }

    struct location_t
    {
        T local_index;
        int rank;
        location_t(T local_index__, int rank__)
            : local_index(local_index__),
              rank(rank__)
        {
        }
    };

  public:
    inline int rank() const
    {
        return rank_;
    }

    inline int num_ranks() const
    {
        return num_ranks_;
    }

    inline T global_index_size() const
    {
        return global_index_size_;
    }

    static inline T block_size(T size__, int num_ranks__)
    {
        return size__ / num_ranks__ + std::min(T(1), size__ % num_ranks__);
    }
};

template <splindex_t type, typename T = int>
class splindex : public splindex_base<T>
{
};

/// Specialization for the block distribution.
template <typename T>
class splindex<block, T> : public splindex_base<T>
{
  private:
    T block_size_;

    void init(T global_index_size__, int num_ranks__, int rank__)
    {
        this->global_index_size_ = global_index_size__;

        if (num_ranks__ < 0) {
            std::stringstream s;
            s << "wrong number of ranks: " << num_ranks__;
            throw std::runtime_error(s.str());
        }
        this->num_ranks_ = num_ranks__;

        if (rank__ < 0 || rank__ >= num_ranks__) {
            std::stringstream s;
            s << "wrong rank: " << rank__;
            throw std::runtime_error(s.str());
        }
        this->rank_ = rank__;

        block_size_ = this->block_size(global_index_size__, num_ranks__);
    }

  public:
    /// Default constructor
    splindex()
    {
    }

    /// Constructor.
    splindex(T global_index_size__, int num_ranks__, int rank__)
    {
        init(global_index_size__, num_ranks__, rank__);
    }

    /// Return "local index, rank" pair for a global index.
    inline typename splindex_base<T>::location_t location(T idxglob__) const
    {
        assert(idxglob__ < this->global_index_size_);

        int rank = int(idxglob__ / block_size_);
        T idxloc = idxglob__ - rank * block_size_;

        //return std::pair<T, int>(idxloc, rank);
        return typename splindex_base<T>::location_t(idxloc, rank);
    }

    /// Return local size of the split index for an arbitrary rank.
    inline T local_size(int rank__) const
    {
        assert(rank__ >= 0 && rank__ < this->num_ranks_);

        int n = static_cast<int>(this->global_index_size_ / block_size_);
        if (rank__ < n) {
            return block_size_;
        } else if (rank__ == n) {
            return this->global_index_size_ - rank__ * block_size_;
        } else {
            return 0;
        }
    }

    /// Return local size of the split index for a current rank.
    inline T local_size() const
    {
        return local_size(this->rank_);
    }

    /// Return rank which holds the element with the given global index.
    inline int local_rank(T idxglob__) const
    {
        return location(idxglob__).rank;
    }

    /// Return local index of the element for the rank which handles the given global index.
    inline T local_index(T idxglob__) const
    {
        return location(idxglob__).local_index;
    }

    /// Return global index of an element by local index and rank.
    inline T global_index(T idxloc__, int rank__) const
    {
        assert(rank__ >= 0 && rank__ < this->num_ranks_);

        if (local_size(rank__) == 0)
            return std::numeric_limits<T>::max();

        assert(idxloc__ < local_size(rank__));

        return rank__ * block_size_ + idxloc__;
    }

    inline T global_offset() const
    {
        return global_index(0, this->rank_);
    }

    inline T global_offset(int rank__) const
    {
        return global_index(0, rank__);
    }

    inline T operator[](T idxloc__) const
    {
        return global_index(idxloc__, this->rank_);
    }

    inline std::vector<T> offsets() const
    {
        std::vector<T> v(this->num_ranks_);
        for (int i = 0; i < this->num_ranks_; i++) {
            v[i] = global_offset(i);
        }
        return std::move(v);
    }

    inline std::vector<T> counts() const
    {
        std::vector<T> v(this->num_ranks_);
        for (int i = 0; i < this->num_ranks_; i++) {
            v[i] = local_size(i);
        }
        return std::move(v);
    }
};

/// Specialization for the block-cyclic distribution.
template <typename T>
class splindex<block_cyclic, T> : public splindex_base<T>
{
  private:
    /// cyclic block size of the distribution
    int block_size_{-1};

    // Check and initialize variables.
    void init(T global_index_size__, int num_ranks__, int rank__, int block_size__)
    {
        this->global_index_size_ = global_index_size__;

        if (num_ranks__ < 0) {
            std::stringstream s;
            s << "wrong number of ranks: " << num_ranks__;
            throw std::runtime_error(s.str());
        }
        this->num_ranks_ = num_ranks__;

        if (rank__ < 0 || rank__ >= num_ranks__) {
            std::stringstream s;
            s << "wrong rank: " << rank__;
            throw std::runtime_error(s.str());
        }
        this->rank_ = rank__;

        if (block_size__ <= 0) {
            std::stringstream s;
            s << "wrong block size: " << block_size__;
            throw std::runtime_error(s.str());
        }
        block_size_ = block_size__;
    }

  public:
    /// Default constructor
    splindex()
    {
    }

    /// Constructor with implicit cyclic block size
    splindex(T global_index_size__, int num_ranks__, int rank__, int bs__)
    {
        init(global_index_size__, num_ranks__, rank__, bs__);
    }

    /// Return "local index, rank" pair for a global index.
    inline typename splindex_base<T>::location_t location(T idxglob__) const
    {
        assert(idxglob__ < this->global_index_size_);

        /* number of full blocks */
        T num_blocks = idxglob__ / block_size_;

        /* local index */
        T idxloc = (num_blocks / this->num_ranks_) * block_size_ + idxglob__ % block_size_;

        /* corresponding rank */
        int rank = static_cast<int>(num_blocks % this->num_ranks_);

        return typename splindex_base<T>::location_t(idxloc, rank);
    }

    /// Return local size of the split index for an arbitrary rank.
    inline T local_size(int rank__) const
    {
        assert(rank__ >= 0 && rank__ < this->num_ranks_);

        /* number of full blocks */
        T num_blocks = this->global_index_size_ / block_size_;

        T n = (num_blocks / this->num_ranks_) * block_size_;

        int rank_offs = static_cast<int>(num_blocks % this->num_ranks_);

        if (rank__ < rank_offs) {
            n += block_size_;
        } else if (rank__ == rank_offs) {
            n += this->global_index_size_ % block_size_;
        }
        return n;
    }

    /// Return local size of the split index for a current rank.
    inline T local_size() const
    {
        return local_size(this->rank_);
    }

    /// Return rank which holds the element with the given global index.
    inline int local_rank(T idxglob__) const
    {
        return location(idxglob__).rank;
    }

    /// Return local index of the element for the rank which handles the given global index.
    inline T local_index(T idxglob__) const
    {
        return location(idxglob__).local_index;
    }

    inline T global_index(T idxloc__, int rank__) const
    {
        assert(rank__ >= 0 && rank__ < this->num_ranks_);
        assert(idxloc__ < local_size(rank__));

        T nb = idxloc__ / block_size_;

        return (nb * this->num_ranks_ + rank__) * block_size_ + idxloc__ % block_size_;
    }

    inline T operator[](T idxloc__) const
    {
        return global_index(idxloc__, this->rank_);
    }
};

} // namespace sddk

#endif // __SPLINDEX_HPP__
<commit_msg>new custom splindex<commit_after>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
//    following disclaimer.
// 2. 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.
//
// 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 HOLDER 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.

/** \file splindex.hpp
 *
 *  \brief Contains definition of splindex_base and specialization of splindex classes.
 */

#ifndef __SPLINDEX_HPP__
#define __SPLINDEX_HPP__

#include <algorithm>
#include <vector>
#include <sstream>
#include <limits>

namespace sddk {

enum splindex_t
{
    block,
    block_cyclic,
    custom
};

/// Base class for split index.
template <typename T>
class splindex_base
{
  protected:
    /// Rank of the block with local fraction of the global index.
    int rank_{-1};

    /// Number of ranks over which the global index is distributed.
    int num_ranks_{-1};

    /// size of the global index
    T global_index_size_;

    /// Default constructor.
    splindex_base()
    {
    }

    struct location_t
    {
        T local_index;
        int rank;
        location_t(T local_index__, int rank__)
            : local_index(local_index__)
            , rank(rank__)
        {
        }
    };

  public:
    inline int rank() const
    {
        return rank_;
    }

    inline int num_ranks() const
    {
        return num_ranks_;
    }

    inline T global_index_size() const
    {
        return global_index_size_;
    }

    static inline T block_size(T size__, int num_ranks__)
    {
        return size__ / num_ranks__ + std::min(T(1), size__ % num_ranks__);
    }
};

template <splindex_t type, typename T = int>
class splindex : public splindex_base<T>
{
};

/// Specialization for the block distribution.
template <typename T>
class splindex<block, T> : public splindex_base<T>
{
  private:
    T block_size_;

    void init(T global_index_size__, int num_ranks__, int rank__)
    {
        this->global_index_size_ = global_index_size__;

        if (num_ranks__ < 0) {
            std::stringstream s;
            s << "wrong number of ranks: " << num_ranks__;
            throw std::runtime_error(s.str());
        }
        this->num_ranks_ = num_ranks__;

        if (rank__ < 0 || rank__ >= num_ranks__) {
            std::stringstream s;
            s << "wrong rank: " << rank__;
            throw std::runtime_error(s.str());
        }
        this->rank_ = rank__;

        block_size_ = this->block_size(global_index_size__, num_ranks__);
    }

  public:
    /// Default constructor
    splindex()
    {
    }

    /// Constructor.
    splindex(T global_index_size__, int num_ranks__, int rank__)
    {
        init(global_index_size__, num_ranks__, rank__);
    }

    /// Return "local index, rank" pair for a global index.
    inline typename splindex_base<T>::location_t location(T idxglob__) const
    {
        assert(idxglob__ < this->global_index_size_);

        int rank = int(idxglob__ / block_size_);
        T idxloc = idxglob__ - rank * block_size_;

        //return std::pair<T, int>(idxloc, rank);
        return typename splindex_base<T>::location_t(idxloc, rank);
    }

    /// Return local size of the split index for an arbitrary rank.
    inline T local_size(int rank__) const
    {
        assert(rank__ >= 0 && rank__ < this->num_ranks_);

        int n = static_cast<int>(this->global_index_size_ / block_size_);
        if (rank__ < n) {
            return block_size_;
        } else if (rank__ == n) {
            return this->global_index_size_ - rank__ * block_size_;
        } else {
            return 0;
        }
    }

    /// Return local size of the split index for a current rank.
    inline T local_size() const
    {
        return local_size(this->rank_);
    }

    /// Return rank which holds the element with the given global index.
    inline int local_rank(T idxglob__) const
    {
        return location(idxglob__).rank;
    }

    /// Return local index of the element for the rank which handles the given global index.
    inline T local_index(T idxglob__) const
    {
        return location(idxglob__).local_index;
    }

    /// Return global index of an element by local index and rank.
    inline T global_index(T idxloc__, int rank__) const
    {
        assert(rank__ >= 0 && rank__ < this->num_ranks_);

        if (local_size(rank__) == 0)
            return std::numeric_limits<T>::max();

        assert(idxloc__ < local_size(rank__));

        return rank__ * block_size_ + idxloc__;
    }

    inline T global_offset() const
    {
        return global_index(0, this->rank_);
    }

    inline T global_offset(int rank__) const
    {
        return global_index(0, rank__);
    }

    inline T operator[](T idxloc__) const
    {
        return global_index(idxloc__, this->rank_);
    }

    inline std::vector<T> offsets() const
    {
        std::vector<T> v(this->num_ranks_);
        for (int i = 0; i < this->num_ranks_; i++) {
            v[i] = global_offset(i);
        }
        return std::move(v);
    }

    inline std::vector<T> counts() const
    {
        std::vector<T> v(this->num_ranks_);
        for (int i = 0; i < this->num_ranks_; i++) {
            v[i] = local_size(i);
        }
        return std::move(v);
    }
};

/// Specialization for the block-cyclic distribution.
template <typename T>
class splindex<block_cyclic, T> : public splindex_base<T>
{
  private:
    /// cyclic block size of the distribution
    int block_size_{-1};

    // Check and initialize variables.
    void init(T global_index_size__, int num_ranks__, int rank__, int block_size__)
    {
        this->global_index_size_ = global_index_size__;

        if (num_ranks__ < 0) {
            std::stringstream s;
            s << "wrong number of ranks: " << num_ranks__;
            throw std::runtime_error(s.str());
        }
        this->num_ranks_ = num_ranks__;

        if (rank__ < 0 || rank__ >= num_ranks__) {
            std::stringstream s;
            s << "wrong rank: " << rank__;
            throw std::runtime_error(s.str());
        }
        this->rank_ = rank__;

        if (block_size__ <= 0) {
            std::stringstream s;
            s << "wrong block size: " << block_size__;
            throw std::runtime_error(s.str());
        }
        block_size_ = block_size__;
    }

  public:
    /// Default constructor
    splindex()
    {
    }

    /// Constructor with implicit cyclic block size
    splindex(T global_index_size__, int num_ranks__, int rank__, int bs__)
    {
        init(global_index_size__, num_ranks__, rank__, bs__);
    }

    /// Return "local index, rank" pair for a global index.
    inline typename splindex_base<T>::location_t location(T idxglob__) const
    {
        assert(idxglob__ < this->global_index_size_);

        /* number of full blocks */
        T num_blocks = idxglob__ / block_size_;

        /* local index */
        T idxloc = (num_blocks / this->num_ranks_) * block_size_ + idxglob__ % block_size_;

        /* corresponding rank */
        int rank = static_cast<int>(num_blocks % this->num_ranks_);

        return typename splindex_base<T>::location_t(idxloc, rank);
    }

    /// Return local size of the split index for an arbitrary rank.
    inline T local_size(int rank__) const
    {
        assert(rank__ >= 0 && rank__ < this->num_ranks_);

        /* number of full blocks */
        T num_blocks = this->global_index_size_ / block_size_;

        T n = (num_blocks / this->num_ranks_) * block_size_;

        int rank_offs = static_cast<int>(num_blocks % this->num_ranks_);

        if (rank__ < rank_offs) {
            n += block_size_;
        } else if (rank__ == rank_offs) {
            n += this->global_index_size_ % block_size_;
        }
        return n;
    }

    /// Return local size of the split index for a current rank.
    inline T local_size() const
    {
        return local_size(this->rank_);
    }

    /// Return rank which holds the element with the given global index.
    inline int local_rank(T idxglob__) const
    {
        return location(idxglob__).rank;
    }

    /// Return local index of the element for the rank which handles the given global index.
    inline T local_index(T idxglob__) const
    {
        return location(idxglob__).local_index;
    }

    inline T global_index(T idxloc__, int rank__) const
    {
        assert(rank__ >= 0 && rank__ < this->num_ranks_);
        assert(idxloc__ < local_size(rank__));

        T nb = idxloc__ / block_size_;

        return (nb * this->num_ranks_ + rank__) * block_size_ + idxloc__ % block_size_;
    }

    inline T operator[](T idxloc__) const
    {
        return global_index(idxloc__, this->rank_);
    }
};

/// Specialization for the block distribution.
template <typename T>
class splindex<custom, T> : public splindex_base<T>
{
  private:
    std::vector<std::vector<T>> global_index_;
    std::vector<typename splindex_base<T>::location_t> locations_;

  public:
    /// Default constructor.
    splindex()
    {
    }

    /// Constructor with specific partitioning.
    /** The idx_map vector is expected to be of global size and store global to local index mapping for
     *  consecutive order of ranks. */
    splindex(T global_index_size__, int num_ranks__, int rank__, std::vector<T> idx_map__)
    {
        this->global_index_size_ = global_index_size__;

        if (num_ranks__ < 0) {
            std::stringstream s;
            s << "wrong number of ranks: " << num_ranks__;
            throw std::runtime_error(s.str());
        }
        this->num_ranks_ = num_ranks__;

        if (rank__ < 0 || rank__ >= num_ranks__) {
            std::stringstream s;
            s << "wrong rank: " << rank__;
            throw std::runtime_error(s.str());
        }
        this->rank_ = rank__;

        for (T i = 0; i < global_index_size__; i++) {
            if (idx_map__[i] == 0) {
                global_index_.push_back(std::vector<T>());
            }
            global_index_.back().push_back(i);
        }
        for (int r = 0; r < num_ranks__; r++) {
            for (int i = 0; i < local_size(r); i++) {
                locations_.push_back(splindex_base<T>::location_t(i, r));
            }
        }
        assert(static_cast<T>(locations_.size()) == global_index_size__);
    }

    inline T local_size(int rank__) const
    {
        assert(rank__ >= 0);
        assert(rank__ < this->num_ranks_);
        return static_cast<T>(global_index_[rank__].size());
    }

    inline T local_size() const
    {
        return local_size(this->rank_);
    }

    inline int local_rank(T idxglob__) const
    {
        return locations_[idxglob__].rank;
    }

    inline T local_index(T idxglob__) const
    {
        return locations_[idxglob__].local_index;
    }

    inline T global_index(T idxloc__, int rank__) const
    {
        return global_index_[rank__][idxloc__];
    }

    inline T operator[](T idxloc__) const
    {
        return global_index(idxloc__, this->rank_);
    }
};

} // namespace sddk

#endif // __SPLINDEX_HPP__
<|endoftext|>


<commit_before>// Piano Hero
// Copyright (c)2006 Nicholas Piegdon
// See license.txt for license information

#include "State_Playing.h"
#include "State_TrackSelection.h"
#include "version.h"

#include <string>
using namespace std;

#include "string_util.h"
#include "MenuLayout.h"
#include "TextWriter.h"

#include "libmidi\Midi.h"
#include "libmidi\MidiTrack.h"
#include "libmidi\MidiEvent.h"
#include "libmidi\MidiUtil.h"

#include "libmidi\MidiComm.h"

void PlayingState::ResetSong()
{
   m_state.midi_out->Reset();

   // NOTE: These should be moved to a configuration file
   // along with ALL other "const static something" variables.
   const static unsigned long long LeadIn = 6000000;
   const static unsigned long long LeadOut = 2500000;

   if (!m_state.midi) return;

   m_state.midi->Reset(LeadIn, LeadOut);
   m_notes = m_state.midi->Notes();

   unsigned long long additional_time = m_state.midi->GetFirstNoteMicroseconds();
   additional_time -= LeadIn;
   Play(additional_time);
}

PlayingState::PlayingState(const SharedState &state)
   : m_state(state), m_keyboard(0), m_first_update(true), m_paused(false)
{ }

void PlayingState::Init()
{
   if (!m_state.midi) throw GameStateError("PlayingState: Init was passed a null MIDI!");

   m_playback_speed = 100;

   // This many microseconds of the song will
   // be shown on the screen at once
   const static unsigned long long DefaultShowDurationMicroseconds = 5000000;
   m_show_duration = DefaultShowDurationMicroseconds;

   m_keyboard = new KeyboardDisplay(KeyboardSize88, GetStateWidth() - 2*Layout::ScreenMarginX, CalcKeyboardHeight());

   // Hide the mouse cursor while we're playing
   ShowCursor(false);

   ResetSong();
}

PlayingState::~PlayingState()
{
   ShowCursor(true);
}

int PlayingState::CalcKeyboardHeight() const
{
   // Start with the size of the screen
   int height = GetStateHeight();

   // Leave at least enough for a title bar and horizontal
   // rule at the top
   height -= Layout::ScreenMarginY;

   // Allow another couple lines of text below the HR
   height -= Layout::ButtonFontSize * 4;

   return height;
}

void PlayingState::Play(unsigned long long delta_microseconds)
{
   MidiEventListWithTrackId evs = m_state.midi->Update(delta_microseconds);

   const size_t length = evs.size();
   for (size_t i = 0; i < length; ++i)
   {
      const size_t &track_id = evs[i].first;
      const MidiEvent &ev = evs[i].second;

      // Draw refers to the keys lighting up (automatically) -- not necessarily
      // the falling notes.  The KeyboardDisplay object contains its own logic
      // to decide how to draw the falling notes
      bool draw = false;
      bool play = false;
      switch (m_state.track_properties[track_id].mode)
      {
      case ModeNotPlayed:           draw = false;  play = false;  break;
      case ModePlayedButHidden:     draw = false;  play = true;   break;
      case ModeYouPlay:             draw = false;  play = false;  break;
      case ModePlayedAutomatically: draw = true;   play = true;   break;
      }

      if (draw && ev.Type() == MidiEventType_NoteOn || ev.Type() == MidiEventType_NoteOff)
      {
         int vel = ev.NoteVelocity();
         const string name = MidiEvent::NoteName(ev.NoteNumber());

         m_keyboard->SetKeyActive(name, (vel > 0), m_state.track_properties[track_id].color);
      }

      if (play) m_state.midi_out->Write(ev);
   }
}

void PlayingState::Update()
{
   const unsigned long long current_microseconds = GetStateMilliseconds() * 1000;
   unsigned long long delta_microseconds = static_cast<unsigned long long>(GetDeltaMilliseconds()) * 1000;

   // The 100 term is really paired with the playback speed, but this
   // formation is less likely to produce overflow errors.
   delta_microseconds = (delta_microseconds / 100) * m_playback_speed;

   if (m_paused) delta_microseconds = 0;

   // Our delta milliseconds on the first frame after state start is extra
   // long because we just reset the MIDI.  By skipping the "Play" that
   // update, we don't have an artificially fast-forwarded start.
   if (!m_first_update)
   {
      Play(delta_microseconds);
   }
   m_first_update = false;

   // Delete notes that are finished playing
   unsigned long long cur_time = m_state.midi->GetSongPositionInMicroseconds();
   for (TranslatedNoteSet::iterator i = m_notes.begin(); i != m_notes.end(); )
   {
      TranslatedNoteSet::iterator next = i;
      ++next;

      if (i->end < cur_time) m_notes.erase(i);
      i = next;
   }

   if (IsKeyPressed(KeyUp))
   {
      m_show_duration -= 250000;
      if (m_show_duration < 250000) m_show_duration = 250000;
   }

   if (IsKeyPressed(KeyDown))
   {
      m_show_duration += 250000;
      if (m_show_duration > 10000000) m_show_duration = 10000000;
   }

   if (IsKeyPressed(KeyLeft))
   {
      m_playback_speed -= 10;
      if (m_playback_speed < 0) m_playback_speed = 0;
   }

   if (IsKeyPressed(KeyRight))
   {
      m_playback_speed += 10;
      if (m_playback_speed > 400) m_playback_speed = 400;
   }

   if (IsKeyPressed(KeyEnter))
   {
      ResetSong();
      m_keyboard->ResetActiveKeys();
   }

   if (IsKeyPressed(KeySpace))
   {
      m_paused = !m_paused;
   }

   if (IsKeyPressed(KeyEscape) || m_state.midi->GetSongPercentageComplete() >= 1.0)
   {
      ChangeState(new TrackSelectionState(m_state));
   }
}

void PlayingState::Draw(HDC hdc) const
{
   m_keyboard->Draw(hdc, Layout::ScreenMarginX, GetStateHeight() - CalcKeyboardHeight(), m_notes,
      m_show_duration, m_state.midi->GetSongPositionInMicroseconds(), m_state.track_properties);

   Layout::DrawTitle(hdc, m_state.song_title);
   Layout::DrawHorizontalRule(hdc, GetStateWidth(), Layout::ScreenMarginY);

   double non_zero_playback_speed = ( (m_playback_speed == 0) ? 0.1 : (m_playback_speed/100.0) );
   unsigned long long tot_seconds = static_cast<unsigned long long>((m_state.midi->GetSongLengthInMicroseconds() / 100000.0) / non_zero_playback_speed);
   unsigned long long cur_seconds = static_cast<unsigned long long>((m_state.midi->GetSongPositionInMicroseconds() / 100000.0) / non_zero_playback_speed);
   int completion  = static_cast<int>(m_state.midi->GetSongPercentageComplete() * 100.0);

   unsigned int tot_min = static_cast<unsigned int>((tot_seconds/10) / 60);
   unsigned int tot_sec = static_cast<unsigned int>((tot_seconds/10) % 60);
   unsigned int tot_ten = static_cast<unsigned int>( tot_seconds%10      );
   const wstring total_time = WSTRING(tot_min << L":" << setfill(L'0') << setw(2) << tot_sec << L"." << tot_ten);

   unsigned int cur_min = static_cast<unsigned int>((cur_seconds/10) / 60);
   unsigned int cur_sec = static_cast<unsigned int>((cur_seconds/10) % 60);
   unsigned int cur_ten = static_cast<unsigned int>( cur_seconds%10      );
   const wstring current_time = WSTRING(cur_min << L":" << setfill(L'0') << setw(2) << cur_sec << L"." << cur_ten);
   const wstring percent_complete = WSTRING(L" (" << completion << L"%)");

   int small_text_y = Layout::ScreenMarginY + Layout::SmallFontSize;
   TextWriter stats1(Layout::ScreenMarginX, small_text_y, hdc, false, Layout::SmallFontSize);
   stats1 << Text(L"Time: ", Gray) << current_time << L" / " << total_time << percent_complete << newline;
   stats1 << Text(L"Speed: ", Gray) << m_playback_speed << L"%" << newline;

   TextWriter stats2(Layout::ScreenMarginX + 220, small_text_y, hdc, false, Layout::SmallFontSize);
   stats2 << Text(L"Events: ", Gray) << m_state.midi->AggregateEventCount() - m_state.midi->AggregateEventsRemain() << L" / " << m_state.midi->AggregateEventCount() << newline;
   stats2 << Text(L"Notes: ", Gray) << m_state.midi->AggregateNoteCount() - m_state.midi->AggregateNotesRemain() << L" / " << m_state.midi->AggregateNoteCount() << newline;
}

<commit_msg>Early input device selection.<commit_after>// Piano Hero
// Copyright (c)2006 Nicholas Piegdon
// See license.txt for license information

#include "State_Playing.h"
#include "State_TrackSelection.h"
#include "version.h"

#include <string>
using namespace std;

#include "string_util.h"
#include "MenuLayout.h"
#include "TextWriter.h"

#include "libmidi\Midi.h"
#include "libmidi\MidiTrack.h"
#include "libmidi\MidiEvent.h"
#include "libmidi\MidiUtil.h"

#include "libmidi\MidiComm.h"

void PlayingState::ResetSong()
{
   if (m_state.midi_out) m_state.midi_out->Reset();

   // NOTE: These should be moved to a configuration file
   // along with ALL other "const static something" variables.
   const static unsigned long long LeadIn = 6000000;
   const static unsigned long long LeadOut = 2500000;

   if (!m_state.midi) return;

   m_state.midi->Reset(LeadIn, LeadOut);
   m_notes = m_state.midi->Notes();

   unsigned long long additional_time = m_state.midi->GetFirstNoteMicroseconds();
   additional_time -= LeadIn;
   Play(additional_time);
}

PlayingState::PlayingState(const SharedState &state)
   : m_state(state), m_keyboard(0), m_first_update(true), m_paused(false)
{ }

void PlayingState::Init()
{
   if (!m_state.midi) throw GameStateError("PlayingState: Init was passed a null MIDI!");

   m_playback_speed = 100;

   // This many microseconds of the song will
   // be shown on the screen at once
   const static unsigned long long DefaultShowDurationMicroseconds = 5000000;
   m_show_duration = DefaultShowDurationMicroseconds;

   m_keyboard = new KeyboardDisplay(KeyboardSize88, GetStateWidth() - 2*Layout::ScreenMarginX, CalcKeyboardHeight());

   // Hide the mouse cursor while we're playing
   ShowCursor(false);

   ResetSong();
}

PlayingState::~PlayingState()
{
   ShowCursor(true);
}

int PlayingState::CalcKeyboardHeight() const
{
   // Start with the size of the screen
   int height = GetStateHeight();

   // Leave at least enough for a title bar and horizontal
   // rule at the top
   height -= Layout::ScreenMarginY;

   // Allow another couple lines of text below the HR
   height -= Layout::ButtonFontSize * 4;

   return height;
}

void PlayingState::Play(unsigned long long delta_microseconds)
{
   MidiEventListWithTrackId evs = m_state.midi->Update(delta_microseconds);

   const size_t length = evs.size();
   for (size_t i = 0; i < length; ++i)
   {
      const size_t &track_id = evs[i].first;
      const MidiEvent &ev = evs[i].second;

      // Draw refers to the keys lighting up (automatically) -- not necessarily
      // the falling notes.  The KeyboardDisplay object contains its own logic
      // to decide how to draw the falling notes
      bool draw = false;
      bool play = false;
      switch (m_state.track_properties[track_id].mode)
      {
      case ModeNotPlayed:           draw = false;  play = false;  break;
      case ModePlayedButHidden:     draw = false;  play = true;   break;
      case ModeYouPlay:             draw = false;  play = false;  break;
      case ModePlayedAutomatically: draw = true;   play = true;   break;
      }

      if (draw && ev.Type() == MidiEventType_NoteOn || ev.Type() == MidiEventType_NoteOff)
      {
         int vel = ev.NoteVelocity();
         const string name = MidiEvent::NoteName(ev.NoteNumber());

         m_keyboard->SetKeyActive(name, (vel > 0), m_state.track_properties[track_id].color);
      }

      if (play && m_state.midi_out) m_state.midi_out->Write(ev);
   }
}

void PlayingState::Update()
{
   const unsigned long long current_microseconds = GetStateMilliseconds() * 1000;
   unsigned long long delta_microseconds = static_cast<unsigned long long>(GetDeltaMilliseconds()) * 1000;

   // The 100 term is really paired with the playback speed, but this
   // formation is less likely to produce overflow errors.
   delta_microseconds = (delta_microseconds / 100) * m_playback_speed;

   if (m_paused) delta_microseconds = 0;

   // Our delta milliseconds on the first frame after state start is extra
   // long because we just reset the MIDI.  By skipping the "Play" that
   // update, we don't have an artificially fast-forwarded start.
   if (!m_first_update)
   {
      Play(delta_microseconds);
   }
   m_first_update = false;

   // Delete notes that are finished playing
   unsigned long long cur_time = m_state.midi->GetSongPositionInMicroseconds();
   for (TranslatedNoteSet::iterator i = m_notes.begin(); i != m_notes.end(); )
   {
      TranslatedNoteSet::iterator next = i;
      ++next;

      if (i->end < cur_time) m_notes.erase(i);
      i = next;
   }

   if (IsKeyPressed(KeyUp))
   {
      m_show_duration -= 250000;
      if (m_show_duration < 250000) m_show_duration = 250000;
   }

   if (IsKeyPressed(KeyDown))
   {
      m_show_duration += 250000;
      if (m_show_duration > 10000000) m_show_duration = 10000000;
   }

   if (IsKeyPressed(KeyLeft))
   {
      m_playback_speed -= 10;
      if (m_playback_speed < 0) m_playback_speed = 0;
   }

   if (IsKeyPressed(KeyRight))
   {
      m_playback_speed += 10;
      if (m_playback_speed > 400) m_playback_speed = 400;
   }

   if (IsKeyPressed(KeyEnter))
   {
      ResetSong();
      m_keyboard->ResetActiveKeys();
   }

   if (IsKeyPressed(KeySpace))
   {
      m_paused = !m_paused;
   }

   if (IsKeyPressed(KeyEscape) || m_state.midi->GetSongPercentageComplete() >= 1.0)
   {
      ChangeState(new TrackSelectionState(m_state));
   }
}

void PlayingState::Draw(HDC hdc) const
{
   m_keyboard->Draw(hdc, Layout::ScreenMarginX, GetStateHeight() - CalcKeyboardHeight(), m_notes,
      m_show_duration, m_state.midi->GetSongPositionInMicroseconds(), m_state.track_properties);

   Layout::DrawTitle(hdc, m_state.song_title);
   Layout::DrawHorizontalRule(hdc, GetStateWidth(), Layout::ScreenMarginY);

   double non_zero_playback_speed = ( (m_playback_speed == 0) ? 0.1 : (m_playback_speed/100.0) );
   unsigned long long tot_seconds = static_cast<unsigned long long>((m_state.midi->GetSongLengthInMicroseconds() / 100000.0) / non_zero_playback_speed);
   unsigned long long cur_seconds = static_cast<unsigned long long>((m_state.midi->GetSongPositionInMicroseconds() / 100000.0) / non_zero_playback_speed);
   int completion  = static_cast<int>(m_state.midi->GetSongPercentageComplete() * 100.0);

   unsigned int tot_min = static_cast<unsigned int>((tot_seconds/10) / 60);
   unsigned int tot_sec = static_cast<unsigned int>((tot_seconds/10) % 60);
   unsigned int tot_ten = static_cast<unsigned int>( tot_seconds%10      );
   const wstring total_time = WSTRING(tot_min << L":" << setfill(L'0') << setw(2) << tot_sec << L"." << tot_ten);

   unsigned int cur_min = static_cast<unsigned int>((cur_seconds/10) / 60);
   unsigned int cur_sec = static_cast<unsigned int>((cur_seconds/10) % 60);
   unsigned int cur_ten = static_cast<unsigned int>( cur_seconds%10      );
   const wstring current_time = WSTRING(cur_min << L":" << setfill(L'0') << setw(2) << cur_sec << L"." << cur_ten);
   const wstring percent_complete = WSTRING(L" (" << completion << L"%)");

   int small_text_y = Layout::ScreenMarginY + Layout::SmallFontSize;
   TextWriter stats1(Layout::ScreenMarginX, small_text_y, hdc, false, Layout::SmallFontSize);
   stats1 << Text(L"Time: ", Gray) << current_time << L" / " << total_time << percent_complete << newline;
   stats1 << Text(L"Speed: ", Gray) << m_playback_speed << L"%" << newline;

   TextWriter stats2(Layout::ScreenMarginX + 220, small_text_y, hdc, false, Layout::SmallFontSize);
   stats2 << Text(L"Events: ", Gray) << m_state.midi->AggregateEventCount() - m_state.midi->AggregateEventsRemain() << L" / " << m_state.midi->AggregateEventCount() << newline;
   stats2 << Text(L"Notes: ", Gray) << m_state.midi->AggregateNoteCount() - m_state.midi->AggregateNotesRemain() << L" / " << m_state.midi->AggregateNoteCount() << newline;
}

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//////////////////////////////////////////////////////////////////////////////
//                                                                          //
// The AliDAQ class is responsible for handling all the information about   //
// Data Acquisition configuration. It defines the detector indexing,        //
// the number of DDLs and LDCs per detector.                                //
// The number of LDCs per detector is used only in the simulation in order  //
// to define the configuration of the dateStream application. Therefore the //
// numbers in the corresponding array can be changed without affecting the  //
// rest of the aliroot code.                                                //
// The equipment ID (DDL ID) is an integer (32-bit) number defined as:      //
// Equipment ID = (detectorID << 8) + DDLIndex                              //
// where the detectorID is given by fgkDetectorName array and DDLIndex is   //
// the index of the corresponding DDL inside the detector partition.        //
// Due to DAQ/HLT limitations, the ddl indexes should be consequtive, or    //
// at least without big gaps in between.                                    //
// The sub-detector code use only this class in the simulation and reading  //
// of the raw data.                                                         //
//                                                                          //
// cvetan.cheshkov@cern.ch  2006/06/09                                      //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////

#include <TClass.h>
#include <TString.h>

#include "AliDAQ.h"
#include "AliLog.h"

ClassImp(AliDAQ)

const char* AliDAQ::fgkDetectorName[AliDAQ::kNDetectors] = {
  "ITSSPD",
  "ITSSDD",
  "ITSSSD",
  "TPC",
  "TRD",
  "TOF",
  "HMPID",
  "PHOS",
  "CPV",
  "PMD",
  "MUONTRK",
  "MUONTRG",
  "FMD",
  "T0",
  "VZERO", // Name to be changed to V0 ?
  "ZDC",
  "ACORDE",
  "TRG",
  "EMCAL",
  "HLT"
};

Int_t AliDAQ::fgkNumberOfDdls[AliDAQ::kNDetectors] = {
  20,
  24,
  16,
  216,
  18,
  72,
  20,
  20,
  10,
  6,
  20,
  2,
  3,
  1,
  1,
  1,
  1,
  1,
  24,
  10
};

Float_t AliDAQ::fgkNumberOfLdcs[AliDAQ::kNDetectors] = {
  4,
  4,
  4,
  36,
  3,
  12,
  4,
  4,
  2,
  1,
  4,
  1,
  1,
  0.5,
  0.5,
  1,
  1,
  1,
  4,
  5
};

AliDAQ::AliDAQ(const AliDAQ& source) :
  TObject(source)
{
  // Copy constructor
  // Nothing to be done
}

AliDAQ& AliDAQ::operator = (const AliDAQ& /* source */)
{
  // Assignment operator
  // Nothing to be done
  return *this;
}

Int_t AliDAQ::DetectorID(const char *detectorName)
{
  // Return the detector index
  // corresponding to a given
  // detector name
  TString detStr = detectorName;

  Int_t iDet;
  for(iDet = 0; iDet < kNDetectors; iDet++) {
    if (detStr.CompareTo(fgkDetectorName[iDet],TString::kIgnoreCase) == 0)
      break;
  }
  if (iDet == kNDetectors) {
    AliErrorClass(Form("Invalid detector name: %s !",detectorName));
    return -1;
  }
  return iDet;
}

const char *AliDAQ::DetectorName(Int_t detectorID)
{
  // Returns the name of particular
  // detector identified by its index
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return "";
  }
  return fgkDetectorName[detectorID];
}

Int_t AliDAQ::DdlIDOffset(const char *detectorName)
{
  // Returns the DDL ID offset
  // for a given detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return -1;

  return DdlIDOffset(detectorID);
}

Int_t AliDAQ::DdlIDOffset(Int_t detectorID)
{
  // Returns the DDL ID offset
  // for a given detector identified
  // by its index
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return -1;
  }
  return (detectorID << 8);
}

const char *AliDAQ::DetectorNameFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
  // Returns the detector name for
  // a given DDL ID
  ddlIndex = -1;
  Int_t detectorID = DetectorIDFromDdlID(ddlID,ddlIndex);
  if (detectorID < 0)
    return "";

  return DetectorName(detectorID);
}

Int_t AliDAQ::DetectorIDFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
  // Returns the detector ID and
  // the ddl index within the
  // detector range for
  // a given input DDL ID
  Int_t detectorID = ddlID >> 8;
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return -1;
  }
  ddlIndex = ddlID & 0xFF;
  if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
    AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
		       ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
    ddlIndex = -1;
    return -1;
  }
  return detectorID;
}

Int_t AliDAQ::DdlID(const char *detectorName, Int_t ddlIndex)
{
  // Returns the DDL ID starting from
  // the detector name and the DDL
  // index inside the detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return -1;

  return DdlID(detectorID,ddlIndex);
}

Int_t AliDAQ::DdlID(Int_t detectorID, Int_t ddlIndex)
{
  // Returns the DDL ID starting from
  // the detector ID and the DDL
  // index inside the detector
  Int_t ddlID = DdlIDOffset(detectorID);
  if (ddlID < 0)
    return -1;

  if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
    AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
		       ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
    return -1;
  }

  ddlID += ddlIndex;
  return ddlID;
}

const char *AliDAQ::DdlFileName(const char *detectorName, Int_t ddlIndex)
{
  // Returns the DDL file name
  // (used in the simulation) starting from
  // the detector name and the DDL
  // index inside the detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return "";

  return DdlFileName(detectorID,ddlIndex);
}

const char *AliDAQ::DdlFileName(Int_t detectorID, Int_t ddlIndex)
{
  // Returns the DDL file name
  // (used in the simulation) starting from
  // the detector ID and the DDL
  // index inside the detector
  Int_t ddlID = DdlIDOffset(detectorID);
  if (ddlID < 0)
    return "";

  if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
    AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
		       ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
    return "";
  }

  ddlID += ddlIndex;
  TString fileName = DetectorName(detectorID);
  fileName += "_";
  fileName += ddlID;
  fileName += ".ddl";
  return fileName.Data();
}

Int_t AliDAQ::NumberOfDdls(const char *detectorName)
{
  // Returns the number of DDLs for
  // a given detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return -1;

  return NumberOfDdls(detectorID);
}

Int_t AliDAQ::NumberOfDdls(Int_t detectorID)
{
  // Returns the number of DDLs for
  // a given detector
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return -1;
  }

  return fgkNumberOfDdls[detectorID];
}

Float_t AliDAQ::NumberOfLdcs(const char *detectorName)
{
  // Returns the number of DDLs for
  // a given detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return -1;

  return NumberOfLdcs(detectorID);
}

Float_t AliDAQ::NumberOfLdcs(Int_t detectorID)
{
  // Returns the number of DDLs for
  // a given detector
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return -1;
  }

  return fgkNumberOfLdcs[detectorID];
}

void AliDAQ::PrintConfig()
{
  // Print the DAQ configuration
  // for all the detectors
  printf("====================================================================\n"
	 "|                ALICE Data Acquisition Configuration              |\n"
	 "====================================================================\n"
	 "| Detector ID | Detector Name | DDL Offset | # of DDLs | # of LDCs |\n"
	 "====================================================================\n");
  for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
    printf("|%11d  |%13s  |%10d  |%9d  |%9.1f  |\n",
	   iDet,DetectorName(iDet),DdlIDOffset(iDet),NumberOfDdls(iDet),NumberOfLdcs(iDet));
  }
  printf("====================================================================\n");

}
<commit_msg>Using static TString to keep the name of the file<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//////////////////////////////////////////////////////////////////////////////
//                                                                          //
// The AliDAQ class is responsible for handling all the information about   //
// Data Acquisition configuration. It defines the detector indexing,        //
// the number of DDLs and LDCs per detector.                                //
// The number of LDCs per detector is used only in the simulation in order  //
// to define the configuration of the dateStream application. Therefore the //
// numbers in the corresponding array can be changed without affecting the  //
// rest of the aliroot code.                                                //
// The equipment ID (DDL ID) is an integer (32-bit) number defined as:      //
// Equipment ID = (detectorID << 8) + DDLIndex                              //
// where the detectorID is given by fgkDetectorName array and DDLIndex is   //
// the index of the corresponding DDL inside the detector partition.        //
// Due to DAQ/HLT limitations, the ddl indexes should be consequtive, or    //
// at least without big gaps in between.                                    //
// The sub-detector code use only this class in the simulation and reading  //
// of the raw data.                                                         //
//                                                                          //
// cvetan.cheshkov@cern.ch  2006/06/09                                      //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////

#include <TClass.h>
#include <TString.h>

#include "AliDAQ.h"
#include "AliLog.h"

ClassImp(AliDAQ)

const char* AliDAQ::fgkDetectorName[AliDAQ::kNDetectors] = {
  "ITSSPD",
  "ITSSDD",
  "ITSSSD",
  "TPC",
  "TRD",
  "TOF",
  "HMPID",
  "PHOS",
  "CPV",
  "PMD",
  "MUONTRK",
  "MUONTRG",
  "FMD",
  "T0",
  "VZERO", // Name to be changed to V0 ?
  "ZDC",
  "ACORDE",
  "TRG",
  "EMCAL",
  "HLT"
};

Int_t AliDAQ::fgkNumberOfDdls[AliDAQ::kNDetectors] = {
  20,
  24,
  16,
  216,
  18,
  72,
  20,
  20,
  10,
  6,
  20,
  2,
  3,
  1,
  1,
  1,
  1,
  1,
  24,
  10
};

Float_t AliDAQ::fgkNumberOfLdcs[AliDAQ::kNDetectors] = {
  4,
  4,
  4,
  36,
  3,
  12,
  4,
  4,
  2,
  1,
  4,
  1,
  1,
  0.5,
  0.5,
  1,
  1,
  1,
  4,
  5
};

AliDAQ::AliDAQ(const AliDAQ& source) :
  TObject(source)
{
  // Copy constructor
  // Nothing to be done
}

AliDAQ& AliDAQ::operator = (const AliDAQ& /* source */)
{
  // Assignment operator
  // Nothing to be done
  return *this;
}

Int_t AliDAQ::DetectorID(const char *detectorName)
{
  // Return the detector index
  // corresponding to a given
  // detector name
  TString detStr = detectorName;

  Int_t iDet;
  for(iDet = 0; iDet < kNDetectors; iDet++) {
    if (detStr.CompareTo(fgkDetectorName[iDet],TString::kIgnoreCase) == 0)
      break;
  }
  if (iDet == kNDetectors) {
    AliErrorClass(Form("Invalid detector name: %s !",detectorName));
    return -1;
  }
  return iDet;
}

const char *AliDAQ::DetectorName(Int_t detectorID)
{
  // Returns the name of particular
  // detector identified by its index
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return "";
  }
  return fgkDetectorName[detectorID];
}

Int_t AliDAQ::DdlIDOffset(const char *detectorName)
{
  // Returns the DDL ID offset
  // for a given detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return -1;

  return DdlIDOffset(detectorID);
}

Int_t AliDAQ::DdlIDOffset(Int_t detectorID)
{
  // Returns the DDL ID offset
  // for a given detector identified
  // by its index
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return -1;
  }
  return (detectorID << 8);
}

const char *AliDAQ::DetectorNameFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
  // Returns the detector name for
  // a given DDL ID
  ddlIndex = -1;
  Int_t detectorID = DetectorIDFromDdlID(ddlID,ddlIndex);
  if (detectorID < 0)
    return "";

  return DetectorName(detectorID);
}

Int_t AliDAQ::DetectorIDFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
  // Returns the detector ID and
  // the ddl index within the
  // detector range for
  // a given input DDL ID
  Int_t detectorID = ddlID >> 8;
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return -1;
  }
  ddlIndex = ddlID & 0xFF;
  if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
    AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
		       ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
    ddlIndex = -1;
    return -1;
  }
  return detectorID;
}

Int_t AliDAQ::DdlID(const char *detectorName, Int_t ddlIndex)
{
  // Returns the DDL ID starting from
  // the detector name and the DDL
  // index inside the detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return -1;

  return DdlID(detectorID,ddlIndex);
}

Int_t AliDAQ::DdlID(Int_t detectorID, Int_t ddlIndex)
{
  // Returns the DDL ID starting from
  // the detector ID and the DDL
  // index inside the detector
  Int_t ddlID = DdlIDOffset(detectorID);
  if (ddlID < 0)
    return -1;

  if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
    AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
		       ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
    return -1;
  }

  ddlID += ddlIndex;
  return ddlID;
}

const char *AliDAQ::DdlFileName(const char *detectorName, Int_t ddlIndex)
{
  // Returns the DDL file name
  // (used in the simulation) starting from
  // the detector name and the DDL
  // index inside the detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return "";

  return DdlFileName(detectorID,ddlIndex);
}

const char *AliDAQ::DdlFileName(Int_t detectorID, Int_t ddlIndex)
{
  // Returns the DDL file name
  // (used in the simulation) starting from
  // the detector ID and the DDL
  // index inside the detector
  Int_t ddlID = DdlIDOffset(detectorID);
  if (ddlID < 0)
    return "";

  if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
    AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
		       ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
    return "";
  }

  ddlID += ddlIndex;
  static TString fileName;

  fileName = DetectorName(detectorID);
  fileName += "_";
  fileName += ddlID;
  fileName += ".ddl";
  return fileName.Data();
}

Int_t AliDAQ::NumberOfDdls(const char *detectorName)
{
  // Returns the number of DDLs for
  // a given detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return -1;

  return NumberOfDdls(detectorID);
}

Int_t AliDAQ::NumberOfDdls(Int_t detectorID)
{
  // Returns the number of DDLs for
  // a given detector
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return -1;
  }

  return fgkNumberOfDdls[detectorID];
}

Float_t AliDAQ::NumberOfLdcs(const char *detectorName)
{
  // Returns the number of DDLs for
  // a given detector
  Int_t detectorID = DetectorID(detectorName);
  if (detectorID < 0)
    return -1;

  return NumberOfLdcs(detectorID);
}

Float_t AliDAQ::NumberOfLdcs(Int_t detectorID)
{
  // Returns the number of DDLs for
  // a given detector
  if (detectorID < 0 || detectorID >= kNDetectors) {
    AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
    return -1;
  }

  return fgkNumberOfLdcs[detectorID];
}

void AliDAQ::PrintConfig()
{
  // Print the DAQ configuration
  // for all the detectors
  printf("====================================================================\n"
	 "|                ALICE Data Acquisition Configuration              |\n"
	 "====================================================================\n"
	 "| Detector ID | Detector Name | DDL Offset | # of DDLs | # of LDCs |\n"
	 "====================================================================\n");
  for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
    printf("|%11d  |%13s  |%10d  |%9d  |%9.1f  |\n",
	   iDet,DetectorName(iDet),DdlIDOffset(iDet),NumberOfDdls(iDet),NumberOfLdcs(iDet));
  }
  printf("====================================================================\n");

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: anytostring.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 02:27:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#if ! defined(INCLUDED_COMPHELPER_ANYTOSTRING_HXX)
#define INCLUDED_COMPHELPER_ANYTOSTRING_HXX

#ifndef _RTL_USTRING_HXX_
#include "rtl/ustring.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include "com/sun/star/uno/Any.hxx"
#endif

#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif

namespace comphelper
{

/** Creates a STRING representation out of an ANY value.

    @param value
           ANY value
    @return
           STRING representation of given ANY value
*/
COMPHELPER_DLLPUBLIC ::rtl::OUString anyToString( ::com::sun::star::uno::Any const & value );

}

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.5.246); FILE MERGED 2008/04/01 15:05:18 thb 1.5.246.3: #i85898# Stripping all external header guards 2008/04/01 12:26:23 thb 1.5.246.2: #i85898# Stripping all external header guards 2008/03/31 12:19:27 rt 1.5.246.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: anytostring.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#if ! defined(INCLUDED_COMPHELPER_ANYTOSTRING_HXX)
#define INCLUDED_COMPHELPER_ANYTOSTRING_HXX

#include "rtl/ustring.hxx"
#include "com/sun/star/uno/Any.hxx"
#include "comphelper/comphelperdllapi.h"

namespace comphelper
{

/** Creates a STRING representation out of an ANY value.

    @param value
           ANY value
    @return
           STRING representation of given ANY value
*/
COMPHELPER_DLLPUBLIC ::rtl::OUString anyToString( ::com::sun::star::uno::Any const & value );

}

#endif

<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// Open the mesh and solution file given, create a new solution file,
// and copy all listed variables from the old solution to the new.

#include "libmesh/libmesh.h"

#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/numeric_vector.h"

unsigned int dim = 2; // This gets overridden by most mesh formats

int main(int argc, char** argv)
{
  using namespace libMesh;

  LibMeshInit init(argc, argv);

  Mesh mesh1(dim);
  EquationSystems es1(mesh1);

  std::cout << "Usage: " << argv[0]
            << " mesh oldsolution newsolution system1 variable1 [sys2 var2...]" << std::endl;

  // We should have one system name for each variable name, and those
  // get preceded by an even number of arguments.
  libmesh_assert (!(argc % 2));

  // We should have at least one system/variable pair following the
  // initial arguments
  libmesh_assert_greater_equal (argc, 6);

  mesh1.read(argv[1]);
  std::cout << "Loaded mesh " << argv[1] << std::endl;
  Mesh mesh2(mesh1);
  EquationSystems es2(mesh2);

  es1.read(argv[2],
           EquationSystems::READ_HEADER |
           EquationSystems::READ_DATA |
           EquationSystems::READ_ADDITIONAL_DATA |
           EquationSystems::READ_BASIC_ONLY);
  std::cout << "Loaded solution " << argv[2] << std::endl;

  std::vector<unsigned int> old_sys_num((argc-4)/2),
                            new_sys_num((argc-4)/2),
                            old_var_num((argc-4)/2),
                            new_var_num((argc-4)/2);

  std::vector<const System *> old_system((argc-4)/2);
  std::vector<System *> new_system((argc-4)/2);

  for (int argi = 4; argi < argc; argi += 2)
    {
      const char* sysname = argv[argi];
      const char* varname = argv[argi+1];

      const unsigned int pairnum = (argi-4)/2;

      libmesh_assert(es1.has_system(sysname));

      const System &old_sys = es1.get_system(sysname);
      old_system[pairnum] = &old_sys;
      old_sys_num[pairnum] = old_sys.number();

      libmesh_assert(old_sys.has_variable(varname));

      old_var_num[pairnum] = old_sys.variable_number(varname);

      const Variable &variable = old_sys.variable(old_var_num[pairnum]);

      std::string systype = old_sys.system_type();

      System &new_sys = es2.add_system(systype, sysname);
      new_system[pairnum] = &new_sys;
      new_sys_num[pairnum] = new_sys.number();

      new_var_num[pairnum] =
        new_sys.add_variable(varname, variable.type(),
                             &variable.active_subdomains());
    }

  es2.init();

  // A future version of this app should copy variables for
  // non-solution vectors too.

  // Copy over any nodal degree of freedom coefficients

  MeshBase::const_node_iterator       old_nit     = mesh1.local_nodes_begin(),
                                      new_nit     = mesh2.local_nodes_begin();
  const MeshBase::const_node_iterator old_nit_end = mesh1.local_nodes_end();

  for (; old_nit != old_nit_end; ++old_nit, ++new_nit)
    {
      const Node* old_node = *old_nit;
      const Node* new_node = *new_nit;

      // Mesh::operator= hopefully preserved elem/node orderings...
      libmesh_assert (*old_node == *new_node);

      for (int argi = 4; argi < argc; argi += 2)
        {
          const unsigned int pairnum = (argi-4)/2;

          const System &old_sys = *old_system[pairnum];
          System &new_sys = *new_system[pairnum];

          const unsigned int n_comp =
            old_node->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
          libmesh_assert_equal_to(n_comp,
            new_node->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));

          for(unsigned int i=0; i<n_comp; i++)
            {
              const unsigned int
                old_index = old_node->dof_number
                  (old_sys_num[pairnum], old_var_num[pairnum], i),
                new_index = new_node->dof_number
                  (new_sys_num[pairnum], new_var_num[pairnum], i);
              new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
            }
        }
    }

  // Copy over any element degree of freedom coefficients

  MeshBase::const_element_iterator       old_eit     = mesh1.active_local_elements_begin(),
                                         new_eit     = mesh2.active_local_elements_begin();
  const MeshBase::const_element_iterator old_eit_end = mesh1.active_local_elements_end();

  for (; old_eit != old_eit_end; ++old_eit, ++new_eit)
    {
      const Elem* old_elem = *old_eit;
      const Elem* new_elem = *new_eit;

      // Mesh::operator= hopefully preserved elem/node orderings...
      libmesh_assert (*old_elem == *new_elem);

      for (int argi = 4; argi < argc; argi += 2)
        {
          const unsigned int pairnum = (argi-4)/2;

          const System &old_sys = *old_system[pairnum];
          System &new_sys = *new_system[pairnum];

          const unsigned int n_comp =
            old_elem->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
          libmesh_assert_equal_to(n_comp,
            new_elem->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));

          for(unsigned int i=0; i<n_comp; i++)
            {
              const unsigned int
                old_index = old_elem->dof_number
                  (old_sys_num[pairnum], old_var_num[pairnum], i),
                new_index = new_elem->dof_number
                  (new_sys_num[pairnum], new_var_num[pairnum], i);
              new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
            }
        }
    }

  es2.write(argv[3], EquationSystems::WRITE_DATA);

  return 0;
}
<commit_msg>dof_id_type fixes<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// Open the mesh and solution file given, create a new solution file,
// and copy all listed variables from the old solution to the new.

#include "libmesh/libmesh.h"

#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/numeric_vector.h"

unsigned int dim = 2; // This gets overridden by most mesh formats

int main(int argc, char** argv)
{
  using namespace libMesh;

  LibMeshInit init(argc, argv);

  Mesh mesh1(dim);
  EquationSystems es1(mesh1);

  std::cout << "Usage: " << argv[0]
            << " mesh oldsolution newsolution system1 variable1 [sys2 var2...]" << std::endl;

  // We should have one system name for each variable name, and those
  // get preceded by an even number of arguments.
  libmesh_assert (!(argc % 2));

  // We should have at least one system/variable pair following the
  // initial arguments
  libmesh_assert_greater_equal (argc, 6);

  mesh1.read(argv[1]);
  std::cout << "Loaded mesh " << argv[1] << std::endl;
  Mesh mesh2(mesh1);
  EquationSystems es2(mesh2);

  es1.read(argv[2],
           EquationSystems::READ_HEADER |
           EquationSystems::READ_DATA |
           EquationSystems::READ_ADDITIONAL_DATA |
           EquationSystems::READ_BASIC_ONLY);
  std::cout << "Loaded solution " << argv[2] << std::endl;

  std::vector<unsigned int> old_sys_num((argc-4)/2),
                            new_sys_num((argc-4)/2),
                            old_var_num((argc-4)/2),
                            new_var_num((argc-4)/2);

  std::vector<const System *> old_system((argc-4)/2);
  std::vector<System *> new_system((argc-4)/2);

  for (int argi = 4; argi < argc; argi += 2)
    {
      const char* sysname = argv[argi];
      const char* varname = argv[argi+1];

      const unsigned int pairnum = (argi-4)/2;

      libmesh_assert(es1.has_system(sysname));

      const System &old_sys = es1.get_system(sysname);
      old_system[pairnum] = &old_sys;
      old_sys_num[pairnum] = old_sys.number();

      libmesh_assert(old_sys.has_variable(varname));

      old_var_num[pairnum] = old_sys.variable_number(varname);

      const Variable &variable = old_sys.variable(old_var_num[pairnum]);

      std::string systype = old_sys.system_type();

      System &new_sys = es2.add_system(systype, sysname);
      new_system[pairnum] = &new_sys;
      new_sys_num[pairnum] = new_sys.number();

      new_var_num[pairnum] =
        new_sys.add_variable(varname, variable.type(),
                             &variable.active_subdomains());
    }

  es2.init();

  // A future version of this app should copy variables for
  // non-solution vectors too.

  // Copy over any nodal degree of freedom coefficients

  MeshBase::const_node_iterator       old_nit     = mesh1.local_nodes_begin(),
                                      new_nit     = mesh2.local_nodes_begin();
  const MeshBase::const_node_iterator old_nit_end = mesh1.local_nodes_end();

  for (; old_nit != old_nit_end; ++old_nit, ++new_nit)
    {
      const Node* old_node = *old_nit;
      const Node* new_node = *new_nit;

      // Mesh::operator= hopefully preserved elem/node orderings...
      libmesh_assert (*old_node == *new_node);

      for (int argi = 4; argi < argc; argi += 2)
        {
          const unsigned int pairnum = (argi-4)/2;

          const System &old_sys = *old_system[pairnum];
          System &new_sys = *new_system[pairnum];

          const unsigned int n_comp =
            old_node->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
          libmesh_assert_equal_to(n_comp,
            new_node->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));

          for(unsigned int i=0; i<n_comp; i++)
            {
              const dof_index_type
                old_index = old_node->dof_number
                  (old_sys_num[pairnum], old_var_num[pairnum], i),
                new_index = new_node->dof_number
                  (new_sys_num[pairnum], new_var_num[pairnum], i);
              new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
            }
        }
    }

  // Copy over any element degree of freedom coefficients

  MeshBase::const_element_iterator       old_eit     = mesh1.active_local_elements_begin(),
                                         new_eit     = mesh2.active_local_elements_begin();
  const MeshBase::const_element_iterator old_eit_end = mesh1.active_local_elements_end();

  for (; old_eit != old_eit_end; ++old_eit, ++new_eit)
    {
      const Elem* old_elem = *old_eit;
      const Elem* new_elem = *new_eit;

      // Mesh::operator= hopefully preserved elem/node orderings...
      libmesh_assert (*old_elem == *new_elem);

      for (int argi = 4; argi < argc; argi += 2)
        {
          const unsigned int pairnum = (argi-4)/2;

          const System &old_sys = *old_system[pairnum];
          System &new_sys = *new_system[pairnum];

          const unsigned int n_comp =
            old_elem->n_comp(old_sys_num[pairnum],old_var_num[pairnum]);
          libmesh_assert_equal_to(n_comp,
            new_elem->n_comp(new_sys_num[pairnum],new_var_num[pairnum]));

          for(unsigned int i=0; i<n_comp; i++)
            {
              const dof_index_type
                old_index = old_elem->dof_number
                  (old_sys_num[pairnum], old_var_num[pairnum], i),
                new_index = new_elem->dof_number
                  (new_sys_num[pairnum], new_var_num[pairnum], i);
              new_sys.solution->set(new_index,(*old_sys.solution)(old_index));
            }
        }
    }

  es2.write(argv[3], EquationSystems::WRITE_DATA);

  return 0;
}
<|endoftext|>


<commit_before>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2009 David Capello
// 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 the author 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 <Vaca/Vaca.h>
#include "../resource.h"

#include "md5.h"
#include "sha1.h"

using namespace Vaca;

//////////////////////////////////////////////////////////////////////
// MD5

static String MD5File(const String& fileName)
{
  FILE* stream = _wfopen(fileName.c_str(), L"rb");
  if (stream == NULL)
    return String(L"Error loading file");

  MD5_CTX md5;
  MD5Init(&md5);

  unsigned char buf[1024];
  size_t len;
  while ((len = fread(buf, 1, 1024, stream)))
    MD5Update(&md5, buf, len);

  fclose(stream);

  unsigned char digest[16];
  MD5Final(digest, &md5);

  // transform "digest" to String
  String res;
  for(int c=0; c<16; ++c)
    res += format_string(L"%02x", digest[c]);
  return res;
}

//////////////////////////////////////////////////////////////////////
// SHA1

static String SHA1File(const String &fileName)
{
  FILE* stream = _wfopen(fileName.c_str(), L"rb");
  if (stream == NULL)
    return String(L"Error loading file");

  SHA1Context sha;
  SHA1Reset(&sha);

  unsigned char buf[1024];
  size_t len;
  while ((len = fread(buf, 1, 1024, stream)))
    SHA1Input(&sha, buf, len);

  fclose(stream);

  uint8_t digest[20];
  SHA1Result(&sha, digest);

  // transform "digest" to String
  String res;
  for(int c=0; c<20; ++c)
    res += format_string(L"%02x", digest[c]);
  return res;
}

//////////////////////////////////////////////////////////////////////

class MainFrame : public Frame
{
  Label m_helpLabel;
  ListView m_filesList;
  TextEdit m_md5Edit;
  TextEdit m_shaEdit;
  LinkLabel m_md5Label;
  LinkLabel m_shaLabel;

public:

  MainFrame()
    : Frame(L"Hashing")
    , m_helpLabel(L"Drop files to the list", this)
    , m_filesList(this, ListView::Styles::Default +
			ListView::Styles::SingleSelection +
			Widget::Styles::AcceptFiles)
    , m_md5Edit(L"", this, TextEdit::Styles::Default +
			   TextEdit::Styles::ReadOnly)
    , m_shaEdit(L"", this, TextEdit::Styles::Default +
			   TextEdit::Styles::ReadOnly)
    , m_md5Label(L"http://www.faqs.org/rfcs/rfc1321.html",
		 L"RFC 1321 - The MD5 Message-Digest Algorithm", this)
    , m_shaLabel(L"http://www.faqs.org/rfcs/rfc3174.html",
		 L"RFC 3174 - US Secure Hash Algorithm 1 (SHA1)", this)
  {
    setLayout(Bix::parse(L"Y[%,f%,XY[%,fx%;%,fx%]]",
			 &m_helpLabel,
			 &m_filesList,
			 &m_md5Label, &m_md5Edit,
			 &m_shaLabel, &m_shaEdit));

    // setup report view
    m_filesList.setType(ListViewType::Report);
    m_filesList.addColumn(L"Filename");
    m_filesList.addColumn(L"MD5");
    m_filesList.addColumn(L"SHA1");

    // signals
    m_filesList.DropFiles.connect(&MainFrame::onDropFilesInFilesList, this);
    m_filesList.AfterSelect.connect(&MainFrame::onSelectFileInList, this);

    // get the small image list from the system and put it in the ListView
    m_filesList.setSmallImageList(System::getImageList(true));
  }

private:

  void onDropFilesInFilesList(DropFilesEvent& ev)
  {
    std::vector<String> files = ev.getFiles();

    // m_filesList.removeAllItems();

    // add items in the list
    for (std::vector<String>::iterator
	   it = files.begin(); it != files.end(); ++it) {
      // get the what image to use
      int imageIndex = System::getFileImageIndex((*it), true);

      // add the new item and hold its index
      int itemIndex = m_filesList.addItem(file_name(*it), imageIndex);

      // calculates the MD5 and SHA1 of the file
      m_filesList.setItemText(itemIndex, MD5File(*it), 1);
      m_filesList.setItemText(itemIndex, SHA1File(*it), 2);
    }

    // set preferred with for each column
    int n = m_filesList.getColumnCount();
    for (int i=0; i<n; ++i)
      m_filesList.setPreferredColumnWidth(i, true);
  }

  void onSelectFileInList(ListViewEvent& ev)
  {
    int itemIndex = ev.getItemIndex();
    if (itemIndex >= 0) {
      m_md5Edit.setText(m_filesList.getItemText(itemIndex, 1));
      m_shaEdit.setText(m_filesList.getItemText(itemIndex, 2));
    }
  }

};

//////////////////////////////////////////////////////////////////////

int VACA_MAIN()
{
  Application app;
  MainFrame frm;
  frm.setIcon(ResourceId(IDI_VACA));
  frm.setVisible(true);
  app.run();
  return 0;
}
<commit_msg>Fixed some compilation errors including std namespace for <cstdio><commit_after>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2009 David Capello
// 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 the author 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 <Vaca/Vaca.h>
#include "../resource.h"

#include "md5.h"
#include "sha1.h"

#include <cstdio>

using namespace std;
using namespace Vaca;

//////////////////////////////////////////////////////////////////////
// MD5

static String MD5File(const String& fileName)
{
  FILE* stream = _wfopen(fileName.c_str(), L"rb");
  if (stream == NULL)
    return String(L"Error loading file");

  MD5_CTX md5;
  MD5Init(&md5);

  unsigned char buf[1024];
  size_t len;
  while ((len = fread(buf, 1, 1024, stream)))
    MD5Update(&md5, buf, len);

  fclose(stream);

  unsigned char digest[16];
  MD5Final(digest, &md5);

  // transform "digest" to String
  String res;
  for(int c=0; c<16; ++c)
    res += format_string(L"%02x", digest[c]);
  return res;
}

//////////////////////////////////////////////////////////////////////
// SHA1

static String SHA1File(const String &fileName)
{
  FILE* stream = _wfopen(fileName.c_str(), L"rb");
  if (stream == NULL)
    return String(L"Error loading file");

  SHA1Context sha;
  SHA1Reset(&sha);

  unsigned char buf[1024];
  size_t len;
  while ((len = fread(buf, 1, 1024, stream)))
    SHA1Input(&sha, buf, len);

  fclose(stream);

  uint8_t digest[20];
  SHA1Result(&sha, digest);

  // transform "digest" to String
  String res;
  for(int c=0; c<20; ++c)
    res += format_string(L"%02x", digest[c]);
  return res;
}

//////////////////////////////////////////////////////////////////////

class MainFrame : public Frame
{
  Label m_helpLabel;
  ListView m_filesList;
  TextEdit m_md5Edit;
  TextEdit m_shaEdit;
  LinkLabel m_md5Label;
  LinkLabel m_shaLabel;

public:

  MainFrame()
    : Frame(L"Hashing")
    , m_helpLabel(L"Drop files to the list", this)
    , m_filesList(this, ListView::Styles::Default +
			ListView::Styles::SingleSelection +
			Widget::Styles::AcceptFiles)
    , m_md5Edit(L"", this, TextEdit::Styles::Default +
			   TextEdit::Styles::ReadOnly)
    , m_shaEdit(L"", this, TextEdit::Styles::Default +
			   TextEdit::Styles::ReadOnly)
    , m_md5Label(L"http://www.faqs.org/rfcs/rfc1321.html",
		 L"RFC 1321 - The MD5 Message-Digest Algorithm", this)
    , m_shaLabel(L"http://www.faqs.org/rfcs/rfc3174.html",
		 L"RFC 3174 - US Secure Hash Algorithm 1 (SHA1)", this)
  {
    setLayout(Bix::parse(L"Y[%,f%,XY[%,fx%;%,fx%]]",
			 &m_helpLabel,
			 &m_filesList,
			 &m_md5Label, &m_md5Edit,
			 &m_shaLabel, &m_shaEdit));

    // setup report view
    m_filesList.setType(ListViewType::Report);
    m_filesList.addColumn(L"Filename");
    m_filesList.addColumn(L"MD5");
    m_filesList.addColumn(L"SHA1");

    // signals
    m_filesList.DropFiles.connect(&MainFrame::onDropFilesInFilesList, this);
    m_filesList.AfterSelect.connect(&MainFrame::onSelectFileInList, this);

    // get the small image list from the system and put it in the ListView
    m_filesList.setSmallImageList(System::getImageList(true));
  }

private:

  void onDropFilesInFilesList(DropFilesEvent& ev)
  {
    vector<String> files = ev.getFiles();

    // Add items in the list
    for (vector<String>::iterator
	   it = files.begin(); it != files.end(); ++it) {
      // Get the what image to use
      int imageIndex = System::getFileImageIndex((*it), true);

      // add the new item and hold its index
      int itemIndex = m_filesList.addItem(file_name(*it), imageIndex);

      // calculates the MD5 and SHA1 of the file
      m_filesList.setItemText(itemIndex, MD5File(*it), 1);
      m_filesList.setItemText(itemIndex, SHA1File(*it), 2);
    }

    // set preferred with for each column
    int n = m_filesList.getColumnCount();
    for (int i=0; i<n; ++i)
      m_filesList.setPreferredColumnWidth(i, true);
  }

  void onSelectFileInList(ListViewEvent& ev)
  {
    int itemIndex = ev.getItemIndex();
    if (itemIndex >= 0) {
      m_md5Edit.setText(m_filesList.getItemText(itemIndex, 1));
      m_shaEdit.setText(m_filesList.getItemText(itemIndex, 2));
    }
  }

};

//////////////////////////////////////////////////////////////////////

int VACA_MAIN()
{
  Application app;
  MainFrame frm;
  frm.setIcon(ResourceId(IDI_VACA));
  frm.setVisible(true);
  app.run();
  return 0;
}
<|endoftext|>


<commit_before>/*******************************************************************************

Largest area rectangle histogram
================================

Ref - http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
    - http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/

--------------------------------------------------------------------------------

Problem
=======
Given a histogram find the area of the largest rectangle formed by it.

--------------------------------------------------------------------------------

Time Complexity
===============
O(n) - Each bar pushed to stack only once

--------------------------------------------------------------------------------

Output
======
Buy on day : 0   Sell on day: 3
Buy on day : 4   Sell on day: 6

*******************************************************************************/

#include <stdio.h>
#include <stack>

using namespace std;

int maxArea(int hist[], int n)  {
    stack<int> s;   // holds indexes of bars in increasing order of heights

    int max = 0, i = 0;

    while(i < n)    {

        // pushing current bar to stack if it exceeds stack top
        if(s.empty() || hist[i] >= hist[s.top()])
            s.push(i++);

        // finding area since current bar is less than the stack top
        // area of rectangle with stack top as the smallest height
        // right index -> i
        // left index -> element before s.top()
        else    {
            int top = s.top();
            s.pop();

            // if stack is empty then this is smallest member and left index is 0
            int area = hist[top] * (s.empty() ? i : i - s.top() - 1);

            if(area > max)
                max = area;
        }
    }

    // finding area for remaining smaller bars
    while(!s.empty())   {
        int top = s.top();
        s.pop();
        int area = hist[top] * (s.empty() ? i : i - s.top() - 1);

        if(area > max)
            max = area;
    }

    return max;
}

int main()  {
    int hist[] = {6, 2, 5, 4, 5, 1, 6};
    printf("Max area: %d\n", maxArea(hist, 7));
    return 0;
}
<commit_msg>:star2: Update Largest area of rectangle under histogram<commit_after>/*******************************************************************************

Largest area rectangle histogram
================================

Ref - http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
    - http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/

--------------------------------------------------------------------------------

Problem
=======
Given a histogram find the area of the largest rectangle formed by it.

--------------------------------------------------------------------------------

Time Complexity
===============
O(n) - Each bar pushed to stack only once

--------------------------------------------------------------------------------

Output
======
Max area: 12

*******************************************************************************/

#include <stdio.h>
#include <stack>

using namespace std;

int maxArea(int hist[], int n)  {
    stack<int> s;   // holds indexes of bars in increasing order of heights

    int max = 0, i = 0;

    while(i < n)    {

        // pushing current bar to stack if it exceeds stack top
        if(s.empty() || hist[i] >= hist[s.top()])
            s.push(i++);

        // finding area since current bar is less than the stack top
        // area of rectangle with stack top as the smallest height
        // right index -> i
        // left index -> element before s.top()
        else    {
            int top = s.top();
            s.pop();

            // if stack is empty then this is smallest member and left index is 0
            int area = hist[top] * (s.empty() ? i : i - s.top() - 1);

            if(area > max)
                max = area;
        }
    }

    // finding area for remaining smaller bars
    while(!s.empty())   {
        int top = s.top();
        s.pop();
        int area = hist[top] * (s.empty() ? i : i - s.top() - 1);

        if(area > max)
            max = area;
    }

    return max;
}

int main()  {
    int hist[] = {6, 2, 5, 4, 5, 1, 6};
    printf("Max area: %d\n", maxArea(hist, 7));
    return 0;
}
<|endoftext|>