<commit_before>//===-- SlotIndexes.cpp - Slot Indexes Pass  ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "slotindexes"

#include "llvm/CodeGen/SlotIndexes.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"

using namespace llvm;

char SlotIndexes::ID = 0;
INITIALIZE_PASS(SlotIndexes, "slotindexes",
                "Slot index numbering", false, false)

void SlotIndexes::getAnalysisUsage(AnalysisUsage &au) const {
  au.setPreservesAll();
  MachineFunctionPass::getAnalysisUsage(au);
}

void SlotIndexes::releaseMemory() {
  mi2iMap.clear();
  mbb2IdxMap.clear();
  idx2MBBMap.clear();
  clearList();
}

bool SlotIndexes::runOnMachineFunction(MachineFunction &fn) {

  // Compute numbering as follows:
  // Grab an iterator to the start of the index list.
  // Iterate over all MBBs, and within each MBB all MIs, keeping the MI
  // iterator in lock-step (though skipping it over indexes which have
  // null pointers in the instruction field).
  // At each iteration assert that the instruction pointed to in the index
  // is the same one pointed to by the MI iterator. This

  // FIXME: This can be simplified. The mi2iMap_, Idx2MBBMap, etc. should
  // only need to be set up once after the first numbering is computed.

  mf = &fn;
  initList();

  // Check that the list contains only the sentinal.
  assert(indexListHead->getNext() == 0 &&
         "Index list non-empty at initial numbering?");
  assert(idx2MBBMap.empty() &&
         "Index -> MBB mapping non-empty at initial numbering?");
  assert(mbb2IdxMap.empty() &&
         "MBB -> Index mapping non-empty at initial numbering?");
  assert(mi2iMap.empty() &&
         "MachineInstr -> Index mapping non-empty at initial numbering?");

  functionSize = 0;
  unsigned index = 0;

  push_back(createEntry(0, index));

  // Iterate over the function.
  for (MachineFunction::iterator mbbItr = mf->begin(), mbbEnd = mf->end();
       mbbItr != mbbEnd; ++mbbItr) {
    MachineBasicBlock *mbb = &*mbbItr;

    // Insert an index for the MBB start.
    SlotIndex blockStartIndex(back(), SlotIndex::LOAD);

    index += SlotIndex::NUM;

    for (MachineBasicBlock::iterator miItr = mbb->begin(), miEnd = mbb->end();
         miItr != miEnd; ++miItr) {
      MachineInstr *mi = miItr;
      if (mi->isDebugValue())
        continue;

      // Insert a store index for the instr.
      push_back(createEntry(mi, index));

      // Save this base index in the maps.
      mi2iMap.insert(
        std::make_pair(mi, SlotIndex(back(), SlotIndex::LOAD)));

      ++functionSize;

      unsigned Slots = mi->getDesc().getNumDefs();
      if (Slots == 0)
        Slots = 1;

      index += (Slots + 1) * SlotIndex::NUM;
    }

    // We insert two blank instructions between basic blocks.
    // One to represent live-out registers and one to represent live-ins.
    push_back(createEntry(0, index));
    index += SlotIndex::NUM;

    push_back(createEntry(0, index));

    SlotIndex blockEndIndex(back(), SlotIndex::LOAD);
    mbb2IdxMap.insert(
      std::make_pair(mbb, std::make_pair(blockStartIndex, blockEndIndex)));

    idx2MBBMap.push_back(IdxMBBPair(blockStartIndex, mbb));
  }

  // Sort the Idx2MBBMap
  std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());

  DEBUG(dump());

  // And we're done!
  return false;
}

void SlotIndexes::renumberIndexes() {

  // Renumber updates the index of every element of the index list.
  // If all instrs in the function have been allocated an index (which has been
  // placed in the index list in the order of instruction iteration) then the
  // resulting numbering will match what would have been generated by the
  // pass during the initial numbering of the function if the new instructions
  // had been present.
  DEBUG(dbgs() << "\n*** Renumbering SlotIndexes ***\n");

  unsigned index = 0;

  for (IndexListEntry *curEntry = front(); curEntry != getTail();
       curEntry = curEntry->getNext()) {
    curEntry->setIndex(index);
    index += 4*SlotIndex::NUM;
  }
}

void SlotIndexes::dump() const {
  for (const IndexListEntry *itr = front(); itr != getTail();
       itr = itr->getNext()) {
    dbgs() << itr->getIndex() << " ";

    if (itr->getInstr() != 0) {
      dbgs() << *itr->getInstr();
    } else {
      dbgs() << "\n";
    }
  }

  for (MBB2IdxMap::const_iterator itr = mbb2IdxMap.begin();
       itr != mbb2IdxMap.end(); ++itr) {
    dbgs() << "MBB " << itr->first->getNumber() << " (" << itr->first << ") - ["
           << itr->second.first << ", " << itr->second.second << "]\n";
  }
}

// Print a SlotIndex to a raw_ostream.
void SlotIndex::print(raw_ostream &os) const {
  if (isValid())
    os << entry().getIndex() << "LudS"[getSlot()];
  else
    os << "invalid";
}

// Dump a SlotIndex to stderr.
void SlotIndex::dump() const {
  print(dbgs());
  dbgs() << "\n";
}

<commit_msg>Add SlotIndex statistics.<commit_after>//===-- SlotIndexes.cpp - Slot Indexes Pass  ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "slotindexes"

#include "llvm/CodeGen/SlotIndexes.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"

using namespace llvm;

char SlotIndexes::ID = 0;
INITIALIZE_PASS(SlotIndexes, "slotindexes",
                "Slot index numbering", false, false)

STATISTIC(NumRenumPasses, "Number of slot index renumber passes");

void SlotIndexes::getAnalysisUsage(AnalysisUsage &au) const {
  au.setPreservesAll();
  MachineFunctionPass::getAnalysisUsage(au);
}

void SlotIndexes::releaseMemory() {
  mi2iMap.clear();
  mbb2IdxMap.clear();
  idx2MBBMap.clear();
  clearList();
}

bool SlotIndexes::runOnMachineFunction(MachineFunction &fn) {

  // Compute numbering as follows:
  // Grab an iterator to the start of the index list.
  // Iterate over all MBBs, and within each MBB all MIs, keeping the MI
  // iterator in lock-step (though skipping it over indexes which have
  // null pointers in the instruction field).
  // At each iteration assert that the instruction pointed to in the index
  // is the same one pointed to by the MI iterator. This

  // FIXME: This can be simplified. The mi2iMap_, Idx2MBBMap, etc. should
  // only need to be set up once after the first numbering is computed.

  mf = &fn;
  initList();

  // Check that the list contains only the sentinal.
  assert(indexListHead->getNext() == 0 &&
         "Index list non-empty at initial numbering?");
  assert(idx2MBBMap.empty() &&
         "Index -> MBB mapping non-empty at initial numbering?");
  assert(mbb2IdxMap.empty() &&
         "MBB -> Index mapping non-empty at initial numbering?");
  assert(mi2iMap.empty() &&
         "MachineInstr -> Index mapping non-empty at initial numbering?");

  functionSize = 0;
  unsigned index = 0;

  push_back(createEntry(0, index));

  // Iterate over the function.
  for (MachineFunction::iterator mbbItr = mf->begin(), mbbEnd = mf->end();
       mbbItr != mbbEnd; ++mbbItr) {
    MachineBasicBlock *mbb = &*mbbItr;

    // Insert an index for the MBB start.
    SlotIndex blockStartIndex(back(), SlotIndex::LOAD);

    index += SlotIndex::NUM;

    for (MachineBasicBlock::iterator miItr = mbb->begin(), miEnd = mbb->end();
         miItr != miEnd; ++miItr) {
      MachineInstr *mi = miItr;
      if (mi->isDebugValue())
        continue;

      // Insert a store index for the instr.
      push_back(createEntry(mi, index));

      // Save this base index in the maps.
      mi2iMap.insert(
        std::make_pair(mi, SlotIndex(back(), SlotIndex::LOAD)));

      ++functionSize;

      unsigned Slots = mi->getDesc().getNumDefs();
      if (Slots == 0)
        Slots = 1;

      index += (Slots + 1) * SlotIndex::NUM;
    }

    // We insert two blank instructions between basic blocks.
    // One to represent live-out registers and one to represent live-ins.
    push_back(createEntry(0, index));
    index += SlotIndex::NUM;

    push_back(createEntry(0, index));

    SlotIndex blockEndIndex(back(), SlotIndex::LOAD);
    mbb2IdxMap.insert(
      std::make_pair(mbb, std::make_pair(blockStartIndex, blockEndIndex)));

    idx2MBBMap.push_back(IdxMBBPair(blockStartIndex, mbb));
  }

  // Sort the Idx2MBBMap
  std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());

  DEBUG(dump());

  // And we're done!
  return false;
}

void SlotIndexes::renumberIndexes() {

  // Renumber updates the index of every element of the index list.
  // If all instrs in the function have been allocated an index (which has been
  // placed in the index list in the order of instruction iteration) then the
  // resulting numbering will match what would have been generated by the
  // pass during the initial numbering of the function if the new instructions
  // had been present.
  DEBUG(dbgs() << "\n*** Renumbering SlotIndexes ***\n");
  ++NumRenumPasses;

  unsigned index = 0;

  for (IndexListEntry *curEntry = front(); curEntry != getTail();
       curEntry = curEntry->getNext()) {
    curEntry->setIndex(index);
    index += 4*SlotIndex::NUM;
  }
}

void SlotIndexes::dump() const {
  for (const IndexListEntry *itr = front(); itr != getTail();
       itr = itr->getNext()) {
    dbgs() << itr->getIndex() << " ";

    if (itr->getInstr() != 0) {
      dbgs() << *itr->getInstr();
    } else {
      dbgs() << "\n";
    }
  }

  for (MBB2IdxMap::const_iterator itr = mbb2IdxMap.begin();
       itr != mbb2IdxMap.end(); ++itr) {
    dbgs() << "MBB " << itr->first->getNumber() << " (" << itr->first << ") - ["
           << itr->second.first << ", " << itr->second.second << "]\n";
  }
}

// Print a SlotIndex to a raw_ostream.
void SlotIndex::print(raw_ostream &os) const {
  if (isValid())
    os << entry().getIndex() << "LudS"[getSlot()];
  else
    os << "invalid";
}

// Dump a SlotIndex to stderr.
void SlotIndex::dump() const {
  print(dbgs());
  dbgs() << "\n";
}

<|endoftext|>


<commit_before>#include "eval.h"
#include "env.h"

namespace
{
using namespace mclisp;

ConsCell *Evcon(const ConsCell *clauses, ConsCell *env)
{
  // TODO Might want throw something more descriptive than TypeError.
  TYPECHECK(clauses, Listp);

  if (Null(clauses))
    return kNil;

  TYPECHECK(Car(clauses), Consp);

  if (*Eval(Caar(clauses), env))
    return Eval(Cadar(clauses), env);

  return Evcon(Cdr(clauses), env);
}

ConsCell* Evlis(ConsCell* lst, ConsCell* env)
{
  TYPECHECK(lst, Listp);

  if (Null(lst))
    return kNil;

  return Cons(Eval(Car(lst), env), Evlis(Cdr(lst), env));
}
} // namespace

namespace mclisp
{

ConsCell *Eval(const ConsCell *exp, ConsCell *env /* env::g_user_env */)
{
  if (Atom(exp))
    return env::Lookup(env, exp);

  if (Atom(Car(exp)))
  {
    if (EQ(Car(exp), QUOTE))
      return Cadr(exp);

    if (EQ(Car(exp), ATOM))
      return FromBool(Atom(Eval(Cadr(exp), env)));

    if (EQ(Car(exp), EQ))
      return FromBool(Eq(Eval(Cadr(exp), env), Eval(Caddr(exp), env)));

    if (EQ(Car(exp), COND))
      return Evcon(Cdr(exp), env);

    if (EQ(Car(exp), CAR))
      return Car(Eval(Cadr(exp), env));

    if (EQ(Car(exp), CDR))
      return Cdr(Eval(Cadr(exp), env));

    if (EQ(Car(exp), CONS))
      return Cons(Eval(Cadr(exp), env), Eval(Caddr(exp), env));

    if (EQ(Car(exp), DEFUN))
    {
      // TODO fix defun.
      //
      // This won't work if the defun isn't a toplevel form.
      ConsCell *fname = Cadr(exp);
      ConsCell *formals = Caddr(exp);
      ConsCell *body = Cdddr(exp);
      ConsCell *lambda = Append(List(BUILTIN(LAMBDA), formals), body);
      env::g_user_env = env::Extend(env::g_user_env, fname, lambda);
      return kNil;
    }

    return Eval(Cons(env::Lookup(env, Car(exp)), Cdr(exp)), env);
  }

  if (EQ(Caar(exp), LABEL))
    return Eval(Cons(Caddar(exp), Cdr(exp)),
                env::Extend(env, Cadar(exp), Car(exp)));

  if (EQ(Caar(exp), LAMBDA))
    return Eval(Caddar(exp),
                env::ExtendAll(env, Cadar(exp), Evlis(Cdr(exp), env)));

  return MakeSymbol("42");
}

} // namespace mclisp
<commit_msg>Add comment explaining defun brokeness.<commit_after>#include "eval.h"
#include "env.h"

namespace
{
using namespace mclisp;

ConsCell *Evcon(const ConsCell *clauses, ConsCell *env)
{
  // TODO Might want throw something more descriptive than TypeError.
  TYPECHECK(clauses, Listp);

  if (Null(clauses))
    return kNil;

  TYPECHECK(Car(clauses), Consp);

  if (*Eval(Caar(clauses), env))
    return Eval(Cadar(clauses), env);

  return Evcon(Cdr(clauses), env);
}

ConsCell* Evlis(ConsCell* lst, ConsCell* env)
{
  TYPECHECK(lst, Listp);

  if (Null(lst))
    return kNil;

  return Cons(Eval(Car(lst), env), Evlis(Cdr(lst), env));
}
} // namespace

namespace mclisp
{

ConsCell *Eval(const ConsCell *exp, ConsCell *env /* env::g_user_env */)
{
  if (Atom(exp))
    return env::Lookup(env, exp);

  if (Atom(Car(exp)))
  {
    if (EQ(Car(exp), QUOTE))
      return Cadr(exp);

    if (EQ(Car(exp), ATOM))
      return FromBool(Atom(Eval(Cadr(exp), env)));

    if (EQ(Car(exp), EQ))
      return FromBool(Eq(Eval(Cadr(exp), env), Eval(Caddr(exp), env)));

    if (EQ(Car(exp), COND))
      return Evcon(Cdr(exp), env);

    if (EQ(Car(exp), CAR))
      return Car(Eval(Cadr(exp), env));

    if (EQ(Car(exp), CDR))
      return Cdr(Eval(Cadr(exp), env));

    if (EQ(Car(exp), CONS))
      return Cons(Eval(Cadr(exp), env), Eval(Caddr(exp), env));

    if (EQ(Car(exp), DEFUN))
    {
      // TODO fix defun (maybe).
      //
      // This won't work as expected if the defun isn't a toplevel form. If a
      // non-toplevel defun is encountered, the binding it creates won't be
      // available until the next toplevel form executes, since we extend the
      // global user env, rather the current dynamic env. For example, the
      // following will cause an UnboundSymbol exception due to foo not being
      // bound in the body of the lambda:
      //
      // ((lambda (ignore) (foo))
      //  (defun foo () 'foo))
      //
      // Not that any sane person would write code like that... The defun
      // brokeness would be a bigger deal if mclisp supported some kind of
      // progn, implicit or otherwise, in which case one might reasonably expect
      // to be able to write internal defuns, like so:
      //
      // (defun foo (x)
      //    (defun helper (a) ...)
      //    (helper x))
      //
      // Even this is not idiomatic lisp, and it's unlikely you would want an
      // internal defun to both create a global binding *and* make the binding
      // immediately available in current env.  More likely, you want only the
      // latter, which can be accomplished in mclisp with a label expression.
      //
      // All the above whining aside, it wouldn't be hard to fix this by either
      // 1) restricting defuns to toplevel forms only, or 2) sticking the
      // binding on the symbol's plist, and falling back to plist lookup if
      // lookup in the dynamic env fails.
      ConsCell *fname = Cadr(exp);
      ConsCell *formals = Caddr(exp);
      ConsCell *body = Cdddr(exp);
      ConsCell *lambda = Append(List(BUILTIN(LAMBDA), formals), body);
      env::g_user_env = env::Extend(env::g_user_env, fname, lambda);
      return kNil;
    }

    return Eval(Cons(env::Lookup(env, Car(exp)), Cdr(exp)), env);
  }

  if (EQ(Caar(exp), LABEL))
    return Eval(Cons(Caddar(exp), Cdr(exp)),
                env::Extend(env, Cadar(exp), Car(exp)));

  if (EQ(Caar(exp), LAMBDA))
    return Eval(Caddar(exp),
                env::ExtendAll(env, Cadar(exp), Evlis(Cdr(exp), env)));

  return MakeSymbol("42");
}

} // namespace mclisp
<|endoftext|>


<commit_before>#include "SDL.h"
#include "oddlib/stream.hpp"
#include "oddlib/lvlarchive.hpp"
#include "oddlib/bits_factory.hpp"
#include "oddlib/ao_bits_pc.hpp"
#include "oddlib/ae_bits_pc.hpp"
#include "oddlib/psx_bits.hpp"
#include "oddlib/anim.hpp"
#include "filesystem.hpp"
#include "logger.hpp"
#include "stdthread.h"
#include "msvc_sdl_link.hpp"
#include "gamedata.hpp"

class DataTest
{
public:
    enum eDataType
    {
        eAoPc,
        eAoPsx,
        eAePc,
        eAePsx,
        eAoPcDemo,
        eAoPsxDemo,
        eAePcDemo,
        eAePsxDemo
    };

    DataTest(eDataType eType, const std::string& resourcePath, const std::vector<std::string>& lvls)
        : mType(eType)
    {
        mFs.Init();

        // Clear out the ones loaded from resource paths json
        mFs.ResourcePaths().ClearAllResourcePaths();

        mGameData.Init(mFs);

        // Add the only one we're interested in
        mFs.ResourcePaths().AddResourcePath(resourcePath, 1);

        for (const auto& lvl : lvls)
        {
            auto stream = mFs.ResourcePaths().Open(lvl);
            if (stream)
            {
                Oddlib::LvlArchive archive(std::move(stream));
                ReadAllAnimations(archive);
                //ReadFg1s(archive);
                //ReadFonts(archive);
                //ReadAllPaths(archive);
                //ReadAllCameras(archive);

                // TODO: Handle sounds/fmvs
            }
            else
            {
                LOG_WARNING("LVL not found: " << lvl);
            }
        }
    }

    void ForChunksOfType(Oddlib::LvlArchive& archive, Uint32 type, std::function<void(Oddlib::LvlArchive::FileChunk&)> cb)
    {
        for (auto i = 0u; i < archive.FileCount(); i++)
        {
            auto file = archive.FileByIndex(i);
            for (auto j = 0u; j < file->ChunkCount(); j++)
            {
                auto chunk = file->ChunkByIndex(j);
                if (chunk->Type() == type)
                {
                    // For AE PSX varients these files need parsing checking/fixing as they seem
                    // to be some slightly changed Anim format
                    bool bBroken =
                    (file->FileName() == "SLIG.BND" && chunk->Id() == 360) ||
                    (file->FileName() == "DUST.BAN" && chunk->Id() == 303) ||
                    (file->FileName() == "METAL.BAN" && chunk->Id() == 365) ||
                    (file->FileName() == "VAPOR.BAN" && chunk->Id() == 305) ||
                    (file->FileName() == "DEADFLR.BAN" && chunk->Id() == 349) ||
                    (file->FileName() == "DEBRIS00.BAN" && chunk->Id() == 1105) ||
                    (file->FileName() == "DOVBASIC.BAN" && chunk->Id() == 60) ||
                    (file->FileName() == "DRPROCK.BAN" && chunk->Id() == 357) ||
                    (file->FileName() == "DRPSPRK.BAN" && chunk->Id() == 357) ||
                    (file->FileName() == "EVILFART.BAN" && chunk->Id() == 6017) ||
                    (file->FileName() == "OMMFLARE.BAN" && chunk->Id() == 312) ||
                    (file->FileName() == "SHELL.BAN" && chunk->Id() == 360) ||
                    (file->FileName() == "LANDMINE.BAN" && chunk->Id() == 1036) ||
                    (file->FileName() == "SLURG.BAN" && chunk->Id() == 306) ||
                    (file->FileName() == "SQBSMK.BAN" && chunk->Id() == 354) ||
                    (file->FileName() == "STICK.BAN" && chunk->Id() == 358) ||
                    (file->FileName() == "TBOMB.BAN" && chunk->Id() == 1037) ||
                    (file->FileName() == "WELLLEAF.BAN" && chunk->Id() == 341) ||
                    (file->FileName() == "BOMB.BND" && chunk->Id() == 1005) ||
                    (file->FileName() == "MINE.BND" && chunk->Id() == 1036) ||
                    (file->FileName() == "UXB.BND" && chunk->Id() == 1037) ||
                    (file->FileName() == "EXPLODE.BND" && chunk->Id() == 1105) ||
                    (file->FileName() == "TRAPDOOR.BAN" && chunk->Id() == 1004) ||
                    (file->FileName() == "SLAM.BAN" && chunk->Id() == 2020) ||
                    (file->FileName() == "SLAMVLTS.BAN" && chunk->Id() == 2020) ||
                    (file->FileName() == "BOMB.BAN" && chunk->Id() == 1005);

                    if (bBroken && (mType != eAePsx && mType != eAePsxDemo))
                    {
                        bBroken = false;
                    }

                    if (!bBroken)
                    {
                        cb(*chunk);
                    }
                }
            }
        }
    }

    void ReadFg1s(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('F', 'G', '1', ' '), [&](Oddlib::LvlArchive::FileChunk&)
        {
            // TODO: FG1 parsing
        });
    }

    void ReadFonts(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('F', 'o', 'n', 't'), [&](Oddlib::LvlArchive::FileChunk&)
        {
            // TODO: Font parsing
        });
    }

    void ReadAllPaths(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('P', 'a', 't', 'h'), [&](Oddlib::LvlArchive::FileChunk&)
        {
            // TODO: Load the game data json for the required hard coded data to load the path
            /*
            Oddlib::Path path(*chunk.Stream(),
                entry->mCollisionDataOffset,
                entry->mObjectIndexTableOffset,
                entry->mObjectDataOffset,
                entry->mMapXSize,
                entry->mMapYSize);*/
        });
    }

    void ReadAllCameras(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('B', 'i', 't', 's'), [&](Oddlib::LvlArchive::FileChunk& chunk)
        {
            auto bits = Oddlib::MakeBits(*chunk.Stream());
            Oddlib::IBits* ptr = nullptr;
            switch (mType)
            {
            case eAoPc:
                ptr = dynamic_cast<Oddlib::AoBitsPc*>(bits.get());
                break;

            case eAePc:
                ptr = dynamic_cast<Oddlib::AeBitsPc*>(bits.get());
                break;

            case eAePsxDemo:
            case eAePsx:
            {
                auto tmp = dynamic_cast<Oddlib::PsxBits*>(bits.get());
                if (tmp && tmp->IncludeLength())
                {
                    ptr = tmp;
                }
            }
                break;

            case eAoPsxDemo:
            case eAoPsx:
            {
                auto tmp = dynamic_cast<Oddlib::PsxBits*>(bits.get());
                if (tmp && !tmp->IncludeLength())
                {
                    ptr = tmp;
                }
            }
                break;

            case eAoPcDemo:
                ptr = dynamic_cast<Oddlib::AoBitsPc*>(bits.get());
                break;

            case eAePcDemo:
                ptr = dynamic_cast<Oddlib::AoBitsPc*>(bits.get());
                if (!ptr)
                {
                    // Very strange, AE PC demo contains "half" cameras of random old PSX
                    // cameras, even half of the anti piracy screen is in here
                    auto tmp = dynamic_cast<Oddlib::PsxBits*>(bits.get());
                    if (tmp && tmp->IncludeLength())
                    {
                        ptr = tmp;
                    }
                }
                break;

            default:
                abort();
            }

            if (!ptr)
            {
                LOG_ERROR("Wrong camera type constructed");
                abort();
            }
            else
            {
                ptr->Save();
            }

        });
    }

    void ReadAllAnimations(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('A', 'n', 'i', 'm'), [&](Oddlib::LvlArchive::FileChunk& chunk)
        {
            Oddlib::AnimSerializer anim(*chunk.Stream());

        });
    }

private:
    eDataType mType;
    GameData mGameData;
    FileSystem mFs;
};

int main(int /*argc*/, char** /*argv*/)
{
    // TODO: Set path/type via command line and setup automated test with valgrind enabled

    const std::vector<std::string> aeLvls =
    {
        "mi.lvl",
        "ba.lvl",
        "bm.lvl",
        "br.lvl",
        "bw.lvl",
        "cr.lvl",
        "fd.lvl",
        "ne.lvl",
        "pv.lvl",
        "st.lvl",
        "sv.lvl"
    };
    DataTest aePsxCd1(DataTest::eAePsx, "C:\\Users\\paul\\Desktop\\alive\\all_data\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin", aeLvls);
    DataTest aePsxCd2(DataTest::eAePsx, "C:\\Users\\paul\\Desktop\\alive\\all_data\\Oddworld - Abe's Exoddus (E) (Disc 2) [SLES-11480].bin", aeLvls);
    DataTest aePc(DataTest::eAePc, "C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Oddworld Abes Exoddus", aeLvls);

    // AO PC/PSX
    const std::vector<std::string> aoLvls =
    {
        "s1.lvl",
        "r6.lvl",
        "r2.lvl",
        "r1.lvl",
        "l1.lvl",
        "f4.lvl",
        "f2.lvl",
        "f1.lvl",
        "e2.lvl",
        "e1.lvl",
        "d7.lvl",
        "d2.lvl",
        "c1.lvl"
    };
    DataTest aoPc(DataTest::eAoPc, "C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Oddworld Abes Oddysee", aoLvls);
    DataTest aoPsx(DataTest::eAoPsx, "C:\\Users\\paul\\Desktop\\alive\\all_data\\Oddworld - Abe's Oddysee (E) [SLES-00664].bin", aoLvls);

    const std::vector<std::string> aoDemoLvls =
    {
        "c1.lvl",
        "r1.lvl",
        "s1.lvl"
    };
    DataTest aoDemoPc(DataTest::eAoPcDemo, "C:\\Users\\paul\\Desktop\\alive\\all_data\\abeodd", aoDemoLvls);

    const std::vector<std::string> aeDemoLvls =
    {
        "cr.lvl",
        "mi.lvl",
        "st.lvl"
    };
    DataTest aeDemoPc(DataTest::eAePcDemo, "C:\\Users\\paul\\Desktop\\alive\\all_data\\exoddemo", aeDemoLvls);

    const std::vector<std::string> aoDemoPsxLvls =
    {
        "ABESODSE\\C1.LVL",
        "ABESODSE\\E1.LVL",
        "ABESODSE\\R1.LVL",
        "ABESODSE\\S1.LVL"
    };

    DataTest aoDemoPsx(DataTest::eAoPsxDemo, "C:\\Users\\paul\\Desktop\\alive\\all_data\\Oddworld - Abe's Oddysee (Demo) (E) [SLED-00725].bin", aoDemoPsxLvls);

    const std::vector<std::string> aeDemoPsxLvls =
    {
        "ABE2\\CR.LVL",
        "ABE2\\MI.LVL",
        "ABE2\\ST.LVL"
    };

    DataTest aeDemoPsx(DataTest::eAePsxDemo, "C:\\Users\\paul\\Desktop\\alive\\all_data\\Euro Demo 38 (E) (Track 1) [SCED-01148].bin", aeDemoPsxLvls);

    return 0;
}
<commit_msg>refactor data test init<commit_after>#include "SDL.h"
#include "oddlib/stream.hpp"
#include "oddlib/lvlarchive.hpp"
#include "oddlib/bits_factory.hpp"
#include "oddlib/ao_bits_pc.hpp"
#include "oddlib/ae_bits_pc.hpp"
#include "oddlib/psx_bits.hpp"
#include "oddlib/anim.hpp"
#include "filesystem.hpp"
#include "logger.hpp"
#include "stdthread.h"
#include "msvc_sdl_link.hpp"
#include "gamedata.hpp"

class DataTest
{
public:
    enum eDataType
    {
        eAoPc,
        eAoPcDemo,
        eAoPsx,
        eAoPsxDemo,
        eAePc,
        eAePcDemo,
        eAePsx,
        eAePsxDemo
    };

    DataTest(eDataType eType, const std::string& resourcePath, const std::vector<std::string>& lvls)
        : mType(eType)
    {
        mFs.Init();

        // Clear out the ones loaded from resource paths json
        mFs.ResourcePaths().ClearAllResourcePaths();

        mGameData.Init(mFs);

        // Add the only one we're interested in
        mFs.ResourcePaths().AddResourcePath(resourcePath, 1);

        for (const auto& lvl : lvls)
        {
            auto stream = mFs.ResourcePaths().Open(lvl);
            if (stream)
            {
                Oddlib::LvlArchive archive(std::move(stream));
                ReadAllAnimations(archive);
                //ReadFg1s(archive);
                //ReadFonts(archive);
                //ReadAllPaths(archive);
                //ReadAllCameras(archive);

                // TODO: Handle sounds/fmvs
            }
            else
            {
                LOG_WARNING("LVL not found: " << lvl);
            }
        }
    }

    void ForChunksOfType(Oddlib::LvlArchive& archive, Uint32 type, std::function<void(Oddlib::LvlArchive::FileChunk&)> cb)
    {
        for (auto i = 0u; i < archive.FileCount(); i++)
        {
            auto file = archive.FileByIndex(i);
            for (auto j = 0u; j < file->ChunkCount(); j++)
            {
                auto chunk = file->ChunkByIndex(j);
                if (chunk->Type() == type)
                {
                    // For AE PSX varients these files need parsing checking/fixing as they seem
                    // to be some slightly changed Anim format
                    bool bBroken =
                    (file->FileName() == "SLIG.BND" && chunk->Id() == 360) ||
                    (file->FileName() == "DUST.BAN" && chunk->Id() == 303) ||
                    (file->FileName() == "METAL.BAN" && chunk->Id() == 365) ||
                    (file->FileName() == "VAPOR.BAN" && chunk->Id() == 305) ||
                    (file->FileName() == "DEADFLR.BAN" && chunk->Id() == 349) ||
                    (file->FileName() == "DEBRIS00.BAN" && chunk->Id() == 1105) ||
                    (file->FileName() == "DOVBASIC.BAN" && chunk->Id() == 60) ||
                    (file->FileName() == "DRPROCK.BAN" && chunk->Id() == 357) ||
                    (file->FileName() == "DRPSPRK.BAN" && chunk->Id() == 357) ||
                    (file->FileName() == "EVILFART.BAN" && chunk->Id() == 6017) ||
                    (file->FileName() == "OMMFLARE.BAN" && chunk->Id() == 312) ||
                    (file->FileName() == "SHELL.BAN" && chunk->Id() == 360) ||
                    (file->FileName() == "LANDMINE.BAN" && chunk->Id() == 1036) ||
                    (file->FileName() == "SLURG.BAN" && chunk->Id() == 306) ||
                    (file->FileName() == "SQBSMK.BAN" && chunk->Id() == 354) ||
                    (file->FileName() == "STICK.BAN" && chunk->Id() == 358) ||
                    (file->FileName() == "TBOMB.BAN" && chunk->Id() == 1037) ||
                    (file->FileName() == "WELLLEAF.BAN" && chunk->Id() == 341) ||
                    (file->FileName() == "BOMB.BND" && chunk->Id() == 1005) ||
                    (file->FileName() == "MINE.BND" && chunk->Id() == 1036) ||
                    (file->FileName() == "UXB.BND" && chunk->Id() == 1037) ||
                    (file->FileName() == "EXPLODE.BND" && chunk->Id() == 1105) ||
                    (file->FileName() == "TRAPDOOR.BAN" && chunk->Id() == 1004) ||
                    (file->FileName() == "SLAM.BAN" && chunk->Id() == 2020) ||
                    (file->FileName() == "SLAMVLTS.BAN" && chunk->Id() == 2020) ||
                    (file->FileName() == "BOMB.BAN" && chunk->Id() == 1005);

                    if (bBroken && (mType != eAePsx && mType != eAePsxDemo))
                    {
                        bBroken = false;
                    }

                    if (!bBroken)
                    {
                        cb(*chunk);
                    }
                }
            }
        }
    }

    void ReadFg1s(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('F', 'G', '1', ' '), [&](Oddlib::LvlArchive::FileChunk&)
        {
            // TODO: FG1 parsing
        });
    }

    void ReadFonts(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('F', 'o', 'n', 't'), [&](Oddlib::LvlArchive::FileChunk&)
        {
            // TODO: Font parsing
        });
    }

    void ReadAllPaths(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('P', 'a', 't', 'h'), [&](Oddlib::LvlArchive::FileChunk&)
        {
            // TODO: Load the game data json for the required hard coded data to load the path
            /*
            Oddlib::Path path(*chunk.Stream(),
                entry->mCollisionDataOffset,
                entry->mObjectIndexTableOffset,
                entry->mObjectDataOffset,
                entry->mMapXSize,
                entry->mMapYSize);*/
        });
    }

    void ReadAllCameras(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('B', 'i', 't', 's'), [&](Oddlib::LvlArchive::FileChunk& chunk)
        {
            auto bits = Oddlib::MakeBits(*chunk.Stream());
            Oddlib::IBits* ptr = nullptr;
            switch (mType)
            {
            case eAoPc:
                ptr = dynamic_cast<Oddlib::AoBitsPc*>(bits.get());
                break;

            case eAePc:
                ptr = dynamic_cast<Oddlib::AeBitsPc*>(bits.get());
                break;

            case eAePsxDemo:
            case eAePsx:
            {
                auto tmp = dynamic_cast<Oddlib::PsxBits*>(bits.get());
                if (tmp && tmp->IncludeLength())
                {
                    ptr = tmp;
                }
            }
                break;

            case eAoPsxDemo:
            case eAoPsx:
            {
                auto tmp = dynamic_cast<Oddlib::PsxBits*>(bits.get());
                if (tmp && !tmp->IncludeLength())
                {
                    ptr = tmp;
                }
            }
                break;

            case eAoPcDemo:
                ptr = dynamic_cast<Oddlib::AoBitsPc*>(bits.get());
                break;

            case eAePcDemo:
                ptr = dynamic_cast<Oddlib::AoBitsPc*>(bits.get());
                if (!ptr)
                {
                    // Very strange, AE PC demo contains "half" cameras of random old PSX
                    // cameras, even half of the anti piracy screen is in here
                    auto tmp = dynamic_cast<Oddlib::PsxBits*>(bits.get());
                    if (tmp && tmp->IncludeLength())
                    {
                        ptr = tmp;
                    }
                }
                break;

            default:
                abort();
            }

            if (!ptr)
            {
                LOG_ERROR("Wrong camera type constructed");
                abort();
            }
            else
            {
                ptr->Save();
            }

        });
    }

    void ReadAllAnimations(Oddlib::LvlArchive& archive)
    {
        ForChunksOfType(archive, Oddlib::MakeType('A', 'n', 'i', 'm'), [&](Oddlib::LvlArchive::FileChunk& chunk)
        {
            Oddlib::AnimSerializer anim(*chunk.Stream());

        });
    }

private:
    eDataType mType;
    GameData mGameData;
    FileSystem mFs;
};

int main(int /*argc*/, char** /*argv*/)
{
    const std::vector<std::string> aoLvls =
    {
        "s1.lvl",
        "r6.lvl",
        "r2.lvl",
        "r1.lvl",
        "l1.lvl",
        "f4.lvl",
        "f2.lvl",
        "f1.lvl",
        "e2.lvl",
        "e1.lvl",
        "d7.lvl",
        "d2.lvl",
        "c1.lvl"
    };

    const std::vector<std::string> aoDemoLvls =
    {
        "c1.lvl",
        "r1.lvl",
        "s1.lvl"
    };

    const std::vector<std::string> aoDemoPsxLvls =
    {
        "ABESODSE\\C1.LVL",
        "ABESODSE\\E1.LVL",
        "ABESODSE\\R1.LVL",
        "ABESODSE\\S1.LVL"
    };

    const std::vector<std::string> aeLvls =
    {
        "mi.lvl",
        "ba.lvl",
        "bm.lvl",
        "br.lvl",
        "bw.lvl",
        "cr.lvl",
        "fd.lvl",
        "ne.lvl",
        "pv.lvl",
        "st.lvl",
        "sv.lvl"
    };

    const std::vector<std::string> aeDemoLvls =
    {
        "cr.lvl",
        "mi.lvl",
        "st.lvl"
    };

    const std::vector<std::string> aeDemoPsxLvls =
    {
        "ABE2\\CR.LVL",
        "ABE2\\MI.LVL",
        "ABE2\\ST.LVL"
    };

    const std::map<DataTest::eDataType, const std::vector<std::string>*> DataTypeLvlMap =
    {
        { DataTest::eAoPc, &aoLvls },
        { DataTest::eAoPsx, &aoLvls },
        { DataTest::eAePc, &aeLvls },
        { DataTest::eAePsx, &aeLvls },
        { DataTest::eAoPcDemo, &aoDemoLvls },
        { DataTest::eAoPsxDemo, &aoDemoPsxLvls },
        { DataTest::eAePcDemo, &aeDemoLvls},
        { DataTest::eAePsxDemo, &aeDemoPsxLvls }
    };

    const std::map<DataTest::eDataType, std::string> datas =
    {

        { DataTest::eAePc,      "C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Oddworld Abes Exoddus" },
        { DataTest::eAePcDemo,  "C:\\Users\\paul\\Desktop\\alive\\all_data\\exoddemo" },
        { DataTest::eAePsx,     "C:\\Users\\paul\\Desktop\\alive\\all_data\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin" },
        { DataTest::eAePsx,     "C:\\Users\\paul\\Desktop\\alive\\all_data\\Oddworld - Abe's Exoddus (E) (Disc 2) [SLES-11480].bin" },
        { DataTest::eAePsxDemo, "C:\\Users\\paul\\Desktop\\alive\\all_data\\Euro Demo 38 (E) (Track 1) [SCED-01148].bin" },
        { DataTest::eAoPc,      "C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Oddworld Abes Oddysee" },
        { DataTest::eAoPcDemo,  "C:\\Users\\paul\\Desktop\\alive\\all_data\\abeodd" },
        { DataTest::eAoPsx,     "C:\\Users\\paul\\Desktop\\alive\\all_data\\Oddworld - Abe's Oddysee (E) [SLES-00664].bin" },
        { DataTest::eAoPsxDemo, "C:\\Users\\paul\\Desktop\\alive\\all_data\\Oddworld - Abe's Oddysee (Demo) (E) [SLED-00725].bin" },
    };

    for (const auto& data : datas)
    {
        const auto it = DataTypeLvlMap.find(data.first);
        if (it == std::end(DataTypeLvlMap))
        {
            // Defined struct is wrong
            abort();
        }
        DataTest dataDecoder(data.first, data.second, *it->second);
    }

    return 0;
}
<|endoftext|>


<commit_before>/*     Copyright 2019 Diligent Graphics LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  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 OF ANY PROPRIETARY RIGHTS.
 *
 *  In no event and under no legal theory, whether in tort (including negligence),
 *  contract, or otherwise, unless required by applicable law (such as deliberate
 *  and grossly negligent acts) or agreed to in writing, shall any Contributor be
 *  liable for any damages, including any direct, indirect, special, incidental,
 *  or consequential damages of any character arising as a result of this License or
 *  out of the use or inability to use the software (including but not limited to damages
 *  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
 *  all other commercial damages or losses), even if such Contributor has been advised
 *  of the possibility of such damages.
 */

#include "NuklearDemo.h"

#include "../../../ThirdParty/nuklear/nuklear.h"

#ifndef NOMINMAX
#   define NOMINMAX
#endif
#include <Windows.h>

#include "NkInputWin32.h"

namespace Diligent
{

bool NuklearDemo::HandleNativeMessage(const void* pNativeMsgData)
{
    struct WindowsMessageData
    {
        HWND hWnd;
        UINT message;
        WPARAM wParam;
        LPARAM lParam;
    }const* pWin32Msg  = reinterpret_cast<const WindowsMessageData*>(pNativeMsgData);

    //nk_input_begin(m_pNkCtx); // TODO: needs to go before msg loop
    return nk_diligent_handle_win32_event(m_pNkCtx, pWin32Msg->hWnd, pWin32Msg->message, pWin32Msg->wParam, pWin32Msg->lParam) != 0;
    //nk_input_end(m_pNkCtx);  // TODO: needs to go after msg loop
}

}
<commit_msg>Nuklear impl: minor updates<commit_after>/*     Copyright 2019 Diligent Graphics LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  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 OF ANY PROPRIETARY RIGHTS.
 *
 *  In no event and under no legal theory, whether in tort (including negligence),
 *  contract, or otherwise, unless required by applicable law (such as deliberate
 *  and grossly negligent acts) or agreed to in writing, shall any Contributor be
 *  liable for any damages, including any direct, indirect, special, incidental,
 *  or consequential damages of any character arising as a result of this License or
 *  out of the use or inability to use the software (including but not limited to damages
 *  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
 *  all other commercial damages or losses), even if such Contributor has been advised
 *  of the possibility of such damages.
 */

#include "NuklearDemo.h"

#include "../../../ThirdParty/nuklear/nuklear.h"

#ifndef NOMINMAX
#   define NOMINMAX
#endif
#include <Windows.h>

#include "NkInputWin32.h"

namespace Diligent
{

bool NuklearDemo::HandleNativeMessage(const void* pNativeMsgData)
{
    struct WindowsMessageData
    {
        HWND hWnd;
        UINT message;
        WPARAM wParam;
        LPARAM lParam;
    }const* pWin32Msg  = reinterpret_cast<const WindowsMessageData*>(pNativeMsgData);

    return nk_diligent_handle_win32_event(m_pNkCtx, pWin32Msg->hWnd, pWin32Msg->message, pWin32Msg->wParam, pWin32Msg->lParam) != 0;
}

}
<|endoftext|>


<commit_before>
#include "Atm_fan.hpp"

/* Add optional parameters for the state machine to begin()
 * Add extra initialization code
 */

Atm_fan& Atm_fan::begin() {
  // clang-format off
  const static state_t state_table[] PROGMEM = {
    /*          ON_ENTER    ON_LOOP  ON_EXIT  EVT_INPUT  ELSE */
    /*  IDLE */       -1, ATM_SLEEP,      -1,      SEND,   -1,
    /*  SEND */ ENT_SEND,        -1,      -1,        -1, IDLE,
  };
  // clang-format on
  Machine::begin( state_table, ELSE );
  return *this;
}

/* Add C++ code for each internally handled event (input)
 * The code must return 1 to trigger the event
 */

int Atm_fan::event( int id ) {
  switch ( id ) {
    case EVT_INPUT:
      push( connectors, ON_INPUT, 0, 1, 1 );
      return 0;
  }
  return 0;
}

/* Add C++ code for each action
 * This generates the 'output' for the state machine
 */

void Atm_fan::action( int id ) {
  switch ( id ) {
    case ENT_SEND:
      return;
  }
}

/* Optionally override the default trigger() method
 * Control how your machine processes triggers
 */

Atm_fan& Atm_fan::trigger( int event ) {
  Machine::trigger( event );
  return *this;
}

/* Optionally override the default state() method
 * Control what the machine returns when another process requests its state
 */

int Atm_fan::state( void ) {
  return Machine::state();
}

/* Nothing customizable below this line
 ************************************************************************************************
*/

/* onInput() push connector variants ( slots 4, autostore 1, broadcast 1 )
 *
 * Usage in action() handler: push( connectors, ON_INPUT, -1, v, up );
 */

Atm_fan& Atm_fan::onInput( Machine& machine, int event ) {
  onPush( connectors, ON_INPUT, -1, 4, 0, 1, machine, event );
  return *this;
}

Atm_fan& Atm_fan::onInput( atm_cb_push_t callback, int idx ) {
  onPush( connectors, ON_INPUT, -1, 4, 0, 1, callback, idx );
  return *this;
}

/* State trace method
 * Sets the symbol table and the default logging method for serial monitoring
 */

Atm_fan& Atm_fan::trace( Stream & stream ) {
  Machine::setTrace( &stream, atm_serial_debug::trace,
    "FAN\0EVT_INPUT\0ELSE\0IDLE\0SEND" );
  return *this;
}

<commit_msg>Fixed comment<commit_after>
#include "Atm_fan.hpp"

/* Add optional parameters for the state machine to begin()
 * Add extra initialization code
 */

Atm_fan& Atm_fan::begin() {
  // clang-format off
  const static state_t state_table[] PROGMEM = {
    /*          ON_ENTER    ON_LOOP  ON_EXIT  EVT_INPUT  ELSE */
    /*  IDLE */       -1, ATM_SLEEP,      -1,      SEND,   -1,
    /*  SEND */ ENT_SEND,        -1,      -1,        -1, IDLE,
  };
  // clang-format on
  Machine::begin( state_table, ELSE );
  return *this;
}

/* Add C++ code for each internally handled event (input)
 * The code must return 1 to trigger the event
 */

int Atm_fan::event( int id ) {
  switch ( id ) {
    case EVT_INPUT:
      push( connectors, ON_INPUT, 0, 1, 1 );
      return 0;
  }
  return 0;
}

/* Add C++ code for each action
 * This generates the 'output' for the state machine
 */

void Atm_fan::action( int id ) {
  switch ( id ) {
    case ENT_SEND:
      return;
  }
}

/* Optionally override the default trigger() method
 * Control how your machine processes triggers
 */

Atm_fan& Atm_fan::trigger( int event ) {
  Machine::trigger( event );
  return *this;
}

/* Optionally override the default state() method
 * Control what the machine returns when another process requests its state
 */

int Atm_fan::state( void ) {
  return Machine::state();
}

/* Nothing customizable below this line
 ************************************************************************************************
*/

/* onInput() push connector variants ( slots 4, autostore 1, broadcast 1 )
 *
 * Usage in action() handler: push( connectors, ON_INPUT, 0, v, up );
 */

Atm_fan& Atm_fan::onInput( Machine& machine, int event ) {
  onPush( connectors, ON_INPUT, -1, 4, 0, 1, machine, event );
  return *this;
}

Atm_fan& Atm_fan::onInput( atm_cb_push_t callback, int idx ) {
  onPush( connectors, ON_INPUT, -1, 4, 0, 1, callback, idx );
  return *this;
}

/* State trace method
 * Sets the symbol table and the default logging method for serial monitoring
 */

Atm_fan& Atm_fan::trace( Stream & stream ) {
  Machine::setTrace( &stream, atm_serial_debug::trace,
    "FAN\0EVT_INPUT\0ELSE\0IDLE\0SEND" );
  return *this;
}

<|endoftext|>


<commit_before>#include <QtTest/QtTest>
#include <QProcess>
#include <QScreen>
#include <QPixmap>

#include "../cutehmi.dirs.hpp"

namespace cutehmi {
namespace daemon {

class test_cutehmi_view:
	public QObject
{
		Q_OBJECT

	private slots:
		void initTestCase();

		void helpOption();

		void versionOption();

		void screenshot();

	private:
		QString m_installDir;
		QString m_programPath;
		int m_windowDecorationsWidth;
		int m_windowDecorationsHeight;
};

void test_cutehmi_view::initTestCase()
{
	m_installDir = qEnvironmentVariable("CUTEHMI_INSTALL_DIR");
	QVERIFY(!m_installDir.isEmpty());

	QString toolsInstallSubdir = CUTEHMI_DIRS_TOOLS_INSTALL_SUBDIR;
	m_programPath = m_installDir;
	if (!toolsInstallSubdir.isEmpty())
		m_programPath += "/" + toolsInstallSubdir;
	m_programPath +=  "/cutehmi.view.2";
#ifndef CUTEHMI_NDEBUG
	m_programPath += ".debug";
#endif

	// Using helper window to calculate size of window decorations.
	QWindow helperWindow;
	helperWindow.show();
	m_windowDecorationsWidth = helperWindow.frameGeometry().width() - helperWindow.geometry().width();
	m_windowDecorationsHeight = helperWindow.frameGeometry().height() - helperWindow.geometry().height();
}

void test_cutehmi_view::helpOption()
{
	QList<QStringList> argumentsList;
	argumentsList << QStringList({"--help"})
			<< QStringList({"--h"});

	for (auto arguments : argumentsList) {
		QProcess process;
		process.start(m_programPath, arguments);
		process.waitForFinished(1000);
		QCOMPARE(process.error(), QProcess::UnknownError);
		QVERIFY(!process.readAllStandardError().contains("Unknown option"));
		QVERIFY(!process.readAllStandardOutput().isEmpty());
		QCOMPARE(process.exitStatus(), QProcess::NormalExit);
		QCOMPARE(process.exitCode(), EXIT_SUCCESS);
	}
}

void test_cutehmi_view::versionOption()
{
	QList<QStringList> argumentsList;
	argumentsList << QStringList({"--version"})
			<< QStringList({"--v"});

	for (auto arguments : argumentsList) {
		QProcess process;
		process.start(m_programPath, arguments);
		process.waitForFinished(1000);
		QCOMPARE(process.error(), QProcess::UnknownError);
		QVERIFY(!process.readAllStandardError().contains("Unknown option"));
		QVERIFY(!process.readAllStandardOutput().isEmpty());
		QCOMPARE(process.exitStatus(), QProcess::NormalExit);
		QCOMPARE(process.exitCode(), EXIT_SUCCESS);
	}
}

void test_cutehmi_view::screenshot()
{
	int width = 800;
	int height = 600;

	QStringList arguments;
	QString windowgeometryArg = QString::number(width) + "x" + QString::number(height) + "+0+0";
	arguments << "-qwindowgeometry" << windowgeometryArg << "--lang" << "en_EN";

	QString screenshotPath = m_installDir;
	QString artifactsInstallSubdir = qEnvironmentVariable("CUTEHMI_ARTIFACTS_INSTALL_SUBDIR");
	if (!artifactsInstallSubdir.isEmpty())
		screenshotPath += "/" + artifactsInstallSubdir;
	screenshotPath += "/screenshots/" CUTEHMI_DIRS_PROJECT_RELATIVE_PATH "/screenshot.png";
	const char * screenshotFormat = "PNG";

	QProcess process;
	process.start(m_programPath, arguments);
	process.waitForFinished(1500);	// This gives some time for the GUI to show up.

	QScreen * screen = QGuiApplication::primaryScreen();
	if (screen) {
		QPixmap screenshot = screen->grabWindow(0, 0, 0, width + m_windowDecorationsWidth, height + m_windowDecorationsHeight);
		QVERIFY(QDir().mkpath(QFileInfo(screenshotPath).dir().path()));
		QVERIFY(screenshot.save(screenshotPath, screenshotFormat));
	}

	process.terminate();
	process.waitForFinished();
}

}
}

QTEST_MAIN(cutehmi::daemon::test_cutehmi_view)
#include "test_cutehmi_view.moc"

//(c)C: Copyright © 2020, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI 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 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI 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.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI.  If not, see <https://www.gnu.org/licenses/>.
<commit_msg>Fix screenshot save path.<commit_after>#include <QtTest/QtTest>
#include <QProcess>
#include <QScreen>
#include <QPixmap>

#include "../cutehmi.dirs.hpp"

namespace cutehmi {
namespace daemon {

class test_cutehmi_view:
	public QObject
{
		Q_OBJECT

	private slots:
		void initTestCase();

		void helpOption();

		void versionOption();

		void screenshot();

	private:
		QString m_installDir;
		QString m_programPath;
		int m_windowDecorationsWidth;
		int m_windowDecorationsHeight;
};

void test_cutehmi_view::initTestCase()
{
	m_installDir = qEnvironmentVariable("CUTEHMI_INSTALL_DIR");
	QVERIFY(!m_installDir.isEmpty());

	QString toolsInstallSubdir = CUTEHMI_DIRS_TOOLS_INSTALL_SUBDIR;
	m_programPath = m_installDir;
	if (!toolsInstallSubdir.isEmpty())
		m_programPath += "/" + toolsInstallSubdir;
	m_programPath +=  "/cutehmi.view.2";
#ifndef CUTEHMI_NDEBUG
	m_programPath += ".debug";
#endif

	// Using helper window to calculate size of window decorations.
	QWindow helperWindow;
	helperWindow.show();
	m_windowDecorationsWidth = helperWindow.frameGeometry().width() - helperWindow.geometry().width();
	m_windowDecorationsHeight = helperWindow.frameGeometry().height() - helperWindow.geometry().height();
}

void test_cutehmi_view::helpOption()
{
	QList<QStringList> argumentsList;
	argumentsList << QStringList({"--help"})
			<< QStringList({"--h"});

	for (auto arguments : argumentsList) {
		QProcess process;
		process.start(m_programPath, arguments);
		process.waitForFinished(1000);
		QCOMPARE(process.error(), QProcess::UnknownError);
		QVERIFY(!process.readAllStandardError().contains("Unknown option"));
		QVERIFY(!process.readAllStandardOutput().isEmpty());
		QCOMPARE(process.exitStatus(), QProcess::NormalExit);
		QCOMPARE(process.exitCode(), EXIT_SUCCESS);
	}
}

void test_cutehmi_view::versionOption()
{
	QList<QStringList> argumentsList;
	argumentsList << QStringList({"--version"})
			<< QStringList({"--v"});

	for (auto arguments : argumentsList) {
		QProcess process;
		process.start(m_programPath, arguments);
		process.waitForFinished(1000);
		QCOMPARE(process.error(), QProcess::UnknownError);
		QVERIFY(!process.readAllStandardError().contains("Unknown option"));
		QVERIFY(!process.readAllStandardOutput().isEmpty());
		QCOMPARE(process.exitStatus(), QProcess::NormalExit);
		QCOMPARE(process.exitCode(), EXIT_SUCCESS);
	}
}

void test_cutehmi_view::screenshot()
{
	int width = 800;
	int height = 600;

	QStringList arguments;
	QString windowgeometryArg = QString::number(width) + "x" + QString::number(height) + "+0+0";
	arguments << "-qwindowgeometry" << windowgeometryArg << "--lang" << "en_EN";

	QString screenshotPath = m_installDir;
	QString artifactsInstallSubdir = CUTEHMI_DIRS_ARTIFACTS_INSTALL_SUBDIR;
	if (!artifactsInstallSubdir.isEmpty())
		screenshotPath += "/" + artifactsInstallSubdir;
	screenshotPath += "/screenshots/" CUTEHMI_DIRS_PROJECT_RELATIVE_PATH "/screenshot.png";
	const char * screenshotFormat = "PNG";

	QProcess process;
	process.start(m_programPath, arguments);
	process.waitForFinished(1500);	// This gives some time for the GUI to show up.

	QScreen * screen = QGuiApplication::primaryScreen();
	if (screen) {
		QPixmap screenshot = screen->grabWindow(0, 0, 0, width + m_windowDecorationsWidth, height + m_windowDecorationsHeight);
		QVERIFY(QDir().mkpath(QFileInfo(screenshotPath).dir().path()));
		QVERIFY(screenshot.save(screenshotPath, screenshotFormat));
	}

	process.terminate();
	process.waitForFinished();
}

}
}

QTEST_MAIN(cutehmi::daemon::test_cutehmi_view)
#include "test_cutehmi_view.moc"

//(c)C: Copyright © 2020, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI 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 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI 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.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI.  If not, see <https://www.gnu.org/licenses/>.
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "exceptions/exceptions.hh"

enum class compressor {
    none,
    lz4,
    snappy,
    deflate,
};

class compression_parameters {
public:
    static constexpr int32_t DEFAULT_CHUNK_LENGTH = 64 * 1024;
    static constexpr double DEFAULT_CRC_CHECK_CHANCE = 1.0;

    static constexpr auto SSTABLE_COMPRESSION = "sstable_compression";
    static constexpr auto CHUNK_LENGTH_KB = "chunk_length_kb";
    static constexpr auto CRC_CHECK_CHANCE = "crc_check_chance";
private:
    compressor _compressor = compressor::none;
    std::experimental::optional<int> _chunk_length;
    std::experimental::optional<double> _crc_check_chance;
public:
    compression_parameters() = default;
    compression_parameters(compressor c) : _compressor(c) { }
    compression_parameters(const std::map<sstring, sstring>& options) {
        validate_options(options);

        const auto& compressor_class = options.at(SSTABLE_COMPRESSION);
        if (is_compressor_class(compressor_class, "LZ4Compressor")) {
            _compressor = compressor::lz4;
        } else if (is_compressor_class(compressor_class, "SnappyCompressor")) {
            _compressor = compressor::snappy;
        } else if (is_compressor_class(compressor_class, "DeflateCompressor")) {
            _compressor = compressor::deflate;
        } else {
            throw exceptions::configuration_exception(sstring("Unsupported compression class '") + compressor_class + "'.");
        }
        auto chunk_length = options.find(CHUNK_LENGTH_KB);
        if (chunk_length != options.end()) {
            try {
                _chunk_length = std::stoi(chunk_length->second) * 1024;
            } catch (const std::exception& e) {
                throw exceptions::syntax_exception(sstring("Invalid integer value ") + chunk_length->second + " for " + CHUNK_LENGTH_KB);
            }
        }
        auto crc_chance = options.find(CRC_CHECK_CHANCE);
        if (crc_chance != options.end()) {
            try {
                _crc_check_chance = std::stod(crc_chance->second);
            } catch (const std::exception& e) {
                throw exceptions::syntax_exception(sstring("Invalid double value ") + crc_chance->second + "for " + CRC_CHECK_CHANCE);
            }
        }
    }

    compressor get_compressor() const { return _compressor; }
    int32_t chunk_length() const { return _chunk_length.value_or(int(DEFAULT_CHUNK_LENGTH)); }
    double crc_check_chance() const { return _crc_check_chance.value_or(double(DEFAULT_CRC_CHECK_CHANCE)); }

    void validate() {
        if (_chunk_length) {
            auto chunk_length = _chunk_length.value();
            if (chunk_length <= 0) {
                throw exceptions::configuration_exception(sstring("Invalid negative or null ") + CHUNK_LENGTH_KB);
            }
            // _chunk_length must be a power of two
            if (chunk_length & (chunk_length - 1)) {
                throw exceptions::configuration_exception(sstring(CHUNK_LENGTH_KB) + " must be a power of 2.");
            }
        }
        if (_crc_check_chance && (_crc_check_chance.value() < 0.0 || _crc_check_chance.value() > 1.0)) {
            throw exceptions::configuration_exception(sstring(CRC_CHECK_CHANCE) + " must be between 0.0 and 1.0.");
        }
    }

    std::map<sstring, sstring> get_options() const {
        if (_compressor == compressor::none) {
            return std::map<sstring, sstring>();
        }
        std::map<sstring, sstring> opts;
        opts.emplace(sstring(SSTABLE_COMPRESSION), compressor_name());
        if (_chunk_length) {
            opts.emplace(sstring(CHUNK_LENGTH_KB), std::to_string(_chunk_length.value() / 1024));
        }
        if (_crc_check_chance) {
            opts.emplace(sstring(CRC_CHECK_CHANCE), std::to_string(_crc_check_chance.value()));
        }
        return opts;
    }
private:
    void validate_options(const std::map<sstring, sstring>& options) {
        // currently, there are no options specific to a particular compressor
        static std::set<sstring> keywords({
            sstring(SSTABLE_COMPRESSION),
            sstring(CHUNK_LENGTH_KB),
            sstring(CRC_CHECK_CHANCE),
        });
        for (auto&& opt : options) {
            if (!keywords.count(opt.first)) {
                throw exceptions::configuration_exception(sprint("Unknown compression option '%s'.", opt.first));
            }
        }
    }
    bool is_compressor_class(const sstring& value, const sstring& class_name) {
        static const sstring namespace_prefix = "org.apache.cassandra.io.compress.";
        return value == class_name || value == namespace_prefix + class_name;
    }
    sstring compressor_name() const {
        switch (_compressor) {
        case compressor::lz4:
             return "org.apache.cassandra.io.compress.LZ4Compressor";
        case compressor::snappy:
            return "org.apache.cassandra.io.compress.SnappyCompressor";
        case compressor::deflate:
            return "org.apache.cassandra.io.compress.DeflateCompressor";
        default:
            abort();
        }
    }
};
<commit_msg>compressor: allow an empty map of options<commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "exceptions/exceptions.hh"

enum class compressor {
    none,
    lz4,
    snappy,
    deflate,
};

class compression_parameters {
public:
    static constexpr int32_t DEFAULT_CHUNK_LENGTH = 64 * 1024;
    static constexpr double DEFAULT_CRC_CHECK_CHANCE = 1.0;

    static constexpr auto SSTABLE_COMPRESSION = "sstable_compression";
    static constexpr auto CHUNK_LENGTH_KB = "chunk_length_kb";
    static constexpr auto CRC_CHECK_CHANCE = "crc_check_chance";
private:
    compressor _compressor = compressor::none;
    std::experimental::optional<int> _chunk_length;
    std::experimental::optional<double> _crc_check_chance;
public:
    compression_parameters() = default;
    compression_parameters(compressor c) : _compressor(c) { }
    compression_parameters(const std::map<sstring, sstring>& options) {
        validate_options(options);

        auto it = options.find(SSTABLE_COMPRESSION);
        if (it == options.end()) {
            return;
        }
        const auto& compressor_class = it->second;
        if (is_compressor_class(compressor_class, "LZ4Compressor")) {
            _compressor = compressor::lz4;
        } else if (is_compressor_class(compressor_class, "SnappyCompressor")) {
            _compressor = compressor::snappy;
        } else if (is_compressor_class(compressor_class, "DeflateCompressor")) {
            _compressor = compressor::deflate;
        } else {
            throw exceptions::configuration_exception(sstring("Unsupported compression class '") + compressor_class + "'.");
        }
        auto chunk_length = options.find(CHUNK_LENGTH_KB);
        if (chunk_length != options.end()) {
            try {
                _chunk_length = std::stoi(chunk_length->second) * 1024;
            } catch (const std::exception& e) {
                throw exceptions::syntax_exception(sstring("Invalid integer value ") + chunk_length->second + " for " + CHUNK_LENGTH_KB);
            }
        }
        auto crc_chance = options.find(CRC_CHECK_CHANCE);
        if (crc_chance != options.end()) {
            try {
                _crc_check_chance = std::stod(crc_chance->second);
            } catch (const std::exception& e) {
                throw exceptions::syntax_exception(sstring("Invalid double value ") + crc_chance->second + "for " + CRC_CHECK_CHANCE);
            }
        }
    }

    compressor get_compressor() const { return _compressor; }
    int32_t chunk_length() const { return _chunk_length.value_or(int(DEFAULT_CHUNK_LENGTH)); }
    double crc_check_chance() const { return _crc_check_chance.value_or(double(DEFAULT_CRC_CHECK_CHANCE)); }

    void validate() {
        if (_chunk_length) {
            auto chunk_length = _chunk_length.value();
            if (chunk_length <= 0) {
                throw exceptions::configuration_exception(sstring("Invalid negative or null ") + CHUNK_LENGTH_KB);
            }
            // _chunk_length must be a power of two
            if (chunk_length & (chunk_length - 1)) {
                throw exceptions::configuration_exception(sstring(CHUNK_LENGTH_KB) + " must be a power of 2.");
            }
        }
        if (_crc_check_chance && (_crc_check_chance.value() < 0.0 || _crc_check_chance.value() > 1.0)) {
            throw exceptions::configuration_exception(sstring(CRC_CHECK_CHANCE) + " must be between 0.0 and 1.0.");
        }
    }

    std::map<sstring, sstring> get_options() const {
        if (_compressor == compressor::none) {
            return std::map<sstring, sstring>();
        }
        std::map<sstring, sstring> opts;
        opts.emplace(sstring(SSTABLE_COMPRESSION), compressor_name());
        if (_chunk_length) {
            opts.emplace(sstring(CHUNK_LENGTH_KB), std::to_string(_chunk_length.value() / 1024));
        }
        if (_crc_check_chance) {
            opts.emplace(sstring(CRC_CHECK_CHANCE), std::to_string(_crc_check_chance.value()));
        }
        return opts;
    }
private:
    void validate_options(const std::map<sstring, sstring>& options) {
        // currently, there are no options specific to a particular compressor
        static std::set<sstring> keywords({
            sstring(SSTABLE_COMPRESSION),
            sstring(CHUNK_LENGTH_KB),
            sstring(CRC_CHECK_CHANCE),
        });
        for (auto&& opt : options) {
            if (!keywords.count(opt.first)) {
                throw exceptions::configuration_exception(sprint("Unknown compression option '%s'.", opt.first));
            }
        }
    }
    bool is_compressor_class(const sstring& value, const sstring& class_name) {
        static const sstring namespace_prefix = "org.apache.cassandra.io.compress.";
        return value == class_name || value == namespace_prefix + class_name;
    }
    sstring compressor_name() const {
        switch (_compressor) {
        case compressor::lz4:
             return "org.apache.cassandra.io.compress.LZ4Compressor";
        case compressor::snappy:
            return "org.apache.cassandra.io.compress.SnappyCompressor";
        case compressor::deflate:
            return "org.apache.cassandra.io.compress.DeflateCompressor";
        default:
            abort();
        }
    }
};
<|endoftext|>


<commit_before>#include <iostream>
#include <cassert>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>

#include "TFile.h"
#include "TTree.h"
#include "TChain.h"
#include "TBranch.h"
#include "TBasket.h"

void readandtest (const std::string & fname)
{
  TFile* inputFile = new TFile(fname.c_str(),"READ");

#if 0
  std::cout << "Print file info: " << std::endl;
  inputFile->Print();
  std::cout << std::endl;

  std::cout << "List file TTree: " << std::endl;
  inputFile->ls();
  std::cout << std::endl;

  std::cout << "Print Pixels info: " << std::endl;
  TTree* t0 = (TTree*) inputFile->Get("Pixels");
  t0->Print();
  std::cout << std::endl;

  std::cout << "Print MC info: " << std::endl;
  TTree* t01 = (TTree*) inputFile->Get("MC");
  t01->Print();
  std::cout << std::endl;

  std::cout << "Print TkStubs info: " << std::endl;
#endif

  TTree* t1 = (TTree*) inputFile->Get("TkStubs");
  TChain* TT = (TChain*) inputFile->Get("TkStubs");

  TTree* tmc = (TTree*) inputFile->Get("MC");
  //tmc->Print();
  TChain* TTmc = (TChain*) inputFile->Get("MC");

  std::vector<float> genpx, * p_genpx;
  p_genpx = &genpx;
  TTmc->SetBranchAddress("gen_px", &p_genpx);

  Int_t neventmc = tmc->GetEntries();
  for (Int_t i=0; i<neventmc; ++i)
  {
     tmc->GetEvent(i);

     int j = 0;
     for (; j<(int)genpx.size(); ++j)
     {
       //std::cout << genpx[j] << std::endl;
     }
  }

#if 0
  t1->Print();
  std::cout << std::endl;
#endif

  std::vector<int> layerid, * p_layerid, moduleid, * p_moduleid,
    ladderid, * p_ladderid, tp, * p_tp;
  p_layerid = &layerid;
  p_ladderid = &ladderid;
  p_moduleid = &moduleid;
  p_tp = &tp;

  TT->SetBranchAddress("L1TkSTUB_layer", &p_layerid);
  TT->SetBranchAddress("L1TkSTUB_ladder", &p_ladderid);
  TT->SetBranchAddress("L1TkSTUB_module", &p_moduleid);
  TT->SetBranchAddress("L1TkSTUB_tp", &p_tp);

  std::vector<float> stubx, * p_stubx, stuby, * p_stuby, stubz, * p_stubz,
    px, * p_px, py, * p_py, x0, * p_x0, y0, * p_y0, z0, * p_z0, eta, * p_eta,
    phi, * p_phi;
  p_stubx = &stubx;
  p_stuby = &stuby;
  p_stubz = &stubz;
  p_px = &px;
  p_py = &py;
  p_x0 = &x0;
  p_y0 = &y0;
  p_z0 = &z0;
  p_eta = η
  p_phi = φ

  TT->SetBranchAddress("L1TkSTUB_x", &p_stubx);
  TT->SetBranchAddress("L1TkSTUB_y", &p_stuby);
  TT->SetBranchAddress("L1TkSTUB_z", &p_stubz);

  TT->SetBranchAddress("L1TkSTUB_pxGEN", &p_px);
  TT->SetBranchAddress("L1TkSTUB_pyGEN", &p_py);
  TT->SetBranchAddress("L1TkSTUB_X0", &p_x0);
  TT->SetBranchAddress("L1TkSTUB_Y0", &p_y0);
  TT->SetBranchAddress("L1TkSTUB_Z0", &p_z0);
  TT->SetBranchAddress("L1TkSTUB_etaGEN", &p_eta);
  TT->SetBranchAddress("L1TkSTUB_PHI0", &p_phi);

  unsigned int countevt = 0;
  Int_t nevent = t1->GetEntries();
  std::cout << "We got " << nevent << " events " << std::endl;
  std::ofstream ptfile("pt.txt");
  std::ofstream phifile("phi.txt");
  std::ofstream d0file("d0.txt");
  std::ofstream etafile("eta.txt");
  std::ofstream z0file("z0.txt");
  for (Int_t i=0; i<nevent; ++i)
  {
     //L1TkSTUB_tp tutti gli stub appartenti alla stessa traccia hanno stesso tp
     //  posso avere eventi con molte tracce devo solezionarle usando tp
     //
     //StubExtractor e' utile punto di partenza visto che contiene il codice
     //   che scrive il Tree L1Tk

     t1->GetEvent(i);
     assert (layerid.size() == ladderid.size());
     assert (layerid.size() == moduleid.size());
     assert (layerid.size() == tp.size());

     assert (layerid.size() == stubx.size());
     assert (layerid.size() == stuby.size());
     assert (layerid.size() == stubz.size());
     assert (layerid.size() == px.size());
     assert (layerid.size() == py.size());
     assert (layerid.size() == x0.size());
     assert (layerid.size() == y0.size());
     assert (layerid.size() == z0.size());
     assert (layerid.size() == eta.size());
     assert (layerid.size() == phi.size());

     /*
      *
      * pT = sqrt(pxGEN^2 + pyGEN^2)
      * Phi = PHI0
      * d0 = sqrt(X0^2 + Y0^2)
      * Eta = etaGEN
      * z0 = Z0
      *
      */

     if (layerid.size() == 6)
     {
       if ((z0[layerid.size()-1] <= 15.0) && (z0[layerid.size()-1] >= -15))
       {
         std::cout << i+1 << " " << tp.size() << std::endl;

         int j = 0;
         for (; j<(int)layerid.size(); ++j)
         {
          std::cout << stubx[j] << " " << stuby[j] << " " <<
             stubz[j] << " ";

#if 0
           std::cout << sqrt(pow(px[j],2.0) + pow(py[j],2.0)) << " "  <<
             phi[j] << " " << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0)) << " "
             << eta[j] << " " << z0[j] << " ";
#endif

           std::cout << layerid[j] << " " << ladderid[j] << " " <<
             moduleid[j] << " "
#if 0
           << tp[j] << std::endl;
#else
           << std::endl;
#endif

           ptfile << sqrt(pow(px[j],2.0) + pow(py[j],2.0))
             << std::endl;
           phifile << phi[j] << std::endl;
           d0file << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0))
             << std::endl;
           etafile << eta[j] << std::endl;
           z0file << z0[j] << std::endl;
         }
         --j;

         std::cout << sqrt(pow(px[j],2.0) + pow(py[j],2.0)) << " "  <<
           phi[j] << " " << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0)) << " "
           << eta[j] << " " << z0[j] << std::endl;

         countevt++;
       }
     }

     //t1->Show(i);
  }
  ptfile.close();
  phifile.close();
  d0file.close();
  etafile.close();
  z0file.close();

  std::cout << "Event with 6 layer " << countevt << std::endl;

  inputFile->Close();
}

# ifndef __CINT__
int main(int argc, char ** argv)
{
  if (argc != 2)
  {
    std::cerr << "usage: " << argv[0] << " rootfilename " << std::endl;
    return 1;
  }

  readandtest(argv[1]);

  return 0;
}
# endif
<commit_msg>check if all elemnt are equals<commit_after>#include <algorithm>
#include <iostream>
#include <cassert>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>

#include "TFile.h"
#include "TTree.h"
#include "TChain.h"
#include "TBranch.h"
#include "TBasket.h"

void readandtest (const std::string & fname)
{
  TFile* inputFile = new TFile(fname.c_str(),"READ");

#if 0
  std::cout << "Print file info: " << std::endl;
  inputFile->Print();
  std::cout << std::endl;

  std::cout << "List file TTree: " << std::endl;
  inputFile->ls();
  std::cout << std::endl;

  std::cout << "Print Pixels info: " << std::endl;
  TTree* t0 = (TTree*) inputFile->Get("Pixels");
  t0->Print();
  std::cout << std::endl;

  std::cout << "Print MC info: " << std::endl;
  TTree* t01 = (TTree*) inputFile->Get("MC");
  t01->Print();
  std::cout << std::endl;

  std::cout << "Print TkStubs info: " << std::endl;
#endif

  TTree* t1 = (TTree*) inputFile->Get("TkStubs");
  TChain* TT = (TChain*) inputFile->Get("TkStubs");

  TTree* tmc = (TTree*) inputFile->Get("MC");
  //tmc->Print();
  TChain* TTmc = (TChain*) inputFile->Get("MC");

  std::vector<float> genpx, * p_genpx;
  p_genpx = &genpx;
  TTmc->SetBranchAddress("gen_px", &p_genpx);

  Int_t neventmc = tmc->GetEntries();
  for (Int_t i=0; i<neventmc; ++i)
  {
     tmc->GetEvent(i);

     int j = 0;
     for (; j<(int)genpx.size(); ++j)
     {
       //std::cout << genpx[j] << std::endl;
     }
  }

#if 0
  t1->Print();
  std::cout << std::endl;
#endif

  std::vector<int> layerid, * p_layerid, moduleid, * p_moduleid,
    ladderid, * p_ladderid, tp, * p_tp;
  p_layerid = &layerid;
  p_ladderid = &ladderid;
  p_moduleid = &moduleid;
  p_tp = &tp;

  TT->SetBranchAddress("L1TkSTUB_layer", &p_layerid);
  TT->SetBranchAddress("L1TkSTUB_ladder", &p_ladderid);
  TT->SetBranchAddress("L1TkSTUB_module", &p_moduleid);
  TT->SetBranchAddress("L1TkSTUB_tp", &p_tp);

  std::vector<float> stubx, * p_stubx, stuby, * p_stuby, stubz, * p_stubz,
    px, * p_px, py, * p_py, x0, * p_x0, y0, * p_y0, z0, * p_z0, eta, * p_eta,
    phi, * p_phi;
  p_stubx = &stubx;
  p_stuby = &stuby;
  p_stubz = &stubz;
  p_px = &px;
  p_py = &py;
  p_x0 = &x0;
  p_y0 = &y0;
  p_z0 = &z0;
  p_eta = η
  p_phi = φ

  TT->SetBranchAddress("L1TkSTUB_x", &p_stubx);
  TT->SetBranchAddress("L1TkSTUB_y", &p_stuby);
  TT->SetBranchAddress("L1TkSTUB_z", &p_stubz);

  TT->SetBranchAddress("L1TkSTUB_pxGEN", &p_px);
  TT->SetBranchAddress("L1TkSTUB_pyGEN", &p_py);
  TT->SetBranchAddress("L1TkSTUB_X0", &p_x0);
  TT->SetBranchAddress("L1TkSTUB_Y0", &p_y0);
  TT->SetBranchAddress("L1TkSTUB_Z0", &p_z0);
  TT->SetBranchAddress("L1TkSTUB_etaGEN", &p_eta);
  TT->SetBranchAddress("L1TkSTUB_PHI0", &p_phi);

  unsigned int countevt = 0;
  Int_t nevent = t1->GetEntries();
  std::cout << "We got " << nevent << " events " << std::endl;
  std::ofstream ptfile("pt.txt");
  std::ofstream phifile("phi.txt");
  std::ofstream d0file("d0.txt");
  std::ofstream etafile("eta.txt");
  std::ofstream z0file("z0.txt");
  for (Int_t i=0; i<nevent; ++i)
  {
     //L1TkSTUB_tp tutti gli stub appartenti alla stessa traccia hanno stesso tp
     //  posso avere eventi con molte tracce devo solezionarle usando tp
     //
     //StubExtractor e' utile punto di partenza visto che contiene il codice
     //   che scrive il Tree L1Tk

     t1->GetEvent(i);
     assert (layerid.size() == ladderid.size());
     assert (layerid.size() == moduleid.size());
     assert (layerid.size() == tp.size());

     assert (layerid.size() == stubx.size());
     assert (layerid.size() == stuby.size());
     assert (layerid.size() == stubz.size());
     assert (layerid.size() == px.size());
     assert (layerid.size() == py.size());
     assert (layerid.size() == x0.size());
     assert (layerid.size() == y0.size());
     assert (layerid.size() == z0.size());
     assert (layerid.size() == eta.size());
     assert (layerid.size() == phi.size());

     /*
      *
      * pT = sqrt(pxGEN^2 + pyGEN^2)
      * Phi = PHI0
      * d0 = sqrt(X0^2 + Y0^2)
      * Eta = etaGEN
      * z0 = Z0
      *
      */

     if (layerid.size() == 6)
     {
       bool allAreEqual = std::find_if(z0.begin() + 1, z0.end(),
          std::bind1st(std::not_equal_to<int>(), z0.front())) == z0.end();
       if ((z0[0] <= 15.0) && (z0[0] >= -15) && allAreEqual)
       {
         std::cout << i+1 << " " << tp.size() << std::endl;

         int j = 0;
         for (; j<(int)layerid.size(); ++j)
         {
          std::cout << stubx[j] << " " << stuby[j] << " " <<
             stubz[j] << " ";

#if 0
           std::cout << sqrt(pow(px[j],2.0) + pow(py[j],2.0)) << " "  <<
             phi[j] << " " << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0)) << " "
             << eta[j] << " " << z0[j] << " ";
#endif

           std::cout << layerid[j] << " " << ladderid[j] << " " <<
             moduleid[j] << " "
#if 0
           << tp[j] << std::endl;
#else
           << std::endl;
#endif

           ptfile << sqrt(pow(px[j],2.0) + pow(py[j],2.0))
             << std::endl;
           phifile << phi[j] << std::endl;
           d0file << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0))
             << std::endl;
           etafile << eta[j] << std::endl;
           z0file << z0[j] << std::endl;
         }
         --j;

         std::cout << sqrt(pow(px[j],2.0) + pow(py[j],2.0)) << " "  <<
           phi[j] << " " << sqrt(pow(x0[j],2.0) + pow(y0[j],2.0)) << " "
           << eta[j] << " " << z0[j] << std::endl;

         countevt++;
       }
     }

     //t1->Show(i);
  }
  ptfile.close();
  phifile.close();
  d0file.close();
  etafile.close();
  z0file.close();

  std::cout << "Event with 6 layer " << countevt << std::endl;

  inputFile->Close();
}

# ifndef __CINT__
int main(int argc, char ** argv)
{
  if (argc != 2)
  {
    std::cerr << "usage: " << argv[0] << " rootfilename " << std::endl;
    return 1;
  }

  readandtest(argv[1]);

  return 0;
}
# endif
<|endoftext|>