<commit_before>#include "stdafx.h"

#include "UpdateGeneral.h"
#include <ATF/global.hpp>

namespace GameServer
{
    namespace Fixes
    {
        template <typename T, size_t N>
        constexpr size_t size_array(T(&)[N])
        {
            return N;
        }

        using namespace ATF;

        void CUpdateGeneral::load()
        {
            auto& core = CATFCore::get_instance();
            core.set_hook(&ATF::CMainThread::_db_Update_General, &CUpdateGeneral::_db_Update_General);
        }

        void CUpdateGeneral::unload()
        {
            auto& core = CATFCore::get_instance();
            core.unset_hook(&ATF::CMainThread::_db_Update_General);
        }

        void CUpdateGeneral::loop()
        {
        }

        ModuleVersion_t CUpdateGeneral::get_version()
        {
            return usVersion;
        }

        ModuleName_t CUpdateGeneral::get_name()
        {
            static const ModuleName_t name = "fix_updategeneral";
            return name;
        }

        void CUpdateGeneral::configure(
            const rapidjson::Value & nodeConfig)
        {
            UNREFERENCED_PARAMETER(nodeConfig);
        }

        bool WINAPIV CUpdateGeneral::_db_Update_General(
            ATF::CMainThread *pObj,
            unsigned int dwSerial,
            ATF::_AVATOR_DATA* pNewData,
            ATF::_AVATOR_DATA* pOldData,
            char* pSzQuery,
            bool bCheckLowHigh,
            ATF::info::CMainThread_db_Update_General258_ptr next)
        {
            UNREFERENCED_PARAMETER(pObj);
            UNREFERENCED_PARAMETER(bCheckLowHigh);
            UNREFERENCED_PARAMETER(next);
            char Source[200];
            memset(&Source[0], '\0', sizeof(Source));
            sprintf(pSzQuery, "UPDATE tbl_general SET ");

            size_t nStartLen = strlen(pSzQuery);

            if (pOldData->dbAvator.m_dExp != pNewData->dbAvator.m_dExp)
            {
                sprintf(Source, "Exp=%f,", pNewData->dbAvator.m_dExp);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dLossExp != pNewData->dbAvator.m_dLossExp)
            {
                sprintf(Source, "LossExp=%f,", pNewData->dbAvator.m_dLossExp);
                strcat(pSzQuery, Source);
            }
            for (int i = 0; i < size_array(pOldData->dbAvator.m_zClassHistory); ++i)
            {
                if (pOldData->dbAvator.m_zClassHistory[i] != pNewData->dbAvator.m_zClassHistory[i])
                {
                    sprintf(Source, "Class%d=%d,", i, pNewData->dbAvator.m_zClassHistory[i]);
                    strcat(pSzQuery, Source);
                }
            }
            if (pOldData->dbAvator.m_dwClassInitCnt != pNewData->dbAvator.m_dwClassInitCnt)
            {
                sprintf(Source, "ClassInitCnt=%d,", pNewData->dbAvator.m_dwClassInitCnt);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_byLastClassGrade != pNewData->dbAvator.m_byLastClassGrade)
            {
                sprintf(Source, "LastClassGrade=%d,", pNewData->dbAvator.m_byLastClassGrade);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dwHP != pNewData->dbAvator.m_dwHP)
            {
                sprintf(Source, "HP=%d,", pNewData->dbAvator.m_dwHP);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dwFP != pNewData->dbAvator.m_dwFP)
            {
                sprintf(Source, "FP=%d,", pNewData->dbAvator.m_dwFP);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dwSP != pNewData->dbAvator.m_dwSP)
            {
                sprintf(Source, "SP=%d,", pNewData->dbAvator.m_dwSP);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dwDP != pNewData->dbAvator.m_dwDP)
            {
                sprintf(Source, "DP=%d,", pNewData->dbAvator.m_dwDP);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_byMapCode != pNewData->dbAvator.m_byMapCode)
            {
                sprintf(Source, "Map=%d,", pNewData->dbAvator.m_byMapCode);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_fStartPos[0] != pNewData->dbAvator.m_fStartPos[0])
            {
                if (_STD isfinite(pNewData->dbAvator.m_fStartPos[0]))
                {
                    sprintf(Source, "X=%f,", pNewData->dbAvator.m_fStartPos[0]);
                    strcat(pSzQuery, Source);
                }
            }
            if (pOldData->dbAvator.m_fStartPos[1] != pNewData->dbAvator.m_fStartPos[1])
            {
                if (_STD isfinite(pNewData->dbAvator.m_fStartPos[1]))
                {
                    sprintf(Source, "Y=%f,", pNewData->dbAvator.m_fStartPos[1]);
                    strcat(pSzQuery, Source);
                }
            }
            if (pOldData->dbAvator.m_fStartPos[2] != pNewData->dbAvator.m_fStartPos[2])
            {
                if (_STD isfinite(pNewData->dbAvator.m_fStartPos[2]))
                {
                    sprintf(Source, "Z=%f,", pNewData->dbAvator.m_fStartPos[2]);
                    strcat(pSzQuery, Source);
                }
            }
            if (pOldData->dbAvator.m_byBagNum != pNewData->dbAvator.m_byBagNum)
            {
                sprintf(Source, "BagNum=%d,", pNewData->dbAvator.m_byBagNum);
                strcat(pSzQuery, Source);
            }

            for (int i = 0; i < 6; ++i)
            {
                if (pNewData->dbEquip.m_EmbellishList[i].Key.IsFilled())
                {
                    if (pOldData->dbEquip.m_EmbellishList[i].Key.IsFilled())
                    {
                        unsigned int newDbKey = pNewData->dbEquip.m_EmbellishList[i].Key.CovDBKey();
                        unsigned int oldDbKey = pOldData->dbEquip.m_EmbellishList[i].Key.CovDBKey();
                        if (newDbKey != oldDbKey)
                        {
                            sprintf(Source, "EK%d=%d,", i, newDbKey);
                            strcat(pSzQuery, Source);
                        }

                        if (pNewData->dbEquip.m_EmbellishList[i].wAmount != pOldData->dbEquip.m_EmbellishList[i].wAmount)
                        {
                            if (pNewData->dbEquip.m_EmbellishList[i].wAmount < 0xFFFF)
                                sprintf(Source, "ED%d=%d,", i, pNewData->dbEquip.m_EmbellishList[i].wAmount);
                            else
                                sprintf(Source, "ED%d=-1,", i);
                            strcat(pSzQuery, Source);
                        }

                        if (pNewData->dbEquip.m_EmbellishList[i].byCsMethod)
                        {
                            unsigned int timeNew = 0;
                            unsigned int timeOld = 0;
                            if (pNewData->dbEquip.m_EmbellishList[i].byCsMethod == 1)
                            {
                                timeNew = pNewData->dbEquip.m_EmbellishList[i].dwT - *ATF::global::Time;
                                timeOld = pOldData->dbEquip.m_EmbellishList[i].dwT - *ATF::global::Time;
                            }
                            else if (pNewData->dbEquip.m_EmbellishList[i].byCsMethod == 2)
                            {
                                timeNew = pNewData->dbEquip.m_EmbellishList[i].dwT;
                                timeOld = pOldData->dbEquip.m_EmbellishList[i].dwT;
                            }
                            if (timeNew != timeOld)
                            {
                                sprintf(Source, "ET%d=%d,", i, timeNew);
                                strcat(pSzQuery, Source);
                            }
                        }
                        if (pNewData->dbEquip.m_EmbellishList[i].lnUID != pOldData->dbEquip.m_EmbellishList[i].lnUID)
                        {
                            sprintf(Source, "ES%d=%I64d,", i, pNewData->dbEquip.m_EmbellishList[i].lnUID);
                            strcat(pSzQuery, Source);
                        }
                    }
                    else
                    {
                        unsigned int newTime = 0;
                        if (pNewData->dbEquip.m_EmbellishList[i].byCsMethod == 1)
                        {
                            newTime = pNewData->dbEquip.m_EmbellishList[i].dwT - *ATF::global::Time;
                        }
                        else if (pNewData->dbEquip.m_EmbellishList[i].byCsMethod == 2)
                        {
                            newTime = pNewData->dbEquip.m_EmbellishList[i].dwT;
                        }
                        if (pNewData->dbEquip.m_EmbellishList[i].wAmount < 0xFFFF)
                        {
                            sprintf(Source, "EK%d=%d,ED%d=%d,ET%d=%d,ES%d=%I64d,",
                                i, (unsigned int)pNewData->dbEquip.m_EmbellishList[i].Key.CovDBKey(),
                                i, pNewData->dbEquip.m_EmbellishList[i].wAmount,
                                i, newTime,
                                i, pNewData->dbEquip.m_EmbellishList[i].lnUID);
                        }
                        else
                        {
                            sprintf(Source, "EK%d=%d,ED%d=-1,ET%d=%d,ES%d=%I64d,",
                                i, (unsigned int)pNewData->dbEquip.m_EmbellishList[i].Key.CovDBKey(),
                                i, i, newTime,
                                i, pNewData->dbEquip.m_EmbellishList[i].lnUID);
                        }
                        strcat(pSzQuery, Source);
                    }
                }
                else if (pOldData->dbEquip.m_EmbellishList[i].Key.IsFilled())
                {
                    sprintf(Source, "EK%d=%d,",
                        i, (unsigned int)pNewData->dbEquip.m_EmbellishList[i].Key.CovDBKey());
                    strcat(pSzQuery, Source);
                }
            }

            for (int i = 0; i < size_array(pNewData->dbForce.m_List); ++i)
            {
                if (pNewData->dbForce.m_List[i].Key.IsFilled())
                {
                    if (pOldData->dbForce.m_List[i].Key.IsFilled())
                    {
                        unsigned int newDbKey = pNewData->dbForce.m_List[i].Key.CovDBKey();
                        unsigned int oldDbKey = pOldData->dbForce.m_List[i].Key.CovDBKey();
                        if (newDbKey != oldDbKey)
                        {
                            sprintf(Source, "F%d=%d,",
                                i, (unsigned int)newDbKey);
                            strcat(pSzQuery, Source);
                        }
                        if (pNewData->dbForce.m_List[i].lnUID != pOldData->dbForce.m_List[i].lnUID)
                        {
                            sprintf(Source, "FS%d=%I64d,",
                                i, pNewData->dbForce.m_List[i].lnUID);
                            strcat(pSzQuery, Source);
                        }
                    }
                    else
                    {
                        sprintf(Source, "F%d=%d,FS%d=%I64d,",
                            i, (unsigned int)pNewData->dbForce.m_List[i].Key.CovDBKey(),
                            i, pNewData->dbForce.m_List[i].lnUID);
                        strcat(pSzQuery, Source);
                    }
                }
                else if (pOldData->dbForce.m_List[i].Key.IsFilled())
                {
                    sprintf(Source, "F%d=%d,",
                        i, (unsigned int)pNewData->dbForce.m_List[i].Key.IsFilled());
                    strcat(pSzQuery, Source);
                }
            }

            if (pOldData->dbAvator.m_byRaceSexCode >> 1 == 1)
            {
                for (int i = 0; i < size_array(pNewData->dbAnimus.m_List); ++i)
                {
                    if (pNewData->dbAnimus.m_List[i].Key.IsFilled())
                    {
                        if (pOldData->dbAnimus.m_List[i].Key.IsFilled())
                        {
                            unsigned int newDbKey = pNewData->dbAnimus.m_List[i].Key.CovDBKey();
                            unsigned int oldDbKey = pOldData->dbAnimus.m_List[i].Key.CovDBKey();
                            if (newDbKey != oldDbKey)
                            {
                                sprintf(Source, "AK%d=%d,AS%d=%I64d,",
                                    i, newDbKey,
                                    i, pNewData->dbAnimus.m_List[i].lnUID);
                                strcat(pSzQuery, Source);
                            }
                            if (pNewData->dbAnimus.m_List[i].dwExp != pOldData->dbAnimus.m_List[i].dwExp)
                            {
                                sprintf(Source, "AD%d=%I64d,", i, pNewData->dbAnimus.m_List[i].dwExp);
                                strcat(pSzQuery, Source);
                            }
                            if (pNewData->dbAnimus.m_List[i].dwParam != pOldData->dbAnimus.m_List[i].dwParam)
                            {
                                sprintf(Source, "AP%d=%d,", i, pNewData->dbAnimus.m_List[i].dwParam);
                                strcat(pSzQuery, Source);
                            }
                        }
                        else
                        {
                            sprintf(Source, "AK%d=%d,AD%d=%I64d,AP%d=%d,AS%d=%I64d,",
                                i, (unsigned int)pNewData->dbAnimus.m_List[i].Key.CovDBKey(),
                                i, pNewData->dbAnimus.m_List[i].lnUID,
                                i, pNewData->dbAnimus.m_List[i].dwParam,
                                i, pNewData->dbAnimus.m_List[i].dwExp);
                            strcat(pSzQuery, Source);
                        }
                    }
                    else if (pOldData->dbAnimus.m_List[i].Key.IsFilled())
                    {
                        sprintf(Source, "AK%d=%d,",
                            i, (unsigned int)pNewData->dbAnimus.m_List[i].Key.CovDBKey());
                        strcat(pSzQuery, Source);
                    }
                }
            }
            for (int i = 0; i < size_array(pNewData->dbStat.m_dwDamWpCnt); ++i)
            {
                if (pOldData->dbStat.m_dwDamWpCnt[i] != pNewData->dbStat.m_dwDamWpCnt[i])
                {
                    sprintf(Source, "WM%d=%d,", i, pNewData->dbStat.m_dwDamWpCnt[i]);
                    strcat(pSzQuery, Source);
                }
            }
            for (int i = 0; i < size_array(pNewData->dbStat.m_dwForceCum); ++i)
            {
                if (pOldData->dbStat.m_dwForceCum[i] != pNewData->dbStat.m_dwForceCum[i])
                {
                    sprintf(Source, "FM%d=%d,", i, pNewData->dbStat.m_dwForceCum[i]);
                    strcat(pSzQuery, Source);
                }
            }
            for (int i = 0; i < size_array(pNewData->dbStat.m_dwSkillCum); ++i)
            {
                if (pOldData->dbStat.m_dwSkillCum[i] != pNewData->dbStat.m_dwSkillCum[i])
                {
                    sprintf(Source, "SM%d=%d,", i, pNewData->dbStat.m_dwSkillCum[i]);
                    strcat(pSzQuery, Source);
                }
            }
            for (int i = 0; i < size_array(pNewData->dbStat.m_dwMakeCum); ++i)
            {
                if (pOldData->dbStat.m_dwMakeCum[i] != pNewData->dbStat.m_dwMakeCum[i])
                {
                    sprintf(Source, "MI%d=%d,", i, pNewData->dbStat.m_dwMakeCum[i]);
                    strcat(pSzQuery, Source);
                }
            }
            if (pOldData->dbStat.m_dwSpecialCum != pNewData->dbStat.m_dwSpecialCum)
            {
                sprintf(Source, "SR=%d,", pNewData->dbStat.m_dwSpecialCum);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbStat.m_dwDefenceCnt != pNewData->dbStat.m_dwDefenceCnt)
            {
                sprintf(Source, "DM=%d,", pNewData->dbStat.m_dwDefenceCnt);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbStat.m_dwShieldCnt != pNewData->dbStat.m_dwShieldCnt)
            {
                sprintf(Source, "PM=%d,", pNewData->dbStat.m_dwShieldCnt);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dPvPPoint != pNewData->dbAvator.m_dPvPPoint)
            {
                sprintf(Source, "PvpPoint=%f,", pNewData->dbAvator.m_dPvPPoint);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dPvPCashBag != pNewData->dbAvator.m_dPvPCashBag)
            {
                sprintf(Source, "PvpCashBag=%f,", pNewData->dbAvator.m_dPvPCashBag);
                strcat(pSzQuery, Source);
            }
            if (strcmp(pOldData->dbAvator.m_szBindMapCode, pNewData->dbAvator.m_szBindMapCode))
            {
                pNewData->dbAvator.m_szBindMapCode[11] = 0;
                sprintf(Source, "BindMapCode='%s',", pNewData->dbAvator.m_szBindMapCode);
                strcat(pSzQuery, Source);
            }
            if (strcmp(pOldData->dbAvator.m_szBindDummy, pNewData->dbAvator.m_szBindDummy))
            {
                pNewData->dbAvator.m_szBindDummy[11] = 0;
                sprintf(Source, "BindDummy='%s',", pNewData->dbAvator.m_szBindDummy);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dwRadarDelayTime != pNewData->dbAvator.m_dwRadarDelayTime)
            {
                sprintf_s(Source, "RDDelay=%d,", pNewData->dbAvator.m_dwRadarDelayTime);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dwTakeLastMentalTicket != pNewData->dbAvator.m_dwTakeLastMentalTicket)
            {
                sprintf_s(Source, "TakeLastMentalTicket=%d,", pNewData->dbAvator.m_dwTakeLastMentalTicket);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_dwTakeLastCriTicket != pNewData->dbAvator.m_dwTakeLastCriTicket)
            {
                sprintf_s(Source, "TakeLastCriTicket=%d,", pNewData->dbAvator.m_dwTakeLastCriTicket);
                strcat(pSzQuery, Source);
            }
            if (pOldData->dbAvator.m_byMaxLevel != pNewData->dbAvator.m_byMaxLevel)
            {
                sprintf(Source, "MaxLevel=%d,", pNewData->dbAvator.m_byMaxLevel);
                strcat(pSzQuery, Source);
            }
            if (pNewData->dbCutting.m_bOldDataLoad)
                strcat(pSzQuery, "LeftResList='*',");
            sprintf(Source, "TotalPlayMin=%d,", pNewData->dbAvator.m_dwTotalPlayMin);
            strcat(pSzQuery, Source);

            size_t nEndLen = strlen(pSzQuery);
            if (nEndLen <= nStartLen)
            {
                memset(pSzQuery, 0, nStartLen);
            }
            else
            {
                sprintf(Source, "WHERE Serial = %d", dwSerial);
                pSzQuery[strlen(pSzQuery) - 1] = ' ';
                strcat(pSzQuery, Source);
            }
            return true;
        }
    }
}<commit_msg>Normal fix for coordinate dup<commit_after>#include "stdafx.h"

#include "UpdateGeneral.h"
#include <ATF/global.hpp>

namespace GameServer
{
    namespace Fixes
    {
        template <typename T, size_t N>
        constexpr size_t size_array(T(&)[N])
        {
            return N;
        }

        using namespace ATF;

        void CUpdateGeneral::load()
        {
            auto& core = CATFCore::get_instance();
            core.set_hook(&ATF::CMainThread::_db_Update_General, &CUpdateGeneral::_db_Update_General);
        }

        void CUpdateGeneral::unload()
        {
            auto& core = CATFCore::get_instance();
            core.unset_hook(&ATF::CMainThread::_db_Update_General);
        }

        void CUpdateGeneral::loop()
        {
        }

        ModuleVersion_t CUpdateGeneral::get_version()
        {
            return usVersion;
        }

        ModuleName_t CUpdateGeneral::get_name()
        {
            static const ModuleName_t name = "fix_updategeneral";
            return name;
        }

        void CUpdateGeneral::configure(
            const rapidjson::Value & nodeConfig)
        {
            UNREFERENCED_PARAMETER(nodeConfig);
        }

        bool WINAPIV CUpdateGeneral::_db_Update_General(
            ATF::CMainThread *pObj,
            unsigned int dwSerial,
            ATF::_AVATOR_DATA* pNewData,
            ATF::_AVATOR_DATA* pOldData,
            char* pSzQuery,
            bool bCheckLowHigh,
            ATF::info::CMainThread_db_Update_General258_ptr next)
        {
            for (int i = 0; i < size_array(pNewData->dbAvator.m_fStartPos); ++i)
            {
                if (_STD isfinite(pOldData->dbAvator.m_fStartPos[i]) &&
                    _STD isfinite(pNewData->dbAvator.m_fStartPos[i]))
                    continue;

                for (int j = 0; j < size_array(pNewData->dbAvator.m_fStartPos); ++j)
                {
                    pOldData->dbAvator.m_fStartPos[j] = 0.0f;
                    pNewData->dbAvator.m_fStartPos[j] = 1.0f;
                }
                break;
            }

            return next(pObj, dwSerial, pNewData, pOldData, pSzQuery, bCheckLowHigh);
        }
    }
}<|endoftext|>


<commit_before>#include <fstream>

#include "common/network/address_impl.h"
#include "common/thread_local/thread_local_impl.h"

#include "server/listener_hooks.h"
#include "server/proto_descriptors.h"
#include "server/server.h"

#include "test/fuzz/fuzz_runner.h"
#include "test/integration/server.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/stats/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/test_time.h"

namespace Envoy {
namespace Server {
namespace {

void makePortHermetic(Fuzz::PerTestEnvironment& test_env, envoy::api::v2::core::Address& address) {
  if (address.has_socket_address()) {
    address.mutable_socket_address()->set_port_value(0);
  } else if (address.has_pipe()) {
    address.mutable_pipe()->set_path("@" + test_env.testId() + address.pipe().path());
  }
}

envoy::config::bootstrap::v2::Bootstrap
makeHermeticPathsAndPorts(Fuzz::PerTestEnvironment& test_env,
                          const envoy::config::bootstrap::v2::Bootstrap& input) {
  envoy::config::bootstrap::v2::Bootstrap output(input);
  // This is not a complete list of places where we need to zero out ports or sanitize paths, so we
  // should adapt it as we go and encounter places that we need to stabilize server test flakes.
  // config_validation_fuzz_test doesn't need to do this sanitization, so should pickup the coverage
  // we lose here. If we don't sanitize here, we get flakes due to port bind conflicts, file
  // conflicts, etc.
  output.clear_admin();
  if (output.has_runtime()) {
    output.mutable_runtime()->set_symlink_root(test_env.temporaryPath(""));
  }
  for (auto& listener : *output.mutable_static_resources()->mutable_listeners()) {
    if (listener.has_address()) {
      makePortHermetic(test_env, *listener.mutable_address());
    }
  }
  for (auto& cluster : *output.mutable_static_resources()->mutable_clusters()) {
    for (auto& host : *cluster.mutable_hosts()) {
      makePortHermetic(test_env, host);
    }
  }
  return output;
}

DEFINE_PROTO_FUZZER(const envoy::config::bootstrap::v2::Bootstrap& input) {
  testing::NiceMock<MockOptions> options;
  DefaultListenerHooks hooks;
  testing::NiceMock<MockHotRestart> restart;
  Stats::TestIsolatedStoreImpl stats_store;
  Thread::MutexBasicLockable fakelock;
  TestComponentFactory component_factory;
  ThreadLocal::InstanceImpl thread_local_instance;
  DangerousDeprecatedTestTime test_time;
  Fuzz::PerTestEnvironment test_env;

  RELEASE_ASSERT(validateProtoDescriptors(), "");

  {
    const std::string bootstrap_path = test_env.temporaryPath("bootstrap.pb_text");
    std::ofstream bootstrap_file(bootstrap_path);
    bootstrap_file << makeHermeticPathsAndPorts(test_env, input).DebugString();
    options.config_path_ = bootstrap_path;
    options.log_level_ = Fuzz::Runner::logLevel();
  }

  std::unique_ptr<InstanceImpl> server;
  try {
    server = std::make_unique<InstanceImpl>(
        options, test_time.timeSystem(),
        std::make_shared<Network::Address::Ipv4Instance>("127.0.0.1"), hooks, restart, stats_store,
        fakelock, component_factory, std::make_unique<Runtime::RandomGeneratorImpl>(),
        thread_local_instance, Thread::threadFactoryForTest(), Filesystem::fileSystemForTest());
  } catch (const EnvoyException& ex) {
    ENVOY_LOG_MISC(debug, "Controlled EnvoyException exit: {}", ex.what());
    return;
  }
  // If we were successful, run any pending events on the main thread's dispatcher loop. These might
  // be, for example, pending DNS resolution callbacks. If they generate exceptions, we want to
  // explode and fail the test, hence we do this outside of the try-catch above.
  server->dispatcher().run(Event::Dispatcher::RunType::NonBlock);
}

} // namespace
} // namespace Server
} // namespace Envoy
<commit_msg>test: enabling deprecated-and-fatal features in the fuzz tests (#6840)<commit_after>#include <fstream>

#include "common/network/address_impl.h"
#include "common/thread_local/thread_local_impl.h"

#include "server/listener_hooks.h"
#include "server/proto_descriptors.h"
#include "server/server.h"

#include "test/common/runtime/utility.h"
#include "test/fuzz/fuzz_runner.h"
#include "test/integration/server.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/stats/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/test_time.h"

namespace Envoy {
namespace Server {
namespace {

void makePortHermetic(Fuzz::PerTestEnvironment& test_env, envoy::api::v2::core::Address& address) {
  if (address.has_socket_address()) {
    address.mutable_socket_address()->set_port_value(0);
  } else if (address.has_pipe()) {
    address.mutable_pipe()->set_path("@" + test_env.testId() + address.pipe().path());
  }
}

envoy::config::bootstrap::v2::Bootstrap
makeHermeticPathsAndPorts(Fuzz::PerTestEnvironment& test_env,
                          const envoy::config::bootstrap::v2::Bootstrap& input) {
  envoy::config::bootstrap::v2::Bootstrap output(input);
  // This is not a complete list of places where we need to zero out ports or sanitize paths, so we
  // should adapt it as we go and encounter places that we need to stabilize server test flakes.
  // config_validation_fuzz_test doesn't need to do this sanitization, so should pickup the coverage
  // we lose here. If we don't sanitize here, we get flakes due to port bind conflicts, file
  // conflicts, etc.
  output.clear_admin();
  if (output.has_runtime()) {
    output.mutable_runtime()->set_symlink_root(test_env.temporaryPath(""));
  }
  for (auto& listener : *output.mutable_static_resources()->mutable_listeners()) {
    if (listener.has_address()) {
      makePortHermetic(test_env, *listener.mutable_address());
    }
  }
  for (auto& cluster : *output.mutable_static_resources()->mutable_clusters()) {
    for (auto& host : *cluster.mutable_hosts()) {
      makePortHermetic(test_env, host);
    }
  }
  return output;
}

class AllFeaturesHooks : public DefaultListenerHooks {
  void onRuntimeCreated() override { Runtime::RuntimeFeaturesPeer::setAllFeaturesAllowed(); }
};

DEFINE_PROTO_FUZZER(const envoy::config::bootstrap::v2::Bootstrap& input) {
  testing::NiceMock<MockOptions> options;
  AllFeaturesHooks hooks;
  testing::NiceMock<MockHotRestart> restart;
  Stats::TestIsolatedStoreImpl stats_store;
  Thread::MutexBasicLockable fakelock;
  TestComponentFactory component_factory;
  ThreadLocal::InstanceImpl thread_local_instance;
  DangerousDeprecatedTestTime test_time;
  Fuzz::PerTestEnvironment test_env;

  RELEASE_ASSERT(validateProtoDescriptors(), "");

  {
    const std::string bootstrap_path = test_env.temporaryPath("bootstrap.pb_text");
    std::ofstream bootstrap_file(bootstrap_path);
    bootstrap_file << makeHermeticPathsAndPorts(test_env, input).DebugString();
    options.config_path_ = bootstrap_path;
    options.log_level_ = Fuzz::Runner::logLevel();
  }

  std::unique_ptr<InstanceImpl> server;
  try {
    server = std::make_unique<InstanceImpl>(
        options, test_time.timeSystem(),
        std::make_shared<Network::Address::Ipv4Instance>("127.0.0.1"), hooks, restart, stats_store,
        fakelock, component_factory, std::make_unique<Runtime::RandomGeneratorImpl>(),
        thread_local_instance, Thread::threadFactoryForTest(), Filesystem::fileSystemForTest());
  } catch (const EnvoyException& ex) {
    ENVOY_LOG_MISC(debug, "Controlled EnvoyException exit: {}", ex.what());
    return;
  }
  // If we were successful, run any pending events on the main thread's dispatcher loop. These might
  // be, for example, pending DNS resolution callbacks. If they generate exceptions, we want to
  // explode and fail the test, hence we do this outside of the try-catch above.
  server->dispatcher().run(Event::Dispatcher::RunType::NonBlock);
}

} // namespace
} // namespace Server
} // namespace Envoy
<|endoftext|>


<commit_before>// Copyright 2014 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 "config.h"
#include "modules/bluetooth/BluetoothDevice.h"

#include "bindings/core/v8/CallbackPromiseAdapter.h"
#include "bindings/core/v8/ScriptPromise.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
#include "core/dom/DOMException.h"
#include "core/dom/ExceptionCode.h"
#include "modules/bluetooth/BluetoothError.h"
#include "modules/bluetooth/BluetoothGATTRemoteServer.h"
#include "public/platform/Platform.h"
#include "public/platform/modules/bluetooth/WebBluetooth.h"
#include "wtf/OwnPtr.h"

namespace blink {

BluetoothDevice::BluetoothDevice(const WebBluetoothDevice& webDevice)
    : m_webDevice(webDevice)
{
}

BluetoothDevice* BluetoothDevice::create(const WebBluetoothDevice& webDevice)
{
    return new BluetoothDevice(webDevice);
}

BluetoothDevice* BluetoothDevice::take(ScriptPromiseResolver*, WebBluetoothDevice* webDeviceRawPointer)
{
    OwnPtr<WebBluetoothDevice> webDevice = adoptPtr(webDeviceRawPointer);
    return BluetoothDevice::create(*webDevice);
}

void BluetoothDevice::dispose(WebBluetoothDevice* webDeviceRaw)
{
    delete webDeviceRaw;
}

unsigned BluetoothDevice::deviceClass(bool& isNull)
{
    isNull = false;
    return m_webDevice.deviceClass;
}

String BluetoothDevice::vendorIDSource()
{
    switch (m_webDevice.vendorIDSource) {
    case WebBluetoothDevice::VendorIDSource::Unknown: return String();
    case WebBluetoothDevice::VendorIDSource::Bluetooth: return "bluetooth";
    case WebBluetoothDevice::VendorIDSource::USB: return "usb";
    }
    ASSERT_NOT_REACHED();
    return String();
}

unsigned BluetoothDevice::vendorID(bool& isNull)
{
    isNull = false;
    return m_webDevice.vendorID;
}

unsigned BluetoothDevice::productID(bool& isNull)
{
    isNull = false;
    return m_webDevice.productID;
}

unsigned BluetoothDevice::productVersion(bool& isNull)
{
    isNull = false;
    return m_webDevice.productVersion;
}

bool BluetoothDevice::paired()
{
    return m_webDevice.paired;
}

Vector<String> BluetoothDevice::uuids()
{
    Vector<String> uuids(m_webDevice.uuids.size());
    for (size_t i = 0; i < m_webDevice.uuids.size(); ++i)
        uuids[i] = m_webDevice.uuids[i];
    return uuids;
}

ScriptPromise BluetoothDevice::connectGATT(ScriptState* scriptState)
{
    WebBluetooth* webbluetooth = Platform::current()->bluetooth();
    if (!webbluetooth)
        return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NotSupportedError));
    RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(scriptState);
    ScriptPromise promise = resolver->promise();
    webbluetooth->connectGATT(instanceID(), new CallbackPromiseAdapter<BluetoothGATTRemoteServer, BluetoothError>(resolver));
    return promise;
}

} // namespace blink
<commit_msg>Oilpan: fix build after r194169.<commit_after>// Copyright 2014 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 "config.h"
#include "modules/bluetooth/BluetoothDevice.h"

#include "bindings/core/v8/CallbackPromiseAdapter.h"
#include "bindings/core/v8/ScriptPromise.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
#include "core/dom/DOMException.h"
#include "core/dom/ExceptionCode.h"
#include "modules/bluetooth/BluetoothError.h"
#include "modules/bluetooth/BluetoothGATTRemoteServer.h"
#include "public/platform/Platform.h"
#include "public/platform/modules/bluetooth/WebBluetooth.h"
#include "wtf/OwnPtr.h"

namespace blink {

BluetoothDevice::BluetoothDevice(const WebBluetoothDevice& webDevice)
    : m_webDevice(webDevice)
{
}

BluetoothDevice* BluetoothDevice::create(const WebBluetoothDevice& webDevice)
{
    return new BluetoothDevice(webDevice);
}

BluetoothDevice* BluetoothDevice::take(ScriptPromiseResolver*, WebBluetoothDevice* webDeviceRawPointer)
{
    OwnPtr<WebBluetoothDevice> webDevice = adoptPtr(webDeviceRawPointer);
    return BluetoothDevice::create(*webDevice);
}

void BluetoothDevice::dispose(WebBluetoothDevice* webDeviceRaw)
{
    delete webDeviceRaw;
}

unsigned BluetoothDevice::deviceClass(bool& isNull)
{
    isNull = false;
    return m_webDevice.deviceClass;
}

String BluetoothDevice::vendorIDSource()
{
    switch (m_webDevice.vendorIDSource) {
    case WebBluetoothDevice::VendorIDSource::Unknown: return String();
    case WebBluetoothDevice::VendorIDSource::Bluetooth: return "bluetooth";
    case WebBluetoothDevice::VendorIDSource::USB: return "usb";
    }
    ASSERT_NOT_REACHED();
    return String();
}

unsigned BluetoothDevice::vendorID(bool& isNull)
{
    isNull = false;
    return m_webDevice.vendorID;
}

unsigned BluetoothDevice::productID(bool& isNull)
{
    isNull = false;
    return m_webDevice.productID;
}

unsigned BluetoothDevice::productVersion(bool& isNull)
{
    isNull = false;
    return m_webDevice.productVersion;
}

bool BluetoothDevice::paired()
{
    return m_webDevice.paired;
}

Vector<String> BluetoothDevice::uuids()
{
    Vector<String> uuids(m_webDevice.uuids.size());
    for (size_t i = 0; i < m_webDevice.uuids.size(); ++i)
        uuids[i] = m_webDevice.uuids[i];
    return uuids;
}

ScriptPromise BluetoothDevice::connectGATT(ScriptState* scriptState)
{
    WebBluetooth* webbluetooth = Platform::current()->bluetooth();
    if (!webbluetooth)
        return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NotSupportedError));
    RefPtrWillBeRawPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(scriptState);
    ScriptPromise promise = resolver->promise();
    webbluetooth->connectGATT(instanceID(), new CallbackPromiseAdapter<BluetoothGATTRemoteServer, BluetoothError>(resolver));
    return promise;
}

} // namespace blink
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef VALUE_HPP
#define VALUE_HPP

// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/config_error.hpp>
// boost
#include <boost/variant.hpp>
// stl
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
// uci
#include <unicode/unistr.h>

namespace mapnik  {

   struct value_null
   {
   };

   typedef boost::variant<value_null,bool,int,double,UnicodeString> value_base;

   namespace impl {
      struct equals
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
	    bool operator() (const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs == rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (UnicodeString const& lhs,
                             UnicodeString const& rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct not_equals
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
	    bool operator() (const T &, const U &) const
	    {
	       return true;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs != rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (UnicodeString const& lhs,
                             UnicodeString const& rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (value_null, const T &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (const T &, value_null) const
	    {
	       return false;
	    }
      };

      struct greater_than
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs > rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct greater_or_equal
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs >= rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs >= rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs >= rhs;
	    }

            bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
	    {
	       return lhs >= rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct less_than
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs < rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs < rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs < rhs;
	    }

            bool operator()(UnicodeString const& lhs,
                            UnicodeString const& rhs ) const
	    {
	       return lhs < rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct less_or_equal
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs <= rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs <= rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs <= rhs;
	    }

            template <typename T>
            bool operator()(UnicodeString const& lhs,
                            UnicodeString const& rhs ) const
	    {
	       return lhs <= rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      template <typename V>
      struct add : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }
            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs + rhs ;
	    }

            value_type operator() (UnicodeString const& lhs ,
                                   UnicodeString const& rhs ) const
	    {
	       return lhs + rhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs + rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs + rhs;
	    }
      };
      template <typename V>
      struct sub : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }

            template <typename T>
            value_type operator() (T  lhs, T rhs) const
	    {
	       return lhs - rhs ;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const& ) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs - rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs - rhs;
	    }
      };

      template <typename V>
      struct mult : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs , T2 const& ) const
	    {
	       return lhs;
	    }
            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs * rhs;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const& ) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs * rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs * rhs;
	    }
      };

      template <typename V>
      struct div: public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }

            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs / rhs;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const&) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs / rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs / rhs;
	    }
      };

      struct to_bool : public boost::static_visitor<bool>
      {

            template <typename T>
            bool operator() (T val) const
	    {
               throw config_error("Boolean value expected");
	    }

            bool operator() (bool val) const
            {
	       return val;
            }
      };

      struct to_string : public boost::static_visitor<std::string>
      {

            template <typename T>
            std::string operator() (T val) const
	    {
               std::stringstream ss;
	       ss << val;
	       return ss.str();
	    }
            // specializations
            std::string operator() (UnicodeString const& val) const
	    {
               //std::stringstream ss;
               //std::wstring::const_iterator pos = val.begin();
               //ss << std::hex ;
               //for (;pos!=val.end();++pos)
               //{
               //  wchar_t c = *pos;
               //  if (c < 0x80)
               //  {
               //     ss << char(c);
               //  }
               //  else
               //  {
               //     ss << "\\x";
               //     unsigned c0 = (c >> 8) & 0xff;
               //     if (c0) ss << c0;
               //     ss << (c & 0xff);
               //  }
               //}
	       //return ss.str();
               return "TODO";
	    }

            std::string operator() (double val) const
            {
               std::stringstream ss;
	       ss << std::setprecision(16) << val;
	       return ss.str();
            }

            std::string operator() (value_null const& val) const
            {
	       return "";
            }
       };

      struct to_unicode : public boost::static_visitor<UnicodeString>
      {

            template <typename T>
            UnicodeString operator() (T val) const
	    {
               std::basic_ostringstream<char> out;
	       out << val;
               return UnicodeString(out.str().c_str());
	    }

            // specializations
            UnicodeString const& operator() (UnicodeString const& val) const
	    {
               return val;
	    }

            UnicodeString operator() (double val) const
            {
               std::basic_ostringstream<char> out;
	       out << std::setprecision(16) << val;
               return UnicodeString(out.str().c_str());
            }

            UnicodeString operator() (value_null const& val) const
            {
	       return UnicodeString("");
            }
      };

      struct to_expression_string : public boost::static_visitor<std::string>
      {
            std::string operator() (UnicodeString const& val) const
	    {
               /*
               std::stringstream ss;
               UnicodeString::const_iterator pos = val.begin();
               ss << std::hex ;
               for (;pos!=val.end();++pos)
               {
                  wchar_t c = *pos;
                  if (c < 0x80)
                  {
                     ss << char(c);
                  }
                  else
                  {
                     ss << "\\x";
                     unsigned c0 = (c >> 8) & 0xff;
                     if (c0) ss << c0;
                     ss << (c & 0xff);
                  }
               }
	       return "\'" + ss.str() + "\'";
               */
               return "TODO";
	    }

            template <typename T>
            std::string operator() (T val) const
	    {
	       std::stringstream ss;
	       ss << val;
	       return ss.str();
	    }

            std::string operator() (double val) const
            {
               std::stringstream ss;
	       ss << std::setprecision(16) << val;
	       return ss.str();
            }

            std::string operator() (value_null const& val) const
	    {
               return "null";
            }
      };
   }

   class value
   {
	 value_base base_;
	 friend const value operator+(value const&,value const&);
	 friend const value operator-(value const&,value const&);
	 friend const value operator*(value const&,value const&);
	 friend const value operator/(value const&,value const&);

      public:
	 value ()
            : base_(value_null()) {}

	 template <typename T> value(T _val_)
            : base_(_val_) {}

	 bool operator==(value const& other) const
	 {
	    return boost::apply_visitor(impl::equals(),base_,other.base_);
	 }

	 bool operator!=(value const& other) const
	 {
	    return boost::apply_visitor(impl::not_equals(),base_,other.base_);
	 }

	 bool operator>(value const& other) const
	 {
	    return boost::apply_visitor(impl::greater_than(),base_,other.base_);
	 }

	 bool operator>=(value const& other) const
	 {
	    return boost::apply_visitor(impl::greater_or_equal(),base_,other.base_);
	 }

	 bool operator<(value const& other) const
	 {
	    return boost::apply_visitor(impl::less_than(),base_,other.base_);
	 }

	 bool operator<=(value const& other) const
	 {
	    return boost::apply_visitor(impl::less_or_equal(),base_,other.base_);
	 }

	 value_base const& base() const
	 {
	    return base_;
	 }

	 bool to_bool() const
	 {
	    return boost::apply_visitor(impl::to_bool(),base_);
	 }

	 std::string to_expression_string() const
	 {
	    return boost::apply_visitor(impl::to_expression_string(),base_);
	 }

	 std::string to_string() const
	 {
	    return boost::apply_visitor(impl::to_string(),base_);
	 }

         UnicodeString to_unicode() const
         {
            return boost::apply_visitor(impl::to_unicode(),base_);
         }
   };

   inline const value operator+(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::add<value>(),p1.base_, p2.base_));
   }

   inline const value operator-(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::sub<value>(),p1.base_, p2.base_));
   }

   inline const value operator*(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::mult<value>(),p1.base_, p2.base_));
   }

   inline const value operator/(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::div<value>(),p1.base_, p2.base_));
   }

  template <typename charT, typename traits>
  inline std::basic_ostream<charT,traits>&
  operator << (std::basic_ostream<charT,traits>& out,
	       value const& v)
  {
    out << v.to_string();
    return out;
  }
}

#endif //VALUE_HPP
<commit_msg>+ to_utf8 function to convert from icu::UnicodeString to utf-8 std::string<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef VALUE_HPP
#define VALUE_HPP

// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/config_error.hpp>
// boost
#include <boost/variant.hpp>
#include <boost/scoped_array.hpp>
// stl
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
// uci
#include <unicode/unistr.h>
#include <unicode/ustring.h>

namespace mapnik  {

   inline void to_utf8(UnicodeString const& input, std::string & target)
   {
      if (input.length() == 0) return;

      const int BUF_SIZE = 256;
      char  buf [BUF_SIZE];
      int len;

      UErrorCode err = U_ZERO_ERROR;
      u_strToUTF8(buf, BUF_SIZE, &len, input.getBuffer(), input.length(), &err);
      if (err == U_BUFFER_OVERFLOW_ERROR || err == U_STRING_NOT_TERMINATED_WARNING )
      {
         boost::scoped_array<char> buf_ptr(new char [len+1]);
         err = U_ZERO_ERROR;
         u_strToUTF8(buf_ptr.get() , len + 1, &len, input.getBuffer(), input.length(), &err);
         target.assign(buf_ptr.get() , len);
      }
      else
      {
         target.assign(buf, len);
      }
   }

   struct value_null
   {
   };

   typedef boost::variant<value_null,bool,int,double,UnicodeString> value_base;

   namespace impl {
      struct equals
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
	    bool operator() (const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs == rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (UnicodeString const& lhs,
                             UnicodeString const& rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct not_equals
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
	    bool operator() (const T &, const U &) const
	    {
	       return true;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs != rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (UnicodeString const& lhs,
                             UnicodeString const& rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (value_null, const T &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (const T &, value_null) const
	    {
	       return false;
	    }
      };

      struct greater_than
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs > rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct greater_or_equal
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs >= rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs >= rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs >= rhs;
	    }

            bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
	    {
	       return lhs >= rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct less_than
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs < rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs < rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs < rhs;
	    }

            bool operator()(UnicodeString const& lhs,
                            UnicodeString const& rhs ) const
	    {
	       return lhs < rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct less_or_equal
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs <= rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs <= rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs <= rhs;
	    }

            template <typename T>
            bool operator()(UnicodeString const& lhs,
                            UnicodeString const& rhs ) const
	    {
	       return lhs <= rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      template <typename V>
      struct add : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }
            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs + rhs ;
	    }

            value_type operator() (UnicodeString const& lhs ,
                                   UnicodeString const& rhs ) const
	    {
	       return lhs + rhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs + rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs + rhs;
	    }
      };
      template <typename V>
      struct sub : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }

            template <typename T>
            value_type operator() (T  lhs, T rhs) const
	    {
	       return lhs - rhs ;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const& ) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs - rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs - rhs;
	    }
      };

      template <typename V>
      struct mult : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs , T2 const& ) const
	    {
	       return lhs;
	    }
            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs * rhs;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const& ) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs * rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs * rhs;
	    }
      };

      template <typename V>
      struct div: public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }

            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs / rhs;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const&) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs / rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs / rhs;
	    }
      };

      struct to_bool : public boost::static_visitor<bool>
      {

            template <typename T>
            bool operator() (T val) const
	    {
               throw config_error("Boolean value expected");
	    }

            bool operator() (bool val) const
            {
	       return val;
            }
      };

      struct to_string : public boost::static_visitor<std::string>
      {

            template <typename T>
            std::string operator() (T val) const
	    {
               std::stringstream ss;
	       ss << val;
	       return ss.str();
	    }
            // specializations
            std::string operator() (UnicodeString const& val) const
	    {
               //std::stringstream ss;
               //std::wstring::const_iterator pos = val.begin();
               //ss << std::hex ;
               //for (;pos!=val.end();++pos)
               //{
               //  wchar_t c = *pos;
               //  if (c < 0x80)
               //  {
               //     ss << char(c);
               //  }
               //  else
               //  {
               //     ss << "\\x";
               //     unsigned c0 = (c >> 8) & 0xff;
               //     if (c0) ss << c0;
               //     ss << (c & 0xff);
               //  }
               //}
	       //return ss.str();
               return "TODO";
	    }

            std::string operator() (double val) const
            {
               std::stringstream ss;
	       ss << std::setprecision(16) << val;
	       return ss.str();
            }

            std::string operator() (value_null const& val) const
            {
	       return "";
            }
       };

      struct to_unicode : public boost::static_visitor<UnicodeString>
      {

            template <typename T>
            UnicodeString operator() (T val) const
	    {
               std::basic_ostringstream<char> out;
	       out << val;
               return UnicodeString(out.str().c_str());
	    }

            // specializations
            UnicodeString const& operator() (UnicodeString const& val) const
	    {
               return val;
	    }

            UnicodeString operator() (double val) const
            {
               std::basic_ostringstream<char> out;
	       out << std::setprecision(16) << val;
               return UnicodeString(out.str().c_str());
            }

            UnicodeString operator() (value_null const& val) const
            {
	       return UnicodeString("");
            }
      };

      struct to_expression_string : public boost::static_visitor<std::string>
      {
            std::string operator() (UnicodeString const& val) const
	    {
               std::string utf8;
               to_utf8(val,utf8);
               return "'" + utf8 + "'";
	    }

            template <typename T>
            std::string operator() (T val) const
	    {
	       std::stringstream ss;
	       ss << val;
	       return ss.str();
	    }

            std::string operator() (double val) const
            {
               std::stringstream ss;
	       ss << std::setprecision(16) << val;
	       return ss.str();
            }

            std::string operator() (value_null const& val) const
	    {
               return "null";
            }
      };
   }

   class value
   {
	 value_base base_;
	 friend const value operator+(value const&,value const&);
	 friend const value operator-(value const&,value const&);
	 friend const value operator*(value const&,value const&);
	 friend const value operator/(value const&,value const&);

      public:
	 value ()
            : base_(value_null()) {}

	 template <typename T> value(T _val_)
            : base_(_val_) {}

	 bool operator==(value const& other) const
	 {
	    return boost::apply_visitor(impl::equals(),base_,other.base_);
	 }

	 bool operator!=(value const& other) const
	 {
	    return boost::apply_visitor(impl::not_equals(),base_,other.base_);
	 }

	 bool operator>(value const& other) const
	 {
	    return boost::apply_visitor(impl::greater_than(),base_,other.base_);
	 }

	 bool operator>=(value const& other) const
	 {
	    return boost::apply_visitor(impl::greater_or_equal(),base_,other.base_);
	 }

	 bool operator<(value const& other) const
	 {
	    return boost::apply_visitor(impl::less_than(),base_,other.base_);
	 }

	 bool operator<=(value const& other) const
	 {
	    return boost::apply_visitor(impl::less_or_equal(),base_,other.base_);
	 }

	 value_base const& base() const
	 {
	    return base_;
	 }

	 bool to_bool() const
	 {
	    return boost::apply_visitor(impl::to_bool(),base_);
	 }

	 std::string to_expression_string() const
	 {
	    return boost::apply_visitor(impl::to_expression_string(),base_);
	 }

	 std::string to_string() const
	 {
	    return boost::apply_visitor(impl::to_string(),base_);
	 }

         UnicodeString to_unicode() const
         {
            return boost::apply_visitor(impl::to_unicode(),base_);
         }
   };

   inline const value operator+(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::add<value>(),p1.base_, p2.base_));
   }

   inline const value operator-(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::sub<value>(),p1.base_, p2.base_));
   }

   inline const value operator*(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::mult<value>(),p1.base_, p2.base_));
   }

   inline const value operator/(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::div<value>(),p1.base_, p2.base_));
   }

  template <typename charT, typename traits>
  inline std::basic_ostream<charT,traits>&
  operator << (std::basic_ostream<charT,traits>& out,
	       value const& v)
  {
    out << v.to_string();
    return out;
  }
}

#endif //VALUE_HPP
<|endoftext|>


<commit_before>#pragma once

#include <glm/glm.hpp>
#include <set>
#include <array>

namespace mos {
namespace io {

class Mouse {
public:
  Mouse();
  enum class Event {
    Button_press_0,
    Button_release_0,
  };
  using Events = std::set<Event>;

  glm::dvec2 position;
  //TODO: set automaticly
  glm::dvec2 old_position;
  Events events;
  std::array<bool, 3> buttons;
};

}
}
<commit_msg>Mouse<commit_after>#pragma once

#include <glm/glm.hpp>
#include <set>
#include <array>

namespace mos {
namespace io {

class Mouse {
public:
  Mouse();
  enum class Event {
    Button_press_0,
    Button_release_0,
    Button_press_1,
    Button_release_1,
    Button_press_2,
    Button_release_2,
  };
  using Events = std::set<Event>;

  glm::dvec2 position;
  //TODO: set automaticly
  glm::dvec2 old_position;
  Events events;
  std::array<bool, 3> buttons;
};

}
}
<|endoftext|>


<commit_before><commit_msg>wrong place I guess<commit_after><|endoftext|>


<commit_before>// Wheels - various C++ utilities
//
// Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>

// id() function object

#ifndef WHEELS_OP_ID_HPP
#define WHEELS_OP_ID_HPP

#include <wheels/adl/id.h++>

#include <utility> // declval, forward

namespace wheels {
    namespace op {
        struct id {
            template <typename T>
            T&& operator()(T&& t) {
                return std::forward<T>(t);
            }
        };
    } // namespace op
} // namespace wheels

#endif // WHEELS_OP_ID_HPP

<commit_msg>Removed bad include on op::id<commit_after>// Wheels - various C++ utilities
//
// Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>

// identity function object

#ifndef WHEELS_OP_ID_HPP
#define WHEELS_OP_ID_HPP

#include <utility> // forward

namespace wheels {
    namespace op {
        struct id {
            template <typename T>
            T&& operator()(T&& t) {
                return std::forward<T>(t);
            }
        };
    } // namespace op
} // namespace wheels

#endif // WHEELS_OP_ID_HPP

<|endoftext|>


<commit_before>class segtree{
public:
    int n;  // array size
    vector<int> t;
    vector<int> d;
    int h;

    void build(vector<int> &v) {  // build the tree
        for (int i = n; i < 2 * n; i++) t[i] = v[i - n];
        for (int i = n - 1; i > 0; --i) t[i] = max(t[i<<1], t[i<<1|1]);
    }

    void apply(int p, int value) {
        t[p] += value;
        if (p < n) d[p] += value;
    }

    void recalc(int p) {
        while (p > 1) p >>= 1, t[p] = max(t[p<<1], t[p<<1|1]) + d[p];
    }

    void push(int p) {
        for (int s = h; s > 0; --s) {
            int i = p >> s;
            if (d[i] != 0) {
                apply(i<<1, d[i]);
                apply(i<<1|1, d[i]);
                d[i] = 0;
            }
        }
    }

    void inc(int l, int r, int value) {
        l += n, r += n;
        int l0 = l, r0 = r;
        for (; l < r; l >>= 1, r >>= 1) {
            if (l&1) apply(l++, value);
            if (r&1) apply(--r, value);
        }
        recalc(l0);
        recalc(r0 - 1);
    }

    int query(int l, int r) {
        l += n, r += n;
        push(l);
        push(r - 1);
        int res = -2e9;
        for (; l < r; l >>= 1, r >>= 1) {
            if (l&1) res = max(res, t[l++]);
            if (r&1) res = max(t[--r], res);
        }
        return res;
    }

    segtree(int n):n(n),t(){
        h = 32 - __builtin_clz(n);
        t.resize(n << 1, 0);
        d.resize(n << 1, 0);
    }
};
<commit_msg>maxtree_segment_increment updated<commit_after>template<typename T>
struct segtree{
    int n;
    vector<T> t;
    vector<T> d;
    int h;

    void build(vector<T> &v) {
        for (int i = n; i < 2 * n; i++) t[i] = v[i - n];
        for (int i = n - 1; i > 0; --i) t[i] = max(t[i<<1], t[i<<1|1]);
    }

    void apply(int p, T value) {
        t[p] += value;
        if (p < n) d[p] += value;
    }

    void recalc(int p) {
        while (p > 1) p >>= 1, t[p] = max(t[p<<1], t[p<<1|1]) + d[p];
    }

    void push(int p) {
        for (int s = h; s > 0; --s) {
            int i = p >> s;
            if (d[i] != 0) {
                apply(i<<1, d[i]);
                apply(i<<1|1, d[i]);
                d[i] = 0;
            }
        }
    }

    void inc(int l, int r, T value) {
        l += n, r += n;
        int l0 = l, r0 = r;
        for (; l < r; l >>= 1, r >>= 1) {
            if (l & 1) apply(l++, value);
            if (r & 1) apply(--r, value);
        }
        recalc(l0);
        recalc(r0 - 1);
    }

    T query(int l, int r) {
        l += n, r += n;
        push(l);
        push(r - 1);
        T res = numeric_limits<T>::min();
        for (; l < r; l >>= 1, r >>= 1) {
            if (l & 1) res = max(res, t[l++]);
            if (r & 1) res = max(t[--r], res);
        }
        return res;
    }

    segtree(int n): n(n), t(n << 1, 0), h(32 - __builtin_clz(n)), d(n, 0) {}
};
<|endoftext|>


<commit_before>/*
Copyright (c) 2016 Modified Work Barrett Adair

Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

HEADER GUARDS INTENTIONALLY OMITTED
DO NOT INCLUDE THIS HEADER DIRECTLY
*/

#define BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
#define BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE std::false_type
#include <boost/callable_traits/detail/unguarded/function_ptr_varargs_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
#undef BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE

#ifdef BOOST_CLBL_TRTS_ENABLE_TRANSACTION_SAFE
#define BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE std::true_type
#define BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE transaction_safe
#include <boost/callable_traits/detail/unguarded/function_ptr_varargs_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
#undef BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE
#endif // #ifdef BOOST_CLBL_TRTS_ENABLE_TRANSACTION_SAFE<commit_msg>Delete function_ptr_varargs.hpp<commit_after><|endoftext|>


<commit_before>#include "GameClient.h"
#include "Singleton.h"

namespace Chimera {

GameClient::GameClient ( Video *_pVideo, Chimera::SceneMng *_pScenMng ) : pSceneMng ( _pScenMng ), pVideo ( _pVideo )  {

    textoFPS = "fps: " + std::to_string ( 0 );

    pHUD = new HUD ( *pVideo->getPRectangle() );

#ifdef WIN32
    pFont = new Chimera::Font("C:\\Projetos\\ChimeraEngine\\fonts\\FreeSans.ttf", 18);
#else
    pFont = new Chimera::Font ( "/home/locutus/Projetos/ChimeraEngine/fonts/FreeSans.ttf",18 );
#endif

    pHUD->addFont ( pFont );

    SDL_Rect area;
    area.x = 10;
    area.y = 10;
    area.w = 600;
    area.h = 40;

    pHUD->addSquare ( area, Color ( 1.0f,1.0f, 1.0f, 0.1f ) );
    pHUD->addText ( 0,0,0,5,Color::RED,&textoFPS );

    fps = 0;
    timerFPS.setElapsedCount ( 1000 );
    timerFPS.start();

    timerSegundo.setElapsedCount ( 1000 );
    timerSegundo.start();

    //logger = log4cxx::Logger::getLogger ( "GameClient" );

    physicWorld = Singleton<PhysicsControl>::getRefSingleton();
}

GameClient::~GameClient() {

    if ( pHUD )
        delete pHUD;

    Singleton<PhysicsControl>::releaseRefSingleton();
}

bool GameClient::newFPS() {
    return timerSegundo.stepCount();
}

void GameClient::countFrame() {
    if ( timerFPS.stepCount() == true ) {
        fps = timerFPS.getCountStep();
        textoFPS = "fps: " + std::to_string ( fps ) + std::string ( " Periodo: " ) + std::to_string ( physicWorld->getLastPeriod() );
    }
}

void GameClient::open() {

    pVideo->initOpenGL();
    //std::string l_msg =  "OpenGL iniciado com sucesso, versao: " + pSceneMng->getVersaoOpenGL();
    //LOG4CXX_INFO ( logger , l_msg );

    start();

    DataMsg dataMsg ( KindOp::START,this,nullptr,nullptr );
    pSceneMng->update ( &dataMsg );

    pHUD->setOn ( true );
}

void GameClient::close ( void ) {

    SDL_Event l_eventQuit;
    l_eventQuit.type = SDL_QUIT;
    if ( SDL_PushEvent ( &l_eventQuit ) == -1 ) {
        throw ExceptionSDL ( ExceptionCode::CLOSE, std::string ( SDL_GetError() ) );
    }

}

void GameClient::processaGame() {

    physicWorld->stepSim();
    physicWorld->checkCollisions();

    countFrame();
    render();

	pVideo->begin2D();
    pHUD->update();
	pVideo->end2D();

    pVideo->swapWindow();

}

void GameClient::validaOpColisao(const SDL_Event &_event) {

     KindOp op = (KindOp) _event.user.code;

    if ((op == Chimera::KindOp::START_COLLIDE)||
        (op == Chimera::KindOp::ON_COLLIDE) ||
        (op == Chimera::KindOp::OFF_COLLIDE)) {

        executeColisao ( op, (Node*)_event.user.data1,(Node*)_event.user.data2);

    } else {
        userEvent(_event);
    }

}

void GameClient::gameLoop ( void ) {

    SDL_Event l_eventSDL;
    bool l_quit = false;
    bool l_isActive = false;

    while ( !l_quit ) {

        while ( SDL_PollEvent ( &l_eventSDL )) {

            switch ( l_eventSDL.type ) {
            case SDL_USEREVENT:
                validaOpColisao(l_eventSDL);
                break;
            case SDL_KEYDOWN:
                keyCapture ( l_eventSDL.key.keysym.sym );
                break;
            case SDL_MOUSEBUTTONDOWN:
                mouseButtonDownCapture ( l_eventSDL.button );
                break;
            case SDL_MOUSEBUTTONUP:
                mouseButtonUpCapture( l_eventSDL.button );
                break;
            case SDL_MOUSEMOTION:
                mouseMotionCapture ( l_eventSDL.motion );
                break;
            case SDL_QUIT:
                l_quit = true;
                stop();
                break;
            case SDL_WINDOWEVENT: {
                    switch ( l_eventSDL.window.event ) {
                    case SDL_WINDOWEVENT_ENTER:
                        l_isActive = true;
                        break;
                    case SDL_WINDOWEVENT_LEAVE:
                        l_isActive = false;
                        break;
                    default:
                        break;
                    }
                }
                break;
            default:
                break;
            }

        }

        if (l_isActive==true) {
            //Se nao houver foco na tela pule o render
            processaGame();

        }

    }
}

}
// kate: indent-mode cstyle; indent-width 4; replace-tabs on;
<commit_msg>carga relativa da fonte<commit_after>#include "GameClient.h"
#include "Singleton.h"

namespace Chimera {

GameClient::GameClient ( Video *_pVideo, Chimera::SceneMng *_pScenMng ) : pSceneMng ( _pScenMng ), pVideo ( _pVideo )  {

    textoFPS = "fps: " + std::to_string ( 0 );

    pHUD = new HUD ( *pVideo->getPRectangle() );

#ifdef WIN32
    pFont = new Chimera::Font("C:\\Projetos\\ChimeraEngine\\fonts\\FreeSans.ttf", 18);
#else
    pFont = new Chimera::Font ( "../../fonts/FreeSans.ttf",18 );
#endif

    pHUD->addFont ( pFont );

    SDL_Rect area;
    area.x = 10;
    area.y = 10;
    area.w = 600;
    area.h = 40;

    pHUD->addSquare ( area, Color ( 1.0f,1.0f, 1.0f, 0.1f ) );
    pHUD->addText ( 0,0,0,5,Color::RED,&textoFPS );

    fps = 0;
    timerFPS.setElapsedCount ( 1000 );
    timerFPS.start();

    timerSegundo.setElapsedCount ( 1000 );
    timerSegundo.start();

    //logger = log4cxx::Logger::getLogger ( "GameClient" );

    physicWorld = Singleton<PhysicsControl>::getRefSingleton();
}

GameClient::~GameClient() {

    if ( pHUD )
        delete pHUD;

    Singleton<PhysicsControl>::releaseRefSingleton();
}

bool GameClient::newFPS() {
    return timerSegundo.stepCount();
}

void GameClient::countFrame() {
    if ( timerFPS.stepCount() == true ) {
        fps = timerFPS.getCountStep();
        textoFPS = "fps: " + std::to_string ( fps ) + std::string ( " Periodo: " ) + std::to_string ( physicWorld->getLastPeriod() );
    }
}

void GameClient::open() {

    pVideo->initOpenGL();
    //std::string l_msg =  "OpenGL iniciado com sucesso, versao: " + pSceneMng->getVersaoOpenGL();
    //LOG4CXX_INFO ( logger , l_msg );

    start();

    DataMsg dataMsg ( KindOp::START,this,nullptr,nullptr );
    pSceneMng->update ( &dataMsg );

    pHUD->setOn ( true );
}

void GameClient::close ( void ) {

    SDL_Event l_eventQuit;
    l_eventQuit.type = SDL_QUIT;
    if ( SDL_PushEvent ( &l_eventQuit ) == -1 ) {
        throw ExceptionSDL ( ExceptionCode::CLOSE, std::string ( SDL_GetError() ) );
    }

}

void GameClient::processaGame() {

    physicWorld->stepSim();
    physicWorld->checkCollisions();

    countFrame();
    render();

	pVideo->begin2D();
    pHUD->update();
	pVideo->end2D();

    pVideo->swapWindow();

}

void GameClient::validaOpColisao(const SDL_Event &_event) {

     KindOp op = (KindOp) _event.user.code;

    if ((op == Chimera::KindOp::START_COLLIDE)||
        (op == Chimera::KindOp::ON_COLLIDE) ||
        (op == Chimera::KindOp::OFF_COLLIDE)) {

        executeColisao ( op, (Node*)_event.user.data1,(Node*)_event.user.data2);

    } else {
        userEvent(_event);
    }

}

void GameClient::gameLoop ( void ) {

    SDL_Event l_eventSDL;
    bool l_quit = false;
    bool l_isActive = false;

    while ( !l_quit ) {

        while ( SDL_PollEvent ( &l_eventSDL )) {

            switch ( l_eventSDL.type ) {
            case SDL_USEREVENT:
                validaOpColisao(l_eventSDL);
                break;
            case SDL_KEYDOWN:
                keyCapture ( l_eventSDL.key.keysym.sym );
                break;
            case SDL_MOUSEBUTTONDOWN:
                mouseButtonDownCapture ( l_eventSDL.button );
                break;
            case SDL_MOUSEBUTTONUP:
                mouseButtonUpCapture( l_eventSDL.button );
                break;
            case SDL_MOUSEMOTION:
                mouseMotionCapture ( l_eventSDL.motion );
                break;
            case SDL_QUIT:
                l_quit = true;
                stop();
                break;
            case SDL_WINDOWEVENT: {
                    switch ( l_eventSDL.window.event ) {
                    case SDL_WINDOWEVENT_ENTER:
                        l_isActive = true;
                        break;
                    case SDL_WINDOWEVENT_LEAVE:
                        l_isActive = false;
                        break;
                    default:
                        break;
                    }
                }
                break;
            default:
                break;
            }

        }

        if (l_isActive==true) {
            //Se nao houver foco na tela pule o render
            processaGame();

        }

    }
}

}
// kate: indent-mode cstyle; indent-width 4; replace-tabs on;
<|endoftext|>