<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 */

#include <numeric>
#include <thread>

#include <adios2.h>
#include <adios2/common/ADIOSMacros.h>
#include <adios2/helper/adiosFunctions.h>
#include <gtest/gtest.h>

using namespace adios2;

size_t print_lines = 0;
size_t to_print_lines = 10;

template <class T>
void GenData(std::vector<std::complex<T>> &data, const size_t step)
{
    for (size_t i = 0; i < data.size(); ++i)
    {
        data[i] = {static_cast<T>(i + 10000 + step * 100),
                   static_cast<T>(i + 10000)};
    }
}

template <class T>
void GenData(std::vector<T> &data, const size_t step)
{
    for (size_t i = 0; i < data.size(); ++i)
    {
        data[i] = i + 10000 + step * 100;
    }
}

template <class T>
void PrintData(const T *data, const size_t size, const size_t step)
{
    std::cout << "Step: " << step << " [";
    size_t printsize = 32;
    if (size < printsize)
    {
        printsize = size;
    }
    for (size_t i = 0; i < printsize; ++i)
    {
        std::cout << data[i] << " ";
    }
    std::cout << "]" << std::endl;
}

template <class T>
void VerifyData(const std::complex<T> *data, const size_t size, size_t step)
{
    std::vector<std::complex<T>> tmpdata(size);
    GenData(tmpdata, step);
    for (size_t i = 0; i < size; ++i)
    {
        ASSERT_EQ(data[i], tmpdata[i]);
    }
}

template <class T>
void VerifyData(const T *data, const size_t size, size_t step)
{
    std::vector<T> tmpdata(size);
    GenData(tmpdata, step);
    for (size_t i = 0; i < size; ++i)
    {
        ASSERT_EQ(data[i], tmpdata[i]);
    }
}

template <class T>
void VerifyData(const std::vector<T> &data, const size_t step)
{
    VerifyData(data.data(), data.size(), step);
}

void DataManWriter(const Dims &shape, const Dims &start, const Dims &count,
                   const size_t steps, const adios2::Params &engineParams)
{
    size_t datasize = std::accumulate(count.begin(), count.end(), 1,
                                      std::multiplies<size_t>());
    adios2::ADIOS adios;
    adios2::IO dataManIO = adios.DeclareIO("WAN");
    dataManIO.SetEngine("DataMan");
    dataManIO.SetParameters(engineParams);
    std::vector<char> myChars(datasize);
    std::vector<unsigned char> myUChars(datasize);
    std::vector<short> myShorts(datasize);
    std::vector<unsigned short> myUShorts(datasize);
    std::vector<int> myInts(datasize);
    std::vector<unsigned int> myUInts(datasize);
    std::vector<float> myFloats(datasize);
    std::vector<double> myDoubles(datasize);
    std::vector<std::complex<float>> myComplexes(datasize);
    std::vector<std::complex<double>> myDComplexes(datasize);
    auto bpChars =
        dataManIO.DefineVariable<char>("bpChars", shape, start, count);
    auto bpUChars = dataManIO.DefineVariable<unsigned char>("bpUChars", shape,
                                                            start, count);
    auto bpShorts =
        dataManIO.DefineVariable<short>("bpShorts", shape, start, count);
    auto bpUShorts = dataManIO.DefineVariable<unsigned short>(
        "bpUShorts", shape, start, count);
    auto bpInts = dataManIO.DefineVariable<int>("bpInts", shape, start, count);
    auto bpUInts =
        dataManIO.DefineVariable<unsigned int>("bpUInts", shape, start, count);
    auto bpFloats =
        dataManIO.DefineVariable<float>("bpFloats", shape, start, count);
    auto bpDoubles =
        dataManIO.DefineVariable<double>("bpDoubles", shape, start, count);
    auto bpComplexes = dataManIO.DefineVariable<std::complex<float>>(
        "bpComplexes", shape, start, count);
    auto bpDComplexes = dataManIO.DefineVariable<std::complex<double>>(
        "bpDComplexes", shape, start, count);
    auto bpUInt64s = dataManIO.DefineVariable<uint64_t>("bpUInt64s");
    dataManIO.DefineAttribute<int>("AttInt", 110);
    adios2::Engine dataManWriter =
        dataManIO.Open("stream", adios2::Mode::Write);
    for (uint64_t i = 0; i < steps; ++i)
    {
        dataManWriter.BeginStep();
        GenData(myChars, i);
        GenData(myUChars, i);
        GenData(myShorts, i);
        GenData(myUShorts, i);
        GenData(myInts, i);
        GenData(myUInts, i);
        GenData(myFloats, i);
        GenData(myDoubles, i);
        GenData(myComplexes, i);
        GenData(myDComplexes, i);
        dataManWriter.Put(bpChars, myChars.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpUChars, myUChars.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpShorts, myShorts.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpInts, myInts.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpUInts, myUInts.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpFloats, myFloats.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpDComplexes, myDComplexes.data(),
                          adios2::Mode::Sync);
        dataManWriter.Put(bpUInt64s, i);
        dataManWriter.EndStep();
    }
    dataManWriter.Close();
}

void DataManReader(const Dims &shape, const Dims &start, const Dims &count,
                   const size_t steps, const adios2::Params &engineParams)
{
    size_t datasize = std::accumulate(count.begin(), count.end(), 1,
                                      std::multiplies<size_t>());
    adios2::ADIOS adios;
    adios2::IO dataManIO = adios.DeclareIO("WAN");
    dataManIO.SetEngine("DataMan");
    dataManIO.SetParameters(engineParams);
    adios2::Engine dataManReader = dataManIO.Open("stream", adios2::Mode::Read);

    std::vector<char> myChars(datasize);
    std::vector<unsigned char> myUChars(datasize);
    std::vector<short> myShorts(datasize);
    std::vector<unsigned short> myUShorts(datasize);
    std::vector<int> myInts(datasize);
    std::vector<unsigned int> myUInts(datasize);
    std::vector<float> myFloats(datasize);
    std::vector<double> myDoubles(datasize);
    std::vector<std::complex<float>> myComplexes(datasize);
    std::vector<std::complex<double>> myDComplexes(datasize);
    bool received_steps = false;
    size_t currentStep;
    while (true)
    {
        adios2::StepStatus status = dataManReader.BeginStep(StepMode::Read, 5);
        if (status == adios2::StepStatus::OK)
        {
            received_steps = true;
            const auto &vars = dataManIO.AvailableVariables();
            ASSERT_EQ(vars.size(), 11);
            currentStep = dataManReader.CurrentStep();
            adios2::Variable<char> bpChars =
                dataManIO.InquireVariable<char>("bpChars");
            adios2::Variable<unsigned char> bpUChars =
                dataManIO.InquireVariable<unsigned char>("bpUChars");
            adios2::Variable<short> bpShorts =
                dataManIO.InquireVariable<short>("bpShorts");
            adios2::Variable<unsigned short> bpUShorts =
                dataManIO.InquireVariable<unsigned short>("bpUShorts");
            adios2::Variable<int> bpInts =
                dataManIO.InquireVariable<int>("bpInts");
            adios2::Variable<unsigned int> bpUInts =
                dataManIO.InquireVariable<unsigned int>("bpUInts");
            adios2::Variable<float> bpFloats =
                dataManIO.InquireVariable<float>("bpFloats");
            adios2::Variable<double> bpDoubles =
                dataManIO.InquireVariable<double>("bpDoubles");
            adios2::Variable<std::complex<float>> bpComplexes =
                dataManIO.InquireVariable<std::complex<float>>("bpComplexes");
            adios2::Variable<std::complex<double>> bpDComplexes =
                dataManIO.InquireVariable<std::complex<double>>("bpDComplexes");
            adios2::Variable<uint64_t> bpUInt64s =
                dataManIO.InquireVariable<uint64_t>("bpUInt64s");
            auto charsBlocksInfo = dataManReader.AllStepsBlocksInfo(bpChars);
            bpChars.SetSelection({start, count});
            bpUChars.SetSelection({start, count});
            bpShorts.SetSelection({start, count});
            bpUShorts.SetSelection({start, count});
            bpInts.SetSelection({start, count});
            bpUInts.SetSelection({start, count});
            bpFloats.SetSelection({start, count});
            bpDoubles.SetSelection({start, count});
            bpComplexes.SetSelection({start, count});
            bpDComplexes.SetSelection({start, count});
            dataManReader.Get(bpChars, myChars.data(), adios2::Mode::Sync);
            dataManReader.Get(bpUChars, myUChars.data(), adios2::Mode::Sync);
            dataManReader.Get(bpShorts, myShorts.data(), adios2::Mode::Sync);
            dataManReader.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
            dataManReader.Get(bpInts, myInts.data(), adios2::Mode::Sync);
            dataManReader.Get(bpUInts, myUInts.data(), adios2::Mode::Sync);
            dataManReader.Get(bpFloats, myFloats.data(), adios2::Mode::Sync);
            dataManReader.Get(bpDoubles, myDoubles.data(), adios2::Mode::Sync);
            dataManReader.Get(bpComplexes, myComplexes.data(),
                              adios2::Mode::Sync);
            dataManReader.Get(bpDComplexes, myDComplexes.data(),
                              adios2::Mode::Sync);
            uint64_t stepValue;
            dataManReader.Get(bpUInt64s, &stepValue, adios2::Mode::Sync);
            ASSERT_EQ(currentStep, stepValue);
            VerifyData(myChars, currentStep);
            VerifyData(myUChars, currentStep);
            VerifyData(myShorts, currentStep);
            VerifyData(myUShorts, currentStep);
            VerifyData(myInts, currentStep);
            VerifyData(myUInts, currentStep);
            VerifyData(myFloats, currentStep);
            VerifyData(myDoubles, currentStep);
            VerifyData(myComplexes, currentStep);
            VerifyData(myDComplexes, currentStep);
            dataManReader.EndStep();
        }
        else if (status == adios2::StepStatus::EndOfStream)
        {
            break;
        }
        else if (status == adios2::StepStatus::NotReady)
        {
            continue;
        }
    }
    if (received_steps)
    {
        auto attInt = dataManIO.InquireAttribute<int>("AttInt");
        ASSERT_EQ(110, attInt.Data()[0]);
        ASSERT_NE(111, attInt.Data()[0]);
    }
    dataManReader.Close();
}

class DataManEngineTest : public ::testing::Test
{
public:
    DataManEngineTest() = default;
};

#ifdef ADIOS2_HAVE_ZEROMQ
TEST_F(DataManEngineTest, 1DSuperLarge)
{
    // set parameters
    Dims shape = {500000};
    Dims start = {0};
    Dims count = {500000};
    size_t steps = 10;

    // run workflow
    adios2::Params readerEngineParams = {{"IPAddress", "127.0.0.1"},
                                         {"Port", "13480"},
                                         {"MaxStepBufferSize", "50000000"},
                                         {"TransportMode", "reliable"}};
    auto r = std::thread(DataManReader, shape, start, count, steps,
                         readerEngineParams);
    adios2::Params writerEngineParams = {{"IPAddress", "127.0.0.1"},
                                         {"Port", "13480"},
                                         {"TransportMode", "reliable"}};
    auto w = std::thread(DataManWriter, shape, start, count, steps,
                         writerEngineParams);
    w.join();
    r.join();
}
#endif // ZEROMQ

int main(int argc, char **argv)
{
    int result;
    ::testing::InitGoogleTest(&argc, argv);
    result = RUN_ALL_TESTS();

    return result;
}
<commit_msg>reduced buffer size to fit CI<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 */

#include <numeric>
#include <thread>

#include <adios2.h>
#include <adios2/common/ADIOSMacros.h>
#include <adios2/helper/adiosFunctions.h>
#include <gtest/gtest.h>

using namespace adios2;

size_t print_lines = 0;
size_t to_print_lines = 10;

template <class T>
void GenData(std::vector<std::complex<T>> &data, const size_t step)
{
    for (size_t i = 0; i < data.size(); ++i)
    {
        data[i] = {static_cast<T>(i + 10000 + step * 100),
                   static_cast<T>(i + 10000)};
    }
}

template <class T>
void GenData(std::vector<T> &data, const size_t step)
{
    for (size_t i = 0; i < data.size(); ++i)
    {
        data[i] = i + 10000 + step * 100;
    }
}

template <class T>
void PrintData(const T *data, const size_t size, const size_t step)
{
    std::cout << "Step: " << step << " [";
    size_t printsize = 32;
    if (size < printsize)
    {
        printsize = size;
    }
    for (size_t i = 0; i < printsize; ++i)
    {
        std::cout << data[i] << " ";
    }
    std::cout << "]" << std::endl;
}

template <class T>
void VerifyData(const std::complex<T> *data, const size_t size, size_t step)
{
    std::vector<std::complex<T>> tmpdata(size);
    GenData(tmpdata, step);
    for (size_t i = 0; i < size; ++i)
    {
        ASSERT_EQ(data[i], tmpdata[i]);
    }
}

template <class T>
void VerifyData(const T *data, const size_t size, size_t step)
{
    std::vector<T> tmpdata(size);
    GenData(tmpdata, step);
    for (size_t i = 0; i < size; ++i)
    {
        ASSERT_EQ(data[i], tmpdata[i]);
    }
}

template <class T>
void VerifyData(const std::vector<T> &data, const size_t step)
{
    VerifyData(data.data(), data.size(), step);
}

void DataManWriter(const Dims &shape, const Dims &start, const Dims &count,
                   const size_t steps, const adios2::Params &engineParams)
{
    size_t datasize = std::accumulate(count.begin(), count.end(), 1,
                                      std::multiplies<size_t>());
    adios2::ADIOS adios;
    adios2::IO dataManIO = adios.DeclareIO("WAN");
    dataManIO.SetEngine("DataMan");
    dataManIO.SetParameters(engineParams);
    std::vector<char> myChars(datasize);
    std::vector<unsigned char> myUChars(datasize);
    std::vector<short> myShorts(datasize);
    std::vector<unsigned short> myUShorts(datasize);
    std::vector<int> myInts(datasize);
    std::vector<unsigned int> myUInts(datasize);
    std::vector<float> myFloats(datasize);
    std::vector<double> myDoubles(datasize);
    std::vector<std::complex<float>> myComplexes(datasize);
    std::vector<std::complex<double>> myDComplexes(datasize);
    auto bpChars =
        dataManIO.DefineVariable<char>("bpChars", shape, start, count);
    auto bpUChars = dataManIO.DefineVariable<unsigned char>("bpUChars", shape,
                                                            start, count);
    auto bpShorts =
        dataManIO.DefineVariable<short>("bpShorts", shape, start, count);
    auto bpUShorts = dataManIO.DefineVariable<unsigned short>(
        "bpUShorts", shape, start, count);
    auto bpInts = dataManIO.DefineVariable<int>("bpInts", shape, start, count);
    auto bpUInts =
        dataManIO.DefineVariable<unsigned int>("bpUInts", shape, start, count);
    auto bpFloats =
        dataManIO.DefineVariable<float>("bpFloats", shape, start, count);
    auto bpDoubles =
        dataManIO.DefineVariable<double>("bpDoubles", shape, start, count);
    auto bpComplexes = dataManIO.DefineVariable<std::complex<float>>(
        "bpComplexes", shape, start, count);
    auto bpDComplexes = dataManIO.DefineVariable<std::complex<double>>(
        "bpDComplexes", shape, start, count);
    auto bpUInt64s = dataManIO.DefineVariable<uint64_t>("bpUInt64s");
    dataManIO.DefineAttribute<int>("AttInt", 110);
    adios2::Engine dataManWriter =
        dataManIO.Open("stream", adios2::Mode::Write);
    for (uint64_t i = 0; i < steps; ++i)
    {
        dataManWriter.BeginStep();
        GenData(myChars, i);
        GenData(myUChars, i);
        GenData(myShorts, i);
        GenData(myUShorts, i);
        GenData(myInts, i);
        GenData(myUInts, i);
        GenData(myFloats, i);
        GenData(myDoubles, i);
        GenData(myComplexes, i);
        GenData(myDComplexes, i);
        dataManWriter.Put(bpChars, myChars.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpUChars, myUChars.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpShorts, myShorts.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpInts, myInts.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpUInts, myUInts.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpFloats, myFloats.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync);
        dataManWriter.Put(bpDComplexes, myDComplexes.data(),
                          adios2::Mode::Sync);
        dataManWriter.Put(bpUInt64s, i);
        dataManWriter.EndStep();
    }
    dataManWriter.Close();
}

void DataManReader(const Dims &shape, const Dims &start, const Dims &count,
                   const size_t steps, const adios2::Params &engineParams)
{
    size_t datasize = std::accumulate(count.begin(), count.end(), 1,
                                      std::multiplies<size_t>());
    adios2::ADIOS adios;
    adios2::IO dataManIO = adios.DeclareIO("WAN");
    dataManIO.SetEngine("DataMan");
    dataManIO.SetParameters(engineParams);
    adios2::Engine dataManReader = dataManIO.Open("stream", adios2::Mode::Read);

    std::vector<char> myChars(datasize);
    std::vector<unsigned char> myUChars(datasize);
    std::vector<short> myShorts(datasize);
    std::vector<unsigned short> myUShorts(datasize);
    std::vector<int> myInts(datasize);
    std::vector<unsigned int> myUInts(datasize);
    std::vector<float> myFloats(datasize);
    std::vector<double> myDoubles(datasize);
    std::vector<std::complex<float>> myComplexes(datasize);
    std::vector<std::complex<double>> myDComplexes(datasize);
    bool received_steps = false;
    size_t currentStep;
    while (true)
    {
        adios2::StepStatus status = dataManReader.BeginStep(StepMode::Read, 5);
        if (status == adios2::StepStatus::OK)
        {
            received_steps = true;
            const auto &vars = dataManIO.AvailableVariables();
            ASSERT_EQ(vars.size(), 11);
            currentStep = dataManReader.CurrentStep();
            adios2::Variable<char> bpChars =
                dataManIO.InquireVariable<char>("bpChars");
            adios2::Variable<unsigned char> bpUChars =
                dataManIO.InquireVariable<unsigned char>("bpUChars");
            adios2::Variable<short> bpShorts =
                dataManIO.InquireVariable<short>("bpShorts");
            adios2::Variable<unsigned short> bpUShorts =
                dataManIO.InquireVariable<unsigned short>("bpUShorts");
            adios2::Variable<int> bpInts =
                dataManIO.InquireVariable<int>("bpInts");
            adios2::Variable<unsigned int> bpUInts =
                dataManIO.InquireVariable<unsigned int>("bpUInts");
            adios2::Variable<float> bpFloats =
                dataManIO.InquireVariable<float>("bpFloats");
            adios2::Variable<double> bpDoubles =
                dataManIO.InquireVariable<double>("bpDoubles");
            adios2::Variable<std::complex<float>> bpComplexes =
                dataManIO.InquireVariable<std::complex<float>>("bpComplexes");
            adios2::Variable<std::complex<double>> bpDComplexes =
                dataManIO.InquireVariable<std::complex<double>>("bpDComplexes");
            adios2::Variable<uint64_t> bpUInt64s =
                dataManIO.InquireVariable<uint64_t>("bpUInt64s");
            auto charsBlocksInfo = dataManReader.AllStepsBlocksInfo(bpChars);
            bpChars.SetSelection({start, count});
            bpUChars.SetSelection({start, count});
            bpShorts.SetSelection({start, count});
            bpUShorts.SetSelection({start, count});
            bpInts.SetSelection({start, count});
            bpUInts.SetSelection({start, count});
            bpFloats.SetSelection({start, count});
            bpDoubles.SetSelection({start, count});
            bpComplexes.SetSelection({start, count});
            bpDComplexes.SetSelection({start, count});
            dataManReader.Get(bpChars, myChars.data(), adios2::Mode::Sync);
            dataManReader.Get(bpUChars, myUChars.data(), adios2::Mode::Sync);
            dataManReader.Get(bpShorts, myShorts.data(), adios2::Mode::Sync);
            dataManReader.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
            dataManReader.Get(bpInts, myInts.data(), adios2::Mode::Sync);
            dataManReader.Get(bpUInts, myUInts.data(), adios2::Mode::Sync);
            dataManReader.Get(bpFloats, myFloats.data(), adios2::Mode::Sync);
            dataManReader.Get(bpDoubles, myDoubles.data(), adios2::Mode::Sync);
            dataManReader.Get(bpComplexes, myComplexes.data(),
                              adios2::Mode::Sync);
            dataManReader.Get(bpDComplexes, myDComplexes.data(),
                              adios2::Mode::Sync);
            uint64_t stepValue;
            dataManReader.Get(bpUInt64s, &stepValue, adios2::Mode::Sync);
            ASSERT_EQ(currentStep, stepValue);
            VerifyData(myChars, currentStep);
            VerifyData(myUChars, currentStep);
            VerifyData(myShorts, currentStep);
            VerifyData(myUShorts, currentStep);
            VerifyData(myInts, currentStep);
            VerifyData(myUInts, currentStep);
            VerifyData(myFloats, currentStep);
            VerifyData(myDoubles, currentStep);
            VerifyData(myComplexes, currentStep);
            VerifyData(myDComplexes, currentStep);
            dataManReader.EndStep();
        }
        else if (status == adios2::StepStatus::EndOfStream)
        {
            break;
        }
        else if (status == adios2::StepStatus::NotReady)
        {
            continue;
        }
    }
    if (received_steps)
    {
        auto attInt = dataManIO.InquireAttribute<int>("AttInt");
        ASSERT_EQ(110, attInt.Data()[0]);
        ASSERT_NE(111, attInt.Data()[0]);
    }
    dataManReader.Close();
}

class DataManEngineTest : public ::testing::Test
{
public:
    DataManEngineTest() = default;
};

#ifdef ADIOS2_HAVE_ZEROMQ
TEST_F(DataManEngineTest, 1DSuperLarge)
{
    // set parameters
    Dims shape = {200000};
    Dims start = {0};
    Dims count = {200000};
    size_t steps = 10;

    // run workflow
    adios2::Params readerEngineParams = {{"IPAddress", "127.0.0.1"},
                                         {"Port", "13480"},
                                         {"MaxStepBufferSize", "20000000"},
                                         {"TransportMode", "reliable"}};
    auto r = std::thread(DataManReader, shape, start, count, steps,
                         readerEngineParams);
    adios2::Params writerEngineParams = {{"IPAddress", "127.0.0.1"},
                                         {"Port", "13480"},
                                         {"TransportMode", "reliable"}};
    auto w = std::thread(DataManWriter, shape, start, count, steps,
                         writerEngineParams);
    w.join();
    r.join();
}
#endif // ZEROMQ

int main(int argc, char **argv)
{
    int result;
    ::testing::InitGoogleTest(&argc, argv);
    result = RUN_ALL_TESTS();

    return result;
}
<|endoftext|>


<commit_before>/*
* Copyright (c) 2007-2012 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"

#include "../stack_array.h"

#include "GlyphRunDW.h"

using namespace System;

namespace SlimDX
{
namespace DirectWrite
{
	GlyphRun::GlyphRun(const DWRITE_GLYPH_RUN &run)
	{
		FontFace = DirectWrite::FontFace::FromPointer(run.fontFace);
		FontSize = run.fontEmSize;
		GlyphCount = run.glyphCount;
		IsSideways = run.isSideways != 0;
		BidiLevel = run.bidiLevel;

		GlyphIndices = gcnew array<short>(GlyphCount);
		GlyphAdvances = gcnew array<float>(GlyphCount);
		GlyphOffsets = gcnew array<GlyphOffset>(GlyphCount);

		for (int i = 0; i < GlyphCount; i++)
		{
			GlyphIndices[i] = run.glyphIndices[i];
			GlyphAdvances[i] = run.glyphAdvances[i];
			GlyphOffsets[i].AdvanceOffset = run.glyphOffsets[i].advanceOffset;
			GlyphOffsets[i].AscenderOffset = run.glyphOffsets[i].ascenderOffset;
		}
	}

	DWRITE_GLYPH_RUN GlyphRun::ToUnmanaged(stack_array<UINT16> &indices, stack_array<FLOAT> &advances, stack_array<DWRITE_GLYPH_OFFSET> &offsets)
	{
		DWRITE_GLYPH_RUN result;

		result.fontFace = FontFace->InternalPointer;
		result.fontEmSize = FontSize;
		result.glyphCount = GlyphCount;
		result.isSideways = IsSideways;
		result.bidiLevel = BidiLevel;
		result.glyphIndices = NULL;
		result.glyphAdvances = NULL;
		result.glyphOffsets = NULL;

		if (GlyphIndices != nullptr && GlyphIndices->Length > 0)
		{
			pin_ptr<short> pinnedIndices = &GlyphIndices[0];
			memcpy(&indices[0], pinnedIndices, sizeof(short) * GlyphIndices->Length);
			result.glyphIndices = &indices[0];
		}

		if (GlyphAdvances != nullptr && GlyphAdvances->Length > 0)
		{
			pin_ptr<float> pinnedAdvances = &GlyphAdvances[0];
			memcpy(&advances[0], pinnedAdvances, sizeof(float) * GlyphAdvances->Length);
			result.glyphAdvances = &advances[0];
		}

		if (GlyphOffsets != nullptr && GlyphOffsets->Length > 0)
		{
			pin_ptr<GlyphOffset> pinnedOffsets = &GlyphOffsets[0];
			memcpy(&offsets[0], pinnedOffsets, sizeof(DWRITE_GLYPH_OFFSET) * GlyphOffsets->Length);
			result.glyphOffsets = &offsets[0];
		}

		return result;
	}
}
}
<commit_msg>Grrrr.<commit_after>/*
* Copyright (c) 2007-2012 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"

#include "../stack_array.h"

#include "GlyphRunDW.h"

using namespace System;

namespace SlimDX
{
namespace DirectWrite
{
	GlyphRun::GlyphRun(const DWRITE_GLYPH_RUN &run)
	{
		run.fontFace->AddRef();
		FontFace = DirectWrite::FontFace::FromPointer(run.fontFace);
		FontSize = run.fontEmSize;
		GlyphCount = run.glyphCount;
		IsSideways = run.isSideways != 0;
		BidiLevel = run.bidiLevel;

		GlyphIndices = gcnew array<short>(GlyphCount);
		GlyphAdvances = gcnew array<float>(GlyphCount);
		GlyphOffsets = gcnew array<GlyphOffset>(GlyphCount);

		for (int i = 0; i < GlyphCount; i++)
		{
			GlyphIndices[i] = run.glyphIndices[i];
			GlyphAdvances[i] = run.glyphAdvances[i];
			GlyphOffsets[i].AdvanceOffset = run.glyphOffsets[i].advanceOffset;
			GlyphOffsets[i].AscenderOffset = run.glyphOffsets[i].ascenderOffset;
		}
	}

	DWRITE_GLYPH_RUN GlyphRun::ToUnmanaged(stack_array<UINT16> &indices, stack_array<FLOAT> &advances, stack_array<DWRITE_GLYPH_OFFSET> &offsets)
	{
		DWRITE_GLYPH_RUN result;

		result.fontFace = FontFace->InternalPointer;
		result.fontEmSize = FontSize;
		result.glyphCount = GlyphCount;
		result.isSideways = IsSideways;
		result.bidiLevel = BidiLevel;
		result.glyphIndices = NULL;
		result.glyphAdvances = NULL;
		result.glyphOffsets = NULL;

		if (GlyphIndices != nullptr && GlyphIndices->Length > 0)
		{
			pin_ptr<short> pinnedIndices = &GlyphIndices[0];
			memcpy(&indices[0], pinnedIndices, sizeof(short) * GlyphIndices->Length);
			result.glyphIndices = &indices[0];
		}

		if (GlyphAdvances != nullptr && GlyphAdvances->Length > 0)
		{
			pin_ptr<float> pinnedAdvances = &GlyphAdvances[0];
			memcpy(&advances[0], pinnedAdvances, sizeof(float) * GlyphAdvances->Length);
			result.glyphAdvances = &advances[0];
		}

		if (GlyphOffsets != nullptr && GlyphOffsets->Length > 0)
		{
			pin_ptr<GlyphOffset> pinnedOffsets = &GlyphOffsets[0];
			memcpy(&offsets[0], pinnedOffsets, sizeof(DWRITE_GLYPH_OFFSET) * GlyphOffsets->Length);
			result.glyphOffsets = &offsets[0];
		}

		return result;
	}
}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: addonmenu.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-25 18:19:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef __FRAMEWORK_CLASSES_ADDONMENU_HXX_
#define __FRAMEWORK_CLASSES_ADDONMENU_HXX_

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <vcl/menu.hxx>
#include <vcl/image.hxx>

class String;
class ImageList;

#define ADDONMENU_ITEMID_START    20000

namespace framework
{

class AddonMenu_Impl;
class AddonMenu : public PopupMenu
{
    public:
                        AddonMenu( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );
                        ~AddonMenu();

        void            Initialize(); // Synchrones Laden der Eintraege

        static sal_Bool HasElements();

    protected:
        USHORT          CreateMenuId();

    private:
                        AddonMenu( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, AddonMenu* pRoot );
                        PopupMenu* BuildSubMenu( ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > aAddonSubMenuDefinition );

        AddonMenu_Impl* _pImp;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& m_xFrame;
};

class AddonPopupMenu : public PopupMenu
{
    public:
                                ~AddonPopupMenu();

        const rtl::OUString&    GetContext() const { return m_aContext; }
        const rtl::OUString&    GetCommandURL() const { return m_aCommandURL; }
        const rtl::OUString&    GetTitle() const { return m_aTitle; }
        USHORT                  GetId() const { return m_nId; }

        // Get the top-level popup menus for addons. The menubar is used as a container. Every popup menu is from type AddonPopupMenu!
        static void             GetAddonPopupMenus( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                                                    MenuBar* pAddonPopupMenus );

        // Merge the addon popup menus into the given menu bar at the provided pos.
        static void             MergeAddonPopupMenus( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                                                      ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& rModel,
                                                      USHORT                nMergeAtPos,
                                                      MenuBar*              pMergeMenuBar );

    protected:
        void                    Initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rAddonPopupMenuDefinition );
        USHORT                  CreateMenuId();
        sal_Bool                IsCorrectContext( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& rModel ) const;

    private:
                                AddonPopupMenu( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );

        PopupMenu*              BuildSubMenu( ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > aAddonSubMenuDefinition );

        USHORT                                                                  m_nId;
        rtl::OUString                                                           m_aCommandURL;
        rtl::OUString                                                           m_aTitle;
        rtl::OUString                                                           m_aContext;
        AddonMenu_Impl*                                                         _pImp;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >&    m_xFrame;
};

} // namespace framework

#endif // #ifndef __FRAMEWORK_CLASSES_ADDONMENU_HXX_
<commit_msg>INTEGRATION: CWS fwk01 (1.1.2.1.6); FILE MERGED 2003/03/19 13:10:50 cd 1.1.2.1.6.5: #107568# Support Add-On help menu items directly in the Office help menu 2003/03/17 09:22:05 cd 1.1.2.1.6.4: #107568# Support context for all items 2003/03/10 14:02:54 cd 1.1.2.1.6.3: #107568# Added support for Add-Ons help integration 2003/03/07 09:28:28 cd 1.1.2.1.6.2: #107568# Support extended Add-Ons configuration format 2003/02/27 07:26:23 cd 1.1.2.1.6.1: #107568# Top-level addon popup menus shouldn't be stored or configured by the user<commit_after>/*************************************************************************
 *
 *  $RCSfile: addonmenu.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2003-04-04 17:11:47 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef __FRAMEWORK_CLASSES_ADDONMENU_HXX_
#define __FRAMEWORK_CLASSES_ADDONMENU_HXX_

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <vcl/menu.hxx>

#define ADDONMENU_ITEMID_START    1500
#define ADDONMENU_ITEMID_END      2000

namespace framework
{

class AddonMenu : public PopupMenu
{
    public:
                        AddonMenu( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );
                        ~AddonMenu();

    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& m_xFrame;
};

class AddonMenuManager;
class AddonPopupMenu : public PopupMenu
{
    public:
                                ~AddonPopupMenu();

        // Check if command URL string has the unique prefix to identify addon popup menus
        static sal_Bool         IsCommandURLPrefix( const rtl::OUString& aCmdURL );

        void                    SetCommandURL( const rtl::OUString& aCmdURL ) { m_aCommandURL = aCmdURL; }
        const rtl::OUString&    GetCommandURL() const { return m_aCommandURL; }

    protected:
        void                    Initialize( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rAddonPopupMenuDefinition );

    private:
                                AddonPopupMenu( com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame );

        rtl::OUString                                                       m_aCommandURL;
        ::com::sun::star::uno::Reference< com::sun::star::frame::XFrame >&  m_xFrame;

    friend AddonMenuManager;
};

class AddonMenuManager
{
    public:
        enum MenuType
        {
            ADDON_MENU,
            ADDON_POPUPMENU
        };

        static sal_Bool   HasAddonMenuElements();
        static sal_Bool   HasAddonHelpMenuElements();

        static sal_Bool   IsAddonMenuId( USHORT nId ) { return (( nId >= ADDONMENU_ITEMID_START ) && ( nId < ADDONMENU_ITEMID_END )); }

        // Check if the context string matches the provided xModel context
        static sal_Bool   IsCorrectContext( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& rModel, const rtl::OUString& aContext );

        // Factory method to create different Add-On menu types
        static PopupMenu* CreatePopupMenuType( MenuType eMenuType, com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame );

        // Create the Add-Ons menu
        static AddonMenu* CreateAddonMenu( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );

        // Merge the Add-Ons help menu items into the given menu bar at a defined pos
        static void       MergeAddonHelpMenu( com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
                                              MenuBar* pMergeMenuBar );

        // Merge the addon popup menus into the given menu bar at the provided pos.
        static void       MergeAddonPopupMenus( com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
                                                com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel,
                                                USHORT   nMergeAtPos,
                                                MenuBar* pMergeMenuBar );

        // Returns the next position to insert a menu item/sub menu
        static USHORT     GetNextPos( USHORT nPos );

        // Build up the menu item and sub menu into the provided pCurrentMenu. The sub menus should be of type nSubMenuType.
        static void       BuildMenu( PopupMenu*  pCurrentMenu,
                                     MenuType    nSubMenuType,
                                     USHORT      nInsPos,
                                     USHORT&     nUniqueMenuId,
                                     com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > > aAddonMenuDefinition,
                                     com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
                                     com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel );

        // Retrieve the menu entry property values from a sequence
        static void       GetMenuEntry( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rAddonMenuEntry,
                                        ::rtl::OUString& rTitle,
                                        ::rtl::OUString& rURL,
                                        ::rtl::OUString& rTarget,
                                        ::rtl::OUString& rImageId,
                                        ::rtl::OUString& rContext,
                                        com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rAddonSubMenu );
};

} // namespace framework

#endif // #ifndef __FRAMEWORK_CLASSES_ADDONMENU_HXX_
<|endoftext|>


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

 The Medical Imaging Interaction Toolkit (MITK)

 Copyright (c) German Cancer Research Center,
 Division of Medical and Biological Informatics.
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without
 even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.

 See LICENSE.txt or http://www.mitk.org for details.

 ===================================================================*/

#include "mitkEventRecorder.h"
#include "mitkEventFactory.h"
#include "mitkInteractionEvent.h"

mitk::EventRecorder::EventRecorder()
  : m_Active(false)
{
}

mitk::EventRecorder::~EventRecorder()
{
  if (m_FileStream.is_open())
  {
    m_FileStream.flush();
    m_FileStream.close();
  }
}

void mitk::EventRecorder::Notify(mitk::InteractionEvent *interactionEvent, bool /*isHandled*/)
{
  std::cout << EventFactory::EventToXML(interactionEvent) << "\n";
  if (m_FileStream.is_open())
    m_FileStream << EventFactory::EventToXML(interactionEvent) << "\n";
}

void mitk::EventRecorder::SetEventIgnoreList(std::vector<std::string> list)
{
  m_IgnoreList = list;
}

void mitk::EventRecorder::StartRecording()
{
  if (m_FileName == "")
  {
    MITK_ERROR << "EventRecorder::StartRecording - Filename needs to be set first.";
    return;
  }
  if (m_FileStream.is_open())
  {
    MITK_ERROR << "EventRecorder::StartRecording - Still recording. Stop recording before starting it again.";
    return;
  }

  m_FileStream.open(m_FileName.c_str(), std::ofstream::out );
  if ( !m_FileStream.good() )
  {
    MITK_ERROR << "File " << m_FileName << " could not be opened!";
    m_FileStream.close();
    return ;
  }
}

void mitk::EventRecorder::StopRecording()
{
  if (m_FileStream.is_open())
  {
    m_FileStream.flush();
    m_FileStream.close();
  }
}
<commit_msg>Opening and closing tag in xml file<commit_after>/*===================================================================

 The Medical Imaging Interaction Toolkit (MITK)

 Copyright (c) German Cancer Research Center,
 Division of Medical and Biological Informatics.
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without
 even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.

 See LICENSE.txt or http://www.mitk.org for details.

 ===================================================================*/

#include "mitkEventRecorder.h"
#include "mitkEventFactory.h"
#include "mitkInteractionEvent.h"

mitk::EventRecorder::EventRecorder()
  : m_Active(false)
{
}

mitk::EventRecorder::~EventRecorder()
{
  if (m_FileStream.is_open())
  {
    m_FileStream.flush();
    m_FileStream.close();
  }
}

void mitk::EventRecorder::Notify(mitk::InteractionEvent *interactionEvent, bool /*isHandled*/)
{
  std::cout << EventFactory::EventToXML(interactionEvent) << "\n";
  if (m_FileStream.is_open())
    m_FileStream << EventFactory::EventToXML(interactionEvent) << "\n";
}

void mitk::EventRecorder::SetEventIgnoreList(std::vector<std::string> list)
{
  m_IgnoreList = list;
}

void mitk::EventRecorder::StartRecording()
{
  if (m_FileName == "")
  {
    MITK_ERROR << "EventRecorder::StartRecording - Filename needs to be set first.";
    return;
  }
  if (m_FileStream.is_open())
  {
    MITK_ERROR << "EventRecorder::StartRecording - Still recording. Stop recording before starting it again.";
    return;
  }

  m_FileStream.open(m_FileName.c_str(), std::ofstream::out );
  if ( !m_FileStream.good() )
  {
    MITK_ERROR << "File " << m_FileName << " could not be opened!";
    m_FileStream.close();
    return ;
  }

  //write open tag
  m_FileStream << "<events>\n";
}

void mitk::EventRecorder::StopRecording()
{
  if (m_FileStream.is_open())
  {
    //write end tag
    m_FileStream << "</events>\n";

    m_FileStream.flush();
    m_FileStream.close();
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/gpu/gpu_process_host_ui_shim.h"

#include <algorithm>

#include "base/id_map.h"
#include "base/process_util.h"
#include "base/debug/trace_event.h"
#include "base/lazy_instance.h"
#include "content/browser/browser_thread.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/common/gpu/gpu_messages.h"

#if defined(TOOLKIT_USES_GTK)
// These two #includes need to come after gpu_messages.h.
#include <gdk/gdkwindow.h>  // NOLINT
#include <gdk/gdkx.h>  // NOLINT
#include "ui/base/x/x11_util.h"
#include "ui/gfx/size.h"
#endif
namespace {

// One of the linux specific headers defines this as a macro.
#ifdef DestroyAll
#undef DestroyAll
#endif

base::LazyInstance<IDMap<GpuProcessHostUIShim> > g_hosts_by_id(
    base::LINKER_INITIALIZED);

class SendOnIOThreadTask : public Task {
 public:
  SendOnIOThreadTask(int host_id, IPC::Message* msg)
      : host_id_(host_id),
        msg_(msg) {
  }

 private:
  void Run() {
    GpuProcessHost* host = GpuProcessHost::FromID(host_id_);
    if (host)
      host->Send(msg_.release());
  }

  int host_id_;
  scoped_ptr<IPC::Message> msg_;
};

}  // namespace

RouteToGpuProcessHostUIShimTask::RouteToGpuProcessHostUIShimTask(
    int host_id,
    const IPC::Message& msg)
  : host_id_(host_id),
    msg_(msg) {
}

RouteToGpuProcessHostUIShimTask::~RouteToGpuProcessHostUIShimTask() {
}

void RouteToGpuProcessHostUIShimTask::Run() {
  GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(host_id_);
  if (ui_shim)
    ui_shim->OnMessageReceived(msg_);
}

GpuProcessHostUIShim::GpuProcessHostUIShim(int host_id)
    : host_id_(host_id) {
  g_hosts_by_id.Pointer()->AddWithID(this, host_id_);
}

// static
GpuProcessHostUIShim* GpuProcessHostUIShim::Create(int host_id) {
  DCHECK(!FromID(host_id));
  return new GpuProcessHostUIShim(host_id);
}

// static
void GpuProcessHostUIShim::Destroy(int host_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  delete FromID(host_id);
}

// static
void GpuProcessHostUIShim::DestroyAll() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  while (!g_hosts_by_id.Pointer()->IsEmpty()) {
    IDMap<GpuProcessHostUIShim>::iterator it(g_hosts_by_id.Pointer());
    delete it.GetCurrentValue();
  }
}

// static
GpuProcessHostUIShim* GpuProcessHostUIShim::FromID(int host_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return g_hosts_by_id.Pointer()->Lookup(host_id);
}

bool GpuProcessHostUIShim::Send(IPC::Message* msg) {
  DCHECK(CalledOnValidThread());
  return BrowserThread::PostTask(BrowserThread::IO,
                                 FROM_HERE,
                                 new SendOnIOThreadTask(host_id_, msg));
}

bool GpuProcessHostUIShim::OnMessageReceived(const IPC::Message& message) {
  DCHECK(CalledOnValidThread());

  if (message.routing_id() != MSG_ROUTING_CONTROL)
    return false;

  return OnControlMessageReceived(message);
}

#if defined(OS_MACOSX)

void GpuProcessHostUIShim::DidDestroyAcceleratedSurface(int renderer_id,
                                                        int render_view_id) {
  // Destroy the command buffer that owns the accelerated surface.
  Send(new GpuMsg_DestroyCommandBuffer(renderer_id, render_view_id));
}

void GpuProcessHostUIShim::SendToGpuHost(int host_id, IPC::Message* msg) {
  GpuProcessHostUIShim* ui_shim = FromID(host_id);
  if (!ui_shim)
    return;

  ui_shim->Send(msg);
}

#endif

GpuProcessHostUIShim::~GpuProcessHostUIShim() {
  DCHECK(CalledOnValidThread());
  g_hosts_by_id.Pointer()->Remove(host_id_);
}

bool GpuProcessHostUIShim::OnControlMessageReceived(
    const IPC::Message& message) {
  DCHECK(CalledOnValidThread());

  IPC_BEGIN_MESSAGE_MAP(GpuProcessHostUIShim, message)
    IPC_MESSAGE_HANDLER(GpuHostMsg_OnLogMessage,
                        OnLogMessage)
#if defined(TOOLKIT_USES_GTK) && !defined(TOUCH_UI) || defined(OS_WIN)
    IPC_MESSAGE_HANDLER(GpuHostMsg_ResizeView, OnResizeView)
#endif

#if defined(OS_MACOSX) || defined(TOUCH_UI)
    IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceSetIOSurface,
                        OnAcceleratedSurfaceSetIOSurface)
    IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
                        OnAcceleratedSurfaceBuffersSwapped)
#endif

#if defined(TOUCH_UI)
    IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceRelease,
                        OnAcceleratedSurfaceRelease)
#endif
    IPC_MESSAGE_UNHANDLED_ERROR()
  IPC_END_MESSAGE_MAP()

  return true;
}

void GpuProcessHostUIShim::OnLogMessage(
    int level,
    const std::string& header,
    const std::string& message) {
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger("level", level);
  dict->SetString("header", header);
  dict->SetString("message", message);
  GpuDataManager::GetInstance()->AddLogMessage(dict);
}

#if defined(TOOLKIT_USES_GTK) && !defined(TOUCH_UI) || defined(OS_WIN)

void GpuProcessHostUIShim::OnResizeView(int32 renderer_id,
                                        int32 render_view_id,
                                        int32 command_buffer_route_id,
                                        gfx::Size size) {
  RenderViewHost* host = RenderViewHost::FromID(renderer_id, render_view_id);
  if (host) {
    RenderWidgetHostView* view = host->view();
    if (view) {
      gfx::PluginWindowHandle handle = view->GetCompositingSurface();

      // Resize the window synchronously. The GPU process must not issue GL
      // calls on the command buffer until the window is the size it expects it
      // to be.
#if defined(TOOLKIT_USES_GTK) && !defined(TOUCH_UI)
      GdkWindow* window = reinterpret_cast<GdkWindow*>(
          gdk_xid_table_lookup(handle));
      if (window) {
        Display* display = GDK_WINDOW_XDISPLAY(window);
        gdk_window_resize(window, size.width(), size.height());
        XSync(display, False);
      }
#elif defined(OS_WIN)
      // Ensure window does not have zero area because D3D cannot create a zero
      // area swap chain.
      SetWindowPos(handle,
          NULL,
          0, 0,
          std::max(1, size.width()),
          std::max(1, size.height()),
          SWP_NOSENDCHANGING | SWP_NOCOPYBITS | SWP_NOZORDER |
              SWP_NOACTIVATE | SWP_DEFERERASE);
#endif
    }
  }

  // Always respond even if the window no longer exists. The GPU process cannot
  // make progress on the resizing command buffer until it receives the
  // response.
  Send(new GpuMsg_ResizeViewACK(renderer_id, command_buffer_route_id));
}

#endif

#if defined(OS_MACOSX) || defined(TOUCH_UI)

void GpuProcessHostUIShim::OnAcceleratedSurfaceSetIOSurface(
    const GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params& params) {
  RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
                                                params.render_view_id);
  if (!host)
    return;
  RenderWidgetHostView* view = host->view();
  if (!view)
    return;
#if defined(OS_MACOSX)
  view->AcceleratedSurfaceSetIOSurface(params.window,
                                       params.width,
                                       params.height,
                                       params.identifier);
#elif defined(TOUCH_UI)
  view->AcceleratedSurfaceSetIOSurface(
      params.width, params.height, params.identifier);
  Send(new AcceleratedSurfaceMsg_SetSurfaceACK(
      params.route_id, params.identifier));
#endif
}

void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped(
    const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
  TRACE_EVENT0("renderer",
      "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped");
  RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
                                                params.render_view_id);
  if (!host)
    return;
  RenderWidgetHostView* view = host->view();
  if (!view)
    return;
#if defined (OS_MACOSX)
  view->AcceleratedSurfaceBuffersSwapped(
      // Parameters needed to swap the IOSurface.
      params.window,
      params.surface_id,
      // Parameters needed to formulate an acknowledgment.
      params.renderer_id,
      params.route_id,
      host_id_,
      params.swap_buffers_count);
#elif defined(TOUCH_UI)
  view->AcceleratedSurfaceBuffersSwapped(params.surface_id);
  Send(new AcceleratedSurfaceMsg_BuffersSwappedACK(params.route_id));
#endif
}

#endif

#if defined(TOUCH_UI)

void GpuProcessHostUIShim::OnAcceleratedSurfaceRelease(
    const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) {
  RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
                                                params.render_view_id);
  if (!host)
    return;
  RenderWidgetHostView* view = host->view();
  if (!view)
    return;
  view->AcceleratedSurfaceRelease(params.identifier);
}

#endif
<commit_msg>Bug=None Test=None<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/gpu/gpu_process_host_ui_shim.h"

#include <algorithm>

#include "base/id_map.h"
#include "base/process_util.h"
#include "base/debug/trace_event.h"
#include "base/lazy_instance.h"
#include "content/browser/browser_thread.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/common/gpu/gpu_messages.h"

#if defined(TOOLKIT_USES_GTK)
// These two #includes need to come after gpu_messages.h.
#include <gdk/gdkwindow.h>  // NOLINT
#include <gdk/gdkx.h>  // NOLINT
#include "ui/base/x/x11_util.h"
#include "ui/gfx/size.h"
#endif
namespace {

// One of the linux specific headers defines this as a macro.
#ifdef DestroyAll
#undef DestroyAll
#endif

base::LazyInstance<IDMap<GpuProcessHostUIShim> > g_hosts_by_id(
    base::LINKER_INITIALIZED);

class SendOnIOThreadTask : public Task {
 public:
  SendOnIOThreadTask(int host_id, IPC::Message* msg)
      : host_id_(host_id),
        msg_(msg) {
  }

 private:
  void Run() {
    GpuProcessHost* host = GpuProcessHost::FromID(host_id_);
    if (host)
      host->Send(msg_.release());
  }

  int host_id_;
  scoped_ptr<IPC::Message> msg_;
};

}  // namespace

RouteToGpuProcessHostUIShimTask::RouteToGpuProcessHostUIShimTask(
    int host_id,
    const IPC::Message& msg)
  : host_id_(host_id),
    msg_(msg) {
}

RouteToGpuProcessHostUIShimTask::~RouteToGpuProcessHostUIShimTask() {
}

void RouteToGpuProcessHostUIShimTask::Run() {
  GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(host_id_);
  if (ui_shim)
    ui_shim->OnMessageReceived(msg_);
}

GpuProcessHostUIShim::GpuProcessHostUIShim(int host_id)
    : host_id_(host_id) {
  g_hosts_by_id.Pointer()->AddWithID(this, host_id_);
}

// static
GpuProcessHostUIShim* GpuProcessHostUIShim::Create(int host_id) {
  DCHECK(!FromID(host_id));
  return new GpuProcessHostUIShim(host_id);
}

// static
void GpuProcessHostUIShim::Destroy(int host_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  delete FromID(host_id);
}

// static
void GpuProcessHostUIShim::DestroyAll() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  while (!g_hosts_by_id.Pointer()->IsEmpty()) {
    IDMap<GpuProcessHostUIShim>::iterator it(g_hosts_by_id.Pointer());
    delete it.GetCurrentValue();
  }
}

// static
GpuProcessHostUIShim* GpuProcessHostUIShim::FromID(int host_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return g_hosts_by_id.Pointer()->Lookup(host_id);
}

bool GpuProcessHostUIShim::Send(IPC::Message* msg) {
  DCHECK(CalledOnValidThread());
  return BrowserThread::PostTask(BrowserThread::IO,
                                 FROM_HERE,
                                 new SendOnIOThreadTask(host_id_, msg));
}

bool GpuProcessHostUIShim::OnMessageReceived(const IPC::Message& message) {
  DCHECK(CalledOnValidThread());

  if (message.routing_id() != MSG_ROUTING_CONTROL)
    return false;

  return OnControlMessageReceived(message);
}

#if defined(OS_MACOSX)

void GpuProcessHostUIShim::DidDestroyAcceleratedSurface(int renderer_id,
                                                        int render_view_id) {
  // Destroy the command buffer that owns the accelerated surface.
  Send(new GpuMsg_DestroyCommandBuffer(renderer_id, render_view_id));
}

void GpuProcessHostUIShim::SendToGpuHost(int host_id, IPC::Message* msg) {
  GpuProcessHostUIShim* ui_shim = FromID(host_id);
  if (!ui_shim) {
    delete msg;
    return;
  }

  ui_shim->Send(msg);
}

#endif

GpuProcessHostUIShim::~GpuProcessHostUIShim() {
  DCHECK(CalledOnValidThread());
  g_hosts_by_id.Pointer()->Remove(host_id_);
}

bool GpuProcessHostUIShim::OnControlMessageReceived(
    const IPC::Message& message) {
  DCHECK(CalledOnValidThread());

  IPC_BEGIN_MESSAGE_MAP(GpuProcessHostUIShim, message)
    IPC_MESSAGE_HANDLER(GpuHostMsg_OnLogMessage,
                        OnLogMessage)
#if defined(TOOLKIT_USES_GTK) && !defined(TOUCH_UI) || defined(OS_WIN)
    IPC_MESSAGE_HANDLER(GpuHostMsg_ResizeView, OnResizeView)
#endif

#if defined(OS_MACOSX) || defined(TOUCH_UI)
    IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceSetIOSurface,
                        OnAcceleratedSurfaceSetIOSurface)
    IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
                        OnAcceleratedSurfaceBuffersSwapped)
#endif

#if defined(TOUCH_UI)
    IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceRelease,
                        OnAcceleratedSurfaceRelease)
#endif
    IPC_MESSAGE_UNHANDLED_ERROR()
  IPC_END_MESSAGE_MAP()

  return true;
}

void GpuProcessHostUIShim::OnLogMessage(
    int level,
    const std::string& header,
    const std::string& message) {
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger("level", level);
  dict->SetString("header", header);
  dict->SetString("message", message);
  GpuDataManager::GetInstance()->AddLogMessage(dict);
}

#if defined(TOOLKIT_USES_GTK) && !defined(TOUCH_UI) || defined(OS_WIN)

void GpuProcessHostUIShim::OnResizeView(int32 renderer_id,
                                        int32 render_view_id,
                                        int32 command_buffer_route_id,
                                        gfx::Size size) {
  RenderViewHost* host = RenderViewHost::FromID(renderer_id, render_view_id);
  if (host) {
    RenderWidgetHostView* view = host->view();
    if (view) {
      gfx::PluginWindowHandle handle = view->GetCompositingSurface();

      // Resize the window synchronously. The GPU process must not issue GL
      // calls on the command buffer until the window is the size it expects it
      // to be.
#if defined(TOOLKIT_USES_GTK) && !defined(TOUCH_UI)
      GdkWindow* window = reinterpret_cast<GdkWindow*>(
          gdk_xid_table_lookup(handle));
      if (window) {
        Display* display = GDK_WINDOW_XDISPLAY(window);
        gdk_window_resize(window, size.width(), size.height());
        XSync(display, False);
      }
#elif defined(OS_WIN)
      // Ensure window does not have zero area because D3D cannot create a zero
      // area swap chain.
      SetWindowPos(handle,
          NULL,
          0, 0,
          std::max(1, size.width()),
          std::max(1, size.height()),
          SWP_NOSENDCHANGING | SWP_NOCOPYBITS | SWP_NOZORDER |
              SWP_NOACTIVATE | SWP_DEFERERASE);
#endif
    }
  }

  // Always respond even if the window no longer exists. The GPU process cannot
  // make progress on the resizing command buffer until it receives the
  // response.
  Send(new GpuMsg_ResizeViewACK(renderer_id, command_buffer_route_id));
}

#endif

#if defined(OS_MACOSX) || defined(TOUCH_UI)

void GpuProcessHostUIShim::OnAcceleratedSurfaceSetIOSurface(
    const GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params& params) {
  RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
                                                params.render_view_id);
  if (!host)
    return;
  RenderWidgetHostView* view = host->view();
  if (!view)
    return;
#if defined(OS_MACOSX)
  view->AcceleratedSurfaceSetIOSurface(params.window,
                                       params.width,
                                       params.height,
                                       params.identifier);
#elif defined(TOUCH_UI)
  view->AcceleratedSurfaceSetIOSurface(
      params.width, params.height, params.identifier);
  Send(new AcceleratedSurfaceMsg_SetSurfaceACK(
      params.route_id, params.identifier));
#endif
}

void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped(
    const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
  TRACE_EVENT0("renderer",
      "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped");
  RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
                                                params.render_view_id);
  if (!host)
    return;
  RenderWidgetHostView* view = host->view();
  if (!view)
    return;
#if defined (OS_MACOSX)
  view->AcceleratedSurfaceBuffersSwapped(
      // Parameters needed to swap the IOSurface.
      params.window,
      params.surface_id,
      // Parameters needed to formulate an acknowledgment.
      params.renderer_id,
      params.route_id,
      host_id_,
      params.swap_buffers_count);
#elif defined(TOUCH_UI)
  view->AcceleratedSurfaceBuffersSwapped(params.surface_id);
  Send(new AcceleratedSurfaceMsg_BuffersSwappedACK(params.route_id));
#endif
}

#endif

#if defined(TOUCH_UI)

void GpuProcessHostUIShim::OnAcceleratedSurfaceRelease(
    const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) {
  RenderViewHost* host = RenderViewHost::FromID(params.renderer_id,
                                                params.render_view_id);
  if (!host)
    return;
  RenderWidgetHostView* view = host->view();
  if (!view)
    return;
  view->AcceleratedSurfaceRelease(params.identifier);
}

#endif
<|endoftext|>


<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    const char* filename = argc >= 2 ? argv[1] : "pic1.png";

    Mat src = imread(filename, 0);
    if(src.empty())
    {
        cout << "can not open " << filename << endl;
        cout << "Usage: houghlines <image_name>" << endl;
    }

    Mat dst, cdst;
    Canny(src, dst, 50, 200, 3);
    cvtColor(dst, cdst, CV_GRAY2BGR);

#if 0
    vector<Vec2f> lines;
    HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 );

    for( size_t i = 0; i < lines.size(); i++ )
    {
        float rho = lines[i][0], theta = lines[i][1];
        Point pt1, pt2;
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho, y0 = b*rho;
        pt1.x = cvRound(x0 + 1000*(-b));
        pt1.y = cvRound(y0 + 1000*(a));
        pt2.x = cvRound(x0 - 1000*(-b));
        pt2.y = cvRound(y0 - 1000*(a));
        line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
    }
#else
    vector<Vec4i> lines;
    HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 );
    for( size_t i = 0; i < lines.size(); i++ )
    {
        Vec4i l = lines[i];
        line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
    }
#endif
    imshow("source", src);
    imshow("detected lines", cdst);

    waitKey();
    return 0;
}

<commit_msg>revamped<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>

using namespace cv;
using namespace std;

void help()
{
	cout << "\nThis program demonstrates line finding with the Hough transform.\n"
			"Call:\n"
			"./houghlines [image_len -- Default is pic1.png\n" << endl;
}

int main(int argc, char** argv)
{
    const char* filename = argc >= 2 ? argv[1] : "pic1.png";

    Mat src = imread(filename, 0);
    if(src.empty())
    {
        cout << "can not open " << filename << endl;
        cout << "Usage: houghlines <image_name>" << endl;
    }
    help();
    Mat dst, cdst;
    Canny(src, dst, 50, 200, 3);
    cvtColor(dst, cdst, CV_GRAY2BGR);

#if 0
    vector<Vec2f> lines;
    HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 );

    for( size_t i = 0; i < lines.size(); i++ )
    {
        float rho = lines[i][0], theta = lines[i][1];
        Point pt1, pt2;
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho, y0 = b*rho;
        pt1.x = cvRound(x0 + 1000*(-b));
        pt1.y = cvRound(y0 + 1000*(a));
        pt2.x = cvRound(x0 - 1000*(-b));
        pt2.y = cvRound(y0 - 1000*(a));
        line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
    }
#else
    vector<Vec4i> lines;
    HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 );
    for( size_t i = 0; i < lines.size(); i++ )
    {
        Vec4i l = lines[i];
        line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
    }
#endif
    imshow("source", src);
    imshow("detected lines", cdst);

    waitKey();
    return 0;
}

<|endoftext|>


<commit_before>/**
 * This file is part of EasyLogging++ samples
 * Demonstration of multithreaded application in C++ (Qt)
 *
 * Compile this program using Qt
 *    qmake qt-sample.pro && make
 *
 * Revision: 1.0
 * @author mkhan3189
 */

#include "../../easylogging++.h"

#include "mythread.h"

_INITIALIZE_EASYLOGGINGPP

FUNC(int, main, (int argc, char* argv[]))   // Using FUNC for performance tracking
    _START_EASYLOGGINGPP(argc, argv)

    bool runThreads = false;

    if (runThreads) {
        for (int i = 1; i <= 1; ++i) {
            MyThread t(i);
            t.start();
            t.wait();
        }
    }

LINFO << easyloggingpp::VersionInfo::licence();

    LVERBOSE(1) << "Verbose ...";

    SDEBUG << "This is security logger for debug";

    BINFO << "This is a business logger";

    PTRACE << "Taking too long? No I dont think so";

  //  LINFO << OSUtilities::getBashOutput ("asdfasdf");

    RETURN(0);
    //_END_EASYLOGGINGPP

END_FUNC(0)
<commit_msg>updated qt sample<commit_after>/**
 * This file is part of EasyLogging++ samples
 * Demonstration of multithreaded application in C++ (Qt)
 *
 * Compile this program using Qt
 *    qmake qt-sample.pro && make
 *
 * Revision: 1.1
 * @author mkhan3189
 */

#include "../../easylogging++.h"

#include "mythread.h"

_INITIALIZE_EASYLOGGINGPP

FUNC(int, main, (int argc, char* argv[]))   // Using FUNC for performance tracking
    _START_EASYLOGGINGPP(argc, argv)

    bool runThreads = true;

    if (runThreads) {
        for (int i = 1; i <= 1; ++i) {
            MyThread t(i);
            t.start();
            t.wait();
        }
    }

    LVERBOSE(1) << "Verbose 1 ...";

    SDEBUG << "This is security logger for debug";

    BINFO << "This is a business logger";

    RETURN(0);

END_FUNC(0)
<|endoftext|>


<commit_before>#include <stdint.h>

#include <PPU.h>
#include <Console.h>
#include <Graphics.h>

PPU::PPU(Console *console) {
    this->console = console;
}

void PPU::boot() {
    // 0x2000: CTRL
    nameTableAddr = 0;              // 0=0x2000, 1=0x2400, 2=0x2800, 3=0x2C00
    vRAMAddrIncr = false;           // 0=1 (across name table), 1=32 (down name table)
    sprPatternTableAddr = false;    // 0=0x0000, 1=0x1000, ignored if sprSize is 8x16
    bgPatternTableAddr = false;     // 0=0x0000, 1=0x1000
    sprSize = false;                // 0=8x8, 1=8x16
    // unused bit
    nmiOnVBlank = false;

    // 0x2001: MASK
    grayscale = false;              // mirrors palette to only shades of grey
    imageMask = false;              // show bg in left 8 columns of screen
    sprMask = false;                // show sprites in left 8 columns of screen
    showBg = false;
    showSpr = false;
    buffRed = false;                // dims non red colours
    buffGreen = false;              // dims non green colours
    buffBlue = false;               // dims non blue colours

    // 0x2002: STATUS
    // 5 unused bits
    sprOverflow = false;            // if > 8 sprites on any scanline in current frame
    spr0Hit = false;                // at first non-zero pixel overlap in both spr0 and bg
    isVBlank = true;                // unset when read

    // 0x2003: OAMADDR
    oamAddrBuffer = 0x00;

    // 0x2004: OAMDATA
    oamReadBuffer = 0x00;

    // 0x2005: SCROLL
    scrollX = 0x00;
    scrollY = 0x00;

    // 0x2006: ADDR
    addrBuffer = 0x0000;

    // 0x2007: DATA
    readBuffer = 0x00;

    // latch used for SCROLL, ADDR. Unset upon STATUS read
    latch = false;

    // palette for background and sprite tiles
    palette.init(console->getPalettePointer());

    // background metatiles
    for (int nt = 0; nt < 4; ++nt) {
        for (int x = 0; x < 8; ++x) {
            for (int y = 0; y < 8; ++y) {
                // offset in nametable where attribute data is located
                uint16_t offset = 0x3C0 + (0x400 * nt) + (y * 8) + x;
                // init
                bgMetaTiles[nt][x][y].init(
                    console->getNameTablePointer() + offset);
            }
        }
    }
    // background tiles
    for (int nt = 0; nt < 4; ++nt) {
        for (int x = 0; x < 32; ++x) {
            for (int y = 0; y < 30; ++y) {
                // offset in name table where data is located
                uint16_t offset = (0x400 * nt) + x + (y * 32);
                // position within enclosing metatile
                uint8_t quadrant = 0;
                if ((x % 4) >= 2) {
                    quadrant |= 0b01;
                }
                if ((y % 4) >= 2) {
                    quadrant |= 0b10;
                }
                // coordinates of parent metatile
                uint8_t mtX = x / 4;
                uint8_t mtY = y / 4;
                // init
                bgTiles[nt][x][y].init(
                    &bgMetaTiles[nt][mtX][mtY],
                    quadrant,
                    console->getNameTablePointer() + offset,
                    console->getPatternTablePointer(),
                    &(bgPatternTableAddr));
            }
        }
    }
    // background pixels
    for (int x = 0; x < 512; ++x) {
        for (int y = 0; y < 480; ++y) {
            // find tile to which pixel belongs
            int nt = 0;
            if (x >= 256) {
                nt += 0b01;
            }
            if (y >= 240) {
                nt += 0b10;
            }
            int tileX = (x % 256) / 8;
            int tileY = (y % 240) / 8;
            // init
            bgPixels[x][y].init(
                &bgTiles[nt][tileX][tileY],
                x % 8,
                y % 8);
        }
    }

    // sprite objects
    for (int i = 0; i < 64; i++) {
        sprites[i].init(
            console->getSprRamPointer() + (i * 4),
            console->getPatternTablePointer(),
            &(sprSize),
            &(sprPatternTableAddr));
    }

    clockCounter = VBLANK;
    oddFrame = false;
}

void PPU::setCTRL(uint8_t value) {
    nameTableAddr = value & 0x03;
    vRAMAddrIncr = !!(value & 0x04);
    sprPatternTableAddr = !!(value & 0x08);
    bgPatternTableAddr = !!(value & 0x10);
    sprSize = !!(value & 0x20);
    nmiOnVBlank = !!(value & 0x80);
}

void PPU::setMASK(uint8_t value) {
    grayscale = !!(value & 0x01);
    imageMask = !!(value & 0x02);
    sprMask = !!(value & 0x04);
    showBg = !!(value & 0x08);
    showSpr = !!(value & 0x10);
    buffRed = !!(value & 0x20);
    buffGreen = !!(value & 0x40);
    buffBlue = !!(value & 0x80);
}

uint8_t PPU::getSTATUS() {
    uint8_t result = 0x00;
    if (sprOverflow) {
        result |= 0x20;
    }
    if (spr0Hit) {
        result |= 0x40;
    }
    if (isVBlank) {
        result |= 0x80;
    }
    isVBlank = false;
    latch = false;
    return result;
}

void PPU::setOAMADDR(uint8_t value) {
    oamAddrBuffer = value;
}

void PPU::setOAMDATA(uint8_t value) {
    oamReadBuffer = value;
    console->oamWrite(oamAddrBuffer++, value);
}

uint8_t PPU::getOAMDATA() {
    // apparently unreliable in NES hardware, but some games use it
    return console->oamRead(oamAddrBuffer);
}

void PPU::setSCROLL(uint8_t value) {
    if (!latch) {
        scrollX = value;
    }
    else {
        scrollY = value;
    }
    latch = !latch;
}

void PPU::setADDR(uint8_t value) {
    if (!latch) {
        // set high byte
        addrBuffer &= 0x00FF;
        addrBuffer |= ((uint16_t)value << 8);
    }
    else {
        // set low byte
        addrBuffer &= 0xFF00;
        addrBuffer |= value;
    }
    latch = !latch;
}

void PPU::setDATA(uint8_t value) {
    console->ppuWrite(addrBuffer, value);
    addrBuffer += ((vRAMAddrIncr) ? 32 : 1);
}

uint8_t PPU::getDATA() {
    uint8_t returnVal;
    if (addrBuffer < 0x3F00) {
        // return what's in the read buffer from the previous
        // read, then load data at current address buffer
        // (before incrementing the address) into the read buffer
        returnVal = readBuffer;
        readBuffer = console->ppuRead(addrBuffer);
    }
    else {
        // when the address buffer points to the palette address range,
        // instead of reading from the read buffer, it returns the
        // data at the immediate address, and stores the name table
        // data that would otherwise be mirrored "underneath" the
        // palette address space in the read buffer
        returnVal = console->ppuRead(addrBuffer);
        readBuffer = console->ppuRead(addrBuffer - 0x1000);
    }
    addrBuffer += ((vRAMAddrIncr) ? 32 : 1);
    return returnVal;
}

void PPU::load() {
    for (int nt = 0; nt < 4; ++nt) {
        for (int x = 0; x < 32; ++x) {
            for (int y = 0; y < 30; ++y) {
                bgTiles[nt][x][y].reload();
            }
        }
    }
    for (int i = 0; i < 64; ++i) {
        sprites[i].reload();
    }
    // TODO reload ppu data here such as scrollX and scrollY
    // reload sprites, due to oamaddr changing
}

void PPU::renderPixel(int x, int y) {
    int realX = x;
    if (nameTableAddr & 0b01) {
        realX += 256;
    }
    realX += scrollX;
    realX %= 512;

    int realY = y;
    if (nameTableAddr & 0b10) {
        realY += 240;
    }
    realY += scrollY;
    realY %= 480;

    // render first occluding sprite that isn't transparent
    for (int i = 0; i < 64; ++i) {
        if (sprites[i].occludes(x, y)) {
            uint8_t paletteIndex = sprites[i].getValue(x, y);
            if (paletteIndex % 4 != 0) {
                uint8_t paletteVal = palette.getValue(paletteIndex);
                uint32_t pixelColour = universalPalette[paletteVal];
                frameBuffer[x + (y * FRAME_WIDTH)] = pixelColour;
                return;
            }
        }
    }

    // otherwise render background if not transparent
    uint8_t paletteIndex = bgPixels[realX][realY].getValue();
    if (paletteIndex % 4 != 0) {
        uint8_t paletteVal = palette.getValue(paletteIndex);
        uint32_t pixelColour = universalPalette[paletteVal];
        frameBuffer[x + (y * FRAME_WIDTH)] = pixelColour;
        return;
    }

    // otherwise render universal background colour
    frameBuffer[x + (y * FRAME_WIDTH)] = universalPalette[palette.getValue(0)];
}

void PPU::renderFrame() {
    for (int y = 0; y < FRAME_HEIGHT; y++) {
        for (int x = 0; x < FRAME_WIDTH; x++) {
            renderPixel(x, y);
            //if(!(x%8) || !(y%8))
            //    frameBuffer[x + (y * FRAME_WIDTH)] = 0xFF0000;
        }
    }
}

void PPU::renderScanline(int scanlNum) {
    for (int x = 0; x < FRAME_WIDTH; x++) {
	renderPixel(x, scanlNum);
    }
}

uint32_t *PPU::getFrame() {
    return frameBuffer;
}

const uint32_t PPU::universalPalette[64] = {
    0x757575, 0x271B8F, 0x0000AB, 0x47009F, 0x8F0077, 0xAB0013,
    0xA70000, 0x7F0B00, 0x432F00, 0x004700, 0x005100, 0x003F17,
    0x1B3F5F, 0x000000, 0x000000, 0x000000, 0xBCBCBC, 0x0073EF,
    0x233BEF, 0x8300F3, 0xBF00BF, 0xE7005B, 0xDB2B00, 0xCB4F0F,
    0x8B7300, 0x009700, 0x00AB00, 0x00933B, 0x00838B, 0x000000,
    0x000000, 0x000000, 0xFFFFFF, 0x3FBFFF, 0x5F97FF, 0xA78BFD,
    0xF77BFF, 0xFF77B7, 0xFF7763, 0xFF9B3B, 0xF3BF3F, 0x83D313,
    0x4FDF4B, 0x58F898, 0x00EBDB, 0x444444, 0x000000, 0x000000,
    0xFFFFFF, 0xABE7FF, 0xC7D7FF, 0xD7CBFF, 0xFFC7FF, 0xFFC7DB,
    0xFFBFB3, 0xFFDBAB, 0xFFE7A3, 0xE3FFA3, 0xABF3BF, 0xB3FFCF,
    0x9FFFF3, 0xAAAAAA, 0x000000, 0x000000};

void PPU::tick() {
    ++clockCounter;
    if (clockCounter >= POST_REND) {
	if (clockCounter == CYC_PER_FRAME) {
	    isVBlank = false;
	    clockCounter = 0;
	    load();
	    if (oddFrame && (showBg || showSpr)) {
		// skip idle cycle 0
		++clockCounter;
		renderScanline(0);
	    }
	}
	else if (clockCounter == PRE_REND) {
	    isVBlank = false;
	}
	else if (clockCounter == VBLANK) {
	    isVBlank = true;
	    if (nmiOnVBlank) {
		console->cpu->signalNMI();
	    }
	    oddFrame ^= 1;
	}
    }
    else if (!(clockCounter % CYC_PER_SCANL)) {
	renderScanline(clockCounter / CYC_PER_SCANL);
    }
}

bool PPU::endOfFrame() {
    return clockCounter == VBLANK;
}
<commit_msg>Clear spr0Hit at start of pre-render line<commit_after>#include <stdint.h>

#include <PPU.h>
#include <Console.h>
#include <Graphics.h>

PPU::PPU(Console *console) {
    this->console = console;
}

void PPU::boot() {
    // 0x2000: CTRL
    nameTableAddr = 0;              // 0=0x2000, 1=0x2400, 2=0x2800, 3=0x2C00
    vRAMAddrIncr = false;           // 0=1 (across name table), 1=32 (down name table)
    sprPatternTableAddr = false;    // 0=0x0000, 1=0x1000, ignored if sprSize is 8x16
    bgPatternTableAddr = false;     // 0=0x0000, 1=0x1000
    sprSize = false;                // 0=8x8, 1=8x16
    // unused bit
    nmiOnVBlank = false;

    // 0x2001: MASK
    grayscale = false;              // mirrors palette to only shades of grey
    imageMask = false;              // show bg in left 8 columns of screen
    sprMask = false;                // show sprites in left 8 columns of screen
    showBg = false;
    showSpr = false;
    buffRed = false;                // dims non red colours
    buffGreen = false;              // dims non green colours
    buffBlue = false;               // dims non blue colours

    // 0x2002: STATUS
    // 5 unused bits
    sprOverflow = false;            // if > 8 sprites on any scanline in current frame
    spr0Hit = false;                // at first non-zero pixel overlap in both spr0 and bg
    isVBlank = true;                // unset when read

    // 0x2003: OAMADDR
    oamAddrBuffer = 0x00;

    // 0x2004: OAMDATA
    oamReadBuffer = 0x00;

    // 0x2005: SCROLL
    scrollX = 0x00;
    scrollY = 0x00;

    // 0x2006: ADDR
    addrBuffer = 0x0000;

    // 0x2007: DATA
    readBuffer = 0x00;

    // latch used for SCROLL, ADDR. Unset upon STATUS read
    latch = false;

    // palette for background and sprite tiles
    palette.init(console->getPalettePointer());

    // background metatiles
    for (int nt = 0; nt < 4; ++nt) {
        for (int x = 0; x < 8; ++x) {
            for (int y = 0; y < 8; ++y) {
                // offset in nametable where attribute data is located
                uint16_t offset = 0x3C0 + (0x400 * nt) + (y * 8) + x;
                // init
                bgMetaTiles[nt][x][y].init(
                    console->getNameTablePointer() + offset);
            }
        }
    }
    // background tiles
    for (int nt = 0; nt < 4; ++nt) {
        for (int x = 0; x < 32; ++x) {
            for (int y = 0; y < 30; ++y) {
                // offset in name table where data is located
                uint16_t offset = (0x400 * nt) + x + (y * 32);
                // position within enclosing metatile
                uint8_t quadrant = 0;
                if ((x % 4) >= 2) {
                    quadrant |= 0b01;
                }
                if ((y % 4) >= 2) {
                    quadrant |= 0b10;
                }
                // coordinates of parent metatile
                uint8_t mtX = x / 4;
                uint8_t mtY = y / 4;
                // init
                bgTiles[nt][x][y].init(
                    &bgMetaTiles[nt][mtX][mtY],
                    quadrant,
                    console->getNameTablePointer() + offset,
                    console->getPatternTablePointer(),
                    &(bgPatternTableAddr));
            }
        }
    }
    // background pixels
    for (int x = 0; x < 512; ++x) {
        for (int y = 0; y < 480; ++y) {
            // find tile to which pixel belongs
            int nt = 0;
            if (x >= 256) {
                nt += 0b01;
            }
            if (y >= 240) {
                nt += 0b10;
            }
            int tileX = (x % 256) / 8;
            int tileY = (y % 240) / 8;
            // init
            bgPixels[x][y].init(
                &bgTiles[nt][tileX][tileY],
                x % 8,
                y % 8);
        }
    }

    // sprite objects
    for (int i = 0; i < 64; i++) {
        sprites[i].init(
            console->getSprRamPointer() + (i * 4),
            console->getPatternTablePointer(),
            &(sprSize),
            &(sprPatternTableAddr));
    }

    clockCounter = VBLANK;
    oddFrame = false;
}

void PPU::setCTRL(uint8_t value) {
    nameTableAddr = value & 0x03;
    vRAMAddrIncr = !!(value & 0x04);
    sprPatternTableAddr = !!(value & 0x08);
    bgPatternTableAddr = !!(value & 0x10);
    sprSize = !!(value & 0x20);
    nmiOnVBlank = !!(value & 0x80);
}

void PPU::setMASK(uint8_t value) {
    grayscale = !!(value & 0x01);
    imageMask = !!(value & 0x02);
    sprMask = !!(value & 0x04);
    showBg = !!(value & 0x08);
    showSpr = !!(value & 0x10);
    buffRed = !!(value & 0x20);
    buffGreen = !!(value & 0x40);
    buffBlue = !!(value & 0x80);
}

uint8_t PPU::getSTATUS() {
    uint8_t result = 0x00;
    if (sprOverflow) {
        result |= 0x20;
    }
    if (spr0Hit) {
        result |= 0x40;
    }
    if (isVBlank) {
        result |= 0x80;
    }
    isVBlank = false;
    latch = false;
    return result;
}

void PPU::setOAMADDR(uint8_t value) {
    oamAddrBuffer = value;
}

void PPU::setOAMDATA(uint8_t value) {
    oamReadBuffer = value;
    console->oamWrite(oamAddrBuffer++, value);
}

uint8_t PPU::getOAMDATA() {
    // apparently unreliable in NES hardware, but some games use it
    return console->oamRead(oamAddrBuffer);
}

void PPU::setSCROLL(uint8_t value) {
    if (!latch) {
        scrollX = value;
    }
    else {
        scrollY = value;
    }
    latch = !latch;
}

void PPU::setADDR(uint8_t value) {
    if (!latch) {
        // set high byte
        addrBuffer &= 0x00FF;
        addrBuffer |= ((uint16_t)value << 8);
    }
    else {
        // set low byte
        addrBuffer &= 0xFF00;
        addrBuffer |= value;
    }
    latch = !latch;
}

void PPU::setDATA(uint8_t value) {
    console->ppuWrite(addrBuffer, value);
    addrBuffer += ((vRAMAddrIncr) ? 32 : 1);
}

uint8_t PPU::getDATA() {
    uint8_t returnVal;
    if (addrBuffer < 0x3F00) {
        // return what's in the read buffer from the previous
        // read, then load data at current address buffer
        // (before incrementing the address) into the read buffer
        returnVal = readBuffer;
        readBuffer = console->ppuRead(addrBuffer);
    }
    else {
        // when the address buffer points to the palette address range,
        // instead of reading from the read buffer, it returns the
        // data at the immediate address, and stores the name table
        // data that would otherwise be mirrored "underneath" the
        // palette address space in the read buffer
        returnVal = console->ppuRead(addrBuffer);
        readBuffer = console->ppuRead(addrBuffer - 0x1000);
    }
    addrBuffer += ((vRAMAddrIncr) ? 32 : 1);
    return returnVal;
}

void PPU::load() {
    for (int nt = 0; nt < 4; ++nt) {
        for (int x = 0; x < 32; ++x) {
            for (int y = 0; y < 30; ++y) {
                bgTiles[nt][x][y].reload();
            }
        }
    }
    for (int i = 0; i < 64; ++i) {
        sprites[i].reload();
    }
    // TODO reload ppu data here such as scrollX and scrollY
    // reload sprites, due to oamaddr changing
}

void PPU::renderPixel(int x, int y) {
    int realX = x;
    if (nameTableAddr & 0b01) {
        realX += 256;
    }
    realX += scrollX;
    realX %= 512;

    int realY = y;
    if (nameTableAddr & 0b10) {
        realY += 240;
    }
    realY += scrollY;
    realY %= 480;

    // render first occluding sprite that isn't transparent
    for (int i = 0; i < 64; ++i) {
        if (sprites[i].occludes(x, y)) {
            uint8_t paletteIndex = sprites[i].getValue(x, y);
            if (paletteIndex % 4 != 0) {
                uint8_t paletteVal = palette.getValue(paletteIndex);
                uint32_t pixelColour = universalPalette[paletteVal];
                frameBuffer[x + (y * FRAME_WIDTH)] = pixelColour;
                return;
            }
        }
    }

    // otherwise render background if not transparent
    uint8_t paletteIndex = bgPixels[realX][realY].getValue();
    if (paletteIndex % 4 != 0) {
        uint8_t paletteVal = palette.getValue(paletteIndex);
        uint32_t pixelColour = universalPalette[paletteVal];
        frameBuffer[x + (y * FRAME_WIDTH)] = pixelColour;
        return;
    }

    // otherwise render universal background colour
    frameBuffer[x + (y * FRAME_WIDTH)] = universalPalette[palette.getValue(0)];
}

void PPU::renderFrame() {
    for (int y = 0; y < FRAME_HEIGHT; y++) {
        for (int x = 0; x < FRAME_WIDTH; x++) {
            renderPixel(x, y);
            //if(!(x%8) || !(y%8))
            //    frameBuffer[x + (y * FRAME_WIDTH)] = 0xFF0000;
        }
    }
}

void PPU::renderScanline(int scanlNum) {
    for (int x = 0; x < FRAME_WIDTH; x++) {
	renderPixel(x, scanlNum);
    }
}

uint32_t *PPU::getFrame() {
    return frameBuffer;
}

const uint32_t PPU::universalPalette[64] = {
    0x757575, 0x271B8F, 0x0000AB, 0x47009F, 0x8F0077, 0xAB0013,
    0xA70000, 0x7F0B00, 0x432F00, 0x004700, 0x005100, 0x003F17,
    0x1B3F5F, 0x000000, 0x000000, 0x000000, 0xBCBCBC, 0x0073EF,
    0x233BEF, 0x8300F3, 0xBF00BF, 0xE7005B, 0xDB2B00, 0xCB4F0F,
    0x8B7300, 0x009700, 0x00AB00, 0x00933B, 0x00838B, 0x000000,
    0x000000, 0x000000, 0xFFFFFF, 0x3FBFFF, 0x5F97FF, 0xA78BFD,
    0xF77BFF, 0xFF77B7, 0xFF7763, 0xFF9B3B, 0xF3BF3F, 0x83D313,
    0x4FDF4B, 0x58F898, 0x00EBDB, 0x444444, 0x000000, 0x000000,
    0xFFFFFF, 0xABE7FF, 0xC7D7FF, 0xD7CBFF, 0xFFC7FF, 0xFFC7DB,
    0xFFBFB3, 0xFFDBAB, 0xFFE7A3, 0xE3FFA3, 0xABF3BF, 0xB3FFCF,
    0x9FFFF3, 0xAAAAAA, 0x000000, 0x000000};

void PPU::tick() {
    ++clockCounter;
    if (clockCounter >= POST_REND) {
	if (clockCounter == CYC_PER_FRAME) {
	    isVBlank = false;
	    clockCounter = 0;
	    load();
	    if (oddFrame && (showBg || showSpr)) {
		// skip idle cycle 0
		++clockCounter;
		renderScanline(0);
	    }
	}
	else if (clockCounter == PRE_REND) {
	    isVBlank = false;
	    spr0Hit = false;
	}
	else if (clockCounter == VBLANK) {
	    isVBlank = true;
	    if (nmiOnVBlank) {
		console->cpu->signalNMI();
	    }
	    oddFrame ^= 1;
	}
    }
    else if (!(clockCounter % CYC_PER_SCANL)) {
	renderScanline(clockCounter / CYC_PER_SCANL);
    }
}

bool PPU::endOfFrame() {
    return clockCounter == VBLANK;
}
<|endoftext|>