<commit_before>/** mock_exchange.cc                                 -*- C++ -*-
    Rémi Attab, 18 Feb 2013
    Copyright (c) 2013 Datacratic.  All rights reserved.

    Implementation of the mock exchange.

*/

#include "mock_exchange.h"

#include "rtbkit/core/post_auction/post_auction_loop.h"
#include "soa/service/http_header.h"
#include "jml/utils/smart_ptr_utils.h"

#include <array>

using namespace std;
using namespace ML;

namespace RTBKIT {

/******************************************************************************/
/* MOCK EXCHANGE                                                              */
/******************************************************************************/

MockExchange::
MockExchange(Datacratic::ServiceProxyArguments & args, const std::string& name) :
    ServiceBase(name, args.makeServiceProxies()),
    running(0) {
}

MockExchange::
MockExchange(const shared_ptr<ServiceProxies> proxies, const string& name) :
    ServiceBase(name, proxies),
    running(0) {
}

MockExchange::
~MockExchange() {
    threads.join_all();
}

void
MockExchange::
start(Json::Value const & configuration) {
    auto workers = configuration["workers"];

    for(auto i = workers.begin(), end = workers.end(); i != end; ++i) {
        auto json = *i;
        auto count = json.get("threads", 1).asInt();

        for(auto j = 0; j != count; ++j) {
            std::cerr << "starting worker " << running << std::endl;
            ML::atomic_inc(running);

            threads.create_thread([=]() {
                Worker worker(this, json["bids"], json["wins"], json["events"]);
                worker.run();

                ML::atomic_dec(running);
            });
        }
    }
}

void
MockExchange::
add(BidSource * bid, WinSource * win, EventSource * event) {
    std::cerr << "starting worker " << running << std::endl;
    ML::atomic_inc(running);

    threads.create_thread([=]() {
        Worker worker(this, bid, win, event);
        worker.run();

        ML::atomic_dec(running);
    });
}

MockExchange::Worker::
Worker(MockExchange * exchange, BidSource *bid, WinSource *win, EventSource *event) :
    exchange(exchange),
    bids(bid),
    wins(win),
    events(event),
    rng(random()) {
}

MockExchange::Worker::
Worker(MockExchange * exchange, Json::Value bid, Json::Value win, Json::Value event) :
    exchange(exchange),
    bids(BidSource::createBidSource(std::move(bid))),
    wins(WinSource::createWinSource(std::move(win))),
    events(EventSource::createEventSource(std::move(event))),
    rng(random()) {
}

void
MockExchange::Worker::
run() {
    while(bid());
}

bool
MockExchange::Worker::bid() {
    for (;;) {
        auto br = bids->sendBidRequest();
        exchange->recordHit("requests");

        auto response = bids->receiveBid();
        exchange->recordHit("responses");

        if (!response.first) continue;
        vector<ExchangeSource::Bid> items = response.second;

        for (auto & bid : items) {
            if(bid.maxPrice == 0) continue;
            exchange->recordHit("responses");

            if (!wins) break;

            auto ret = isWin(br, bid);
            if (!ret.first) continue;
			ML::sleep(0.5);

			bid.bidTimestamp = Date::now();

            wins->sendWin(br, bid, ret.second);
            exchange->recordHit("wins");

            events->sendImpression(br, bid);
            exchange->recordHit("impressions");

            if (!isClick(br, bid)) continue;
            events->sendClick(br, bid);
            exchange->recordHit("clicks");
        }

        break;
    }

    return !bids->isDone();
}

pair<bool, Amount>
MockExchange::Worker::isWin(const BidRequest&, const ExchangeSource::Bid& bid) {
    if (rng.random01() >= 0.1)
        return make_pair(false, Amount());

    return make_pair(true, MicroUSD_CPM(bid.maxPrice * 0.6 + bid.maxPrice * rng.random01() * 0.4));
}

bool
MockExchange::Worker::isClick(const BidRequest&, const ExchangeSource::Bid&) {
    return rng.random01() <= 0.1;
}

} // namepsace RTBKIT
<commit_msg>Fixed some of the graphite logging for the mock exchange.<commit_after>/** mock_exchange.cc                                 -*- C++ -*-
    Rémi Attab, 18 Feb 2013
    Copyright (c) 2013 Datacratic.  All rights reserved.

    Implementation of the mock exchange.

*/

#include "mock_exchange.h"

#include "rtbkit/core/post_auction/post_auction_loop.h"
#include "soa/service/http_header.h"
#include "jml/utils/smart_ptr_utils.h"

#include <array>

using namespace std;
using namespace ML;

namespace RTBKIT {

/******************************************************************************/
/* MOCK EXCHANGE                                                              */
/******************************************************************************/

MockExchange::
MockExchange(Datacratic::ServiceProxyArguments & args, const std::string& name) :
    ServiceBase(name, args.makeServiceProxies()),
    running(0) {
}

MockExchange::
MockExchange(const shared_ptr<ServiceProxies> proxies, const string& name) :
    ServiceBase(name, proxies),
    running(0) {
}

MockExchange::
~MockExchange() {
    threads.join_all();
}

void
MockExchange::
start(Json::Value const & configuration) {
    auto workers = configuration["workers"];

    for(auto i = workers.begin(), end = workers.end(); i != end; ++i) {
        auto json = *i;
        auto count = json.get("threads", 1).asInt();

        for(auto j = 0; j != count; ++j) {
            std::cerr << "starting worker " << running << std::endl;
            ML::atomic_inc(running);

            threads.create_thread([=]() {
                Worker worker(this, json["bids"], json["wins"], json["events"]);
                worker.run();

                ML::atomic_dec(running);
            });
        }
    }
}

void
MockExchange::
add(BidSource * bid, WinSource * win, EventSource * event) {
    std::cerr << "starting worker " << running << std::endl;
    ML::atomic_inc(running);

    threads.create_thread([=]() {
        Worker worker(this, bid, win, event);
        worker.run();

        ML::atomic_dec(running);
    });
}

MockExchange::Worker::
Worker(MockExchange * exchange, BidSource *bid, WinSource *win, EventSource *event) :
    exchange(exchange),
    bids(bid),
    wins(win),
    events(event),
    rng(random()) {
}

MockExchange::Worker::
Worker(MockExchange * exchange, Json::Value bid, Json::Value win, Json::Value event) :
    exchange(exchange),
    bids(BidSource::createBidSource(std::move(bid))),
    wins(WinSource::createWinSource(std::move(win))),
    events(EventSource::createEventSource(std::move(event))),
    rng(random()) {
}

void
MockExchange::Worker::
run() {
    while(bid());
}

bool
MockExchange::Worker::bid() {
    for (;;) {
        auto br = bids->sendBidRequest();
        exchange->recordHit("requests");

        auto response = bids->receiveBid();
        exchange->recordHit("responses");

        vector<ExchangeSource::Bid> items = response.second;

        if (!response.first || items.empty()) {
            exchange->recordHit("noBids");
            continue;
        }

        for (auto & bid : items) {
            if(bid.maxPrice == 0) continue;
            exchange->recordHit("bids");

            if (!wins) break;

            auto ret = isWin(br, bid);
            if (!ret.first) continue;
            ML::sleep(0.5);

            bid.bidTimestamp = Date::now();

            wins->sendWin(br, bid, ret.second);
            exchange->recordHit("wins");

            events->sendImpression(br, bid);
            exchange->recordHit("impressions");

            if (!isClick(br, bid)) continue;
            events->sendClick(br, bid);
            exchange->recordHit("clicks");
        }

        break;
    }

    return !bids->isDone();
}

pair<bool, Amount>
MockExchange::Worker::isWin(const BidRequest&, const ExchangeSource::Bid& bid) {
    if (rng.random01() >= 0.1)
        return make_pair(false, Amount());

    return make_pair(true, MicroUSD_CPM(bid.maxPrice * 0.6 + bid.maxPrice * rng.random01() * 0.4));
}

bool
MockExchange::Worker::isClick(const BidRequest&, const ExchangeSource::Bid&) {
    return rng.random01() <= 0.1;
}

} // namepsace RTBKIT
<|endoftext|>


<commit_before>// ------------------------------------------------------------------------------------------------
#include "Core.hpp"
#include "Base/Shared.hpp"
#include "Base/Color3.hpp"
#include "Base/Vector2.hpp"
#include "Base/Vector3.hpp"
#include "Entity/Player.hpp"
#include "Library/Numeric/LongInt.hpp"

// ------------------------------------------------------------------------------------------------
#include "Misc/Functions.hpp"
#include "Misc/Model.hpp"
#include "Misc/Player.hpp"
#include "Misc/Vehicle.hpp"
#include "Misc/Weapon.hpp"

// ------------------------------------------------------------------------------------------------
namespace SqMod {

// ------------------------------------------------------------------------------------------------
static const Object & FindPlayer(Object & by)
{
    switch (by.GetType())
    {
        case OT_INTEGER:
        {
            return Core::Get().GetPlayer(by.Cast< Int32 >()).mObj;
        } break;
        case OT_FLOAT:
        {
            return Core::Get().GetPlayer(std::round(by.Cast< Float32 >())).mObj;
        } break;
        case OT_STRING:
        {
            // Obtain the argument as a string
            String str(by.Cast< String >());
            // Attempt to locate the player with this name
            Int32 id = _Func->GetPlayerIdFromName(&str[0]);
            // Was there a player with this name?
            if (VALID_ENTITYEX(id, SQMOD_PLAYER_POOL))
            {
                Core::Get().GetPlayer(id).mObj;
            }
        } break;
        default: STHROWF("Unsupported search identifier");
    }
    // Default to a null object
    return NullObject();
}

// ================================================================================================
void Register_Misc(HSQUIRRELVM vm)
{
    Table srvns(vm);

    srvns.SquirrelFunc(_SC("SendLogMessage"), &SendLogMessage)
    .Func(_SC("GetVersion"), &GetServerVersion)
    .Func(_SC("GetSettings"), &GetServerSettings)
    .Func(_SC("GetNumberOfPlugins"), &GetNumberOfPlugins)
    .Func(_SC("GetPluginInfo"), &GetPluginInfo)
    .Func(_SC("FindPlugin"), &FindPlugin)
    .Func(_SC("SendPluginCommand"), &SendPluginCommand)
    .Func(_SC("GetTime"), &GetTime)
    .Func(_SC("GetLastError"), &GetLastError)
    .Func(_SC("GetPluginVersion"), &GetPluginVersion)
    .Func(_SC("GetPluginVersionStr"), &GetPluginVersionStr)
    .Func(_SC("GetPluginName"), &GetPluginName)
    .Func(_SC("GetPluginAuthor"), &GetPluginAuthor)
    .Func(_SC("GetPluginID"), &GetPluginID)
    .Func(_SC("GetServerPort"), &GetServerPort)
    .Func(_SC("GetServerFlags"), &GetServerFlags)
    .Func(_SC("GetMaxPlayers"), &GetMaxPlayers)
    .Func(_SC("SetMaxPlayers"), &SetMaxPlayers)
    .Func(_SC("GetServerName"), &GetServerName)
    .Func(_SC("SetServerName"), &SetServerName)
    .Func(_SC("GetPassword"), &GetServerPassword)
    .Func(_SC("SetPassword"), &SetServerPassword)
    .Func(_SC("GetGameModeText"), &GetGameModeText)
    .Func(_SC("SetGameModeText"), &SetGameModeText)
    .Func(_SC("CreateRadioStream"), &CreateRadioStream)
    .Func(_SC("CreateRadioStreamEx"), &CreateRadioStreamEx)
    .Func(_SC("RemoveRadioStream"), &RemoveRadioStream)
    .Func(_SC("Shutdown"), &ShutdownServer)
    .Func(_SC("GetOption"), &GetServerOption)
    .Func(_SC("SetOption"), &SetServerOption)
    .Func(_SC("SetOptionEx"), &SetServerOptionEx)
    .Func(_SC("GetWorldBounds"), &GetWorldBounds)
    .Func(_SC("SetWorldBounds"), &SetWorldBounds)
    .Func(_SC("SetWorldBoundsEx"), &SetWorldBoundsEx)
    .Func(_SC("GetWastedSettings"), &GetWastedSettings)
    .Func(_SC("SetWastedSettings"), &SetWastedSettings)
    .Func(_SC("GetTimeRate"), &GetTimeRate)
    .Func(_SC("SetTimeRate"), &SetTimeRate)
    .Func(_SC("GetHour"), &GetHour)
    .Func(_SC("SetHour"), &SetHour)
    .Func(_SC("GetMinute"), &GetMinute)
    .Func(_SC("SetMinute"), &SetMinute)
    .Func(_SC("GetWeather"), &GetWeather)
    .Func(_SC("SetWeather"), &SetWeather)
    .Func(_SC("GetGravity"), &GetGravity)
    .Func(_SC("SetGravity"), &SetGravity)
    .Func(_SC("GetGameSpeed"), &GetGameSpeed)
    .Func(_SC("SetGameSpeed"), &SetGameSpeed)
    .Func(_SC("GetWaterLevel"), &GetWaterLevel)
    .Func(_SC("SetWaterLevel"), &SetWaterLevel)
    .Func(_SC("GetMaximumFlightAltitude"), &GetMaximumFlightAltitude)
    .Func(_SC("SetMaximumFlightAltitude"), &SetMaximumFlightAltitude)
    .Func(_SC("GetKillCommandDelay"), &GetKillCommandDelay)
    .Func(_SC("SetKillCommandDelay"), &SetKillCommandDelay)
    .Func(_SC("GetVehiclesForcedRespawnHeight"), &GetVehiclesForcedRespawnHeight)
    .Func(_SC("SetVehiclesForcedRespawnHeight"), &SetVehiclesForcedRespawnHeight)
    .Func(_SC("CreateExplosion"), &CreateExplosion)
    .Func(_SC("CreateExplosionEx"), &CreateExplosionEx)
    .Func(_SC("PlaySound"), &PlaySound)
    .Func(_SC("PlaySoundEx"), &PlaySoundEx)
    .Func(_SC("HideMapObject"), &HideMapObject)
    .Func(_SC("HideMapObjectEx"), &SetKeyCodeName)
    .Func(_SC("HideMapObjectRaw"), &HideMapObjectRaw)
    .Func(_SC("ShowMapObject"), &ShowMapObject)
    .Func(_SC("ShowMapObjectEx"), &ShowMapObjectEx)
    .Func(_SC("ShowMapObjectRaw"), &ShowMapObjectRaw)
    .Func(_SC("ShowAllMapObjects"), &ShowAllMapObjects)
    .Func(_SC("GetWeaponDataValue"), &GetWeaponDataValue)
    .Func(_SC("SetWeaponDataValue"), &SetWeaponDataValue)
    .Func(_SC("ResetWeaponDataValue"), &ResetWeaponDataValue)
    .Func(_SC("IsWeaponDataValueModified"), &IsWeaponDataValueModified)
    .Func(_SC("ResetWeaponData"), &ResetWeaponData)
    .Func(_SC("ResetAllWeaponData"), &ResetAllWeaponData)
    .Func(_SC("AddPlayerClass"), &AddPlayerClass)
    .Func(_SC("SetSpawnPlayerPosition"), &SetSpawnPlayerPosition)
    .Func(_SC("SetSpawnCameraPosition"), &SetSpawnCameraPosition)
    .Func(_SC("SetSpawnCameraLookAt"), &SetSpawnCameraLookAt)
    .Func(_SC("SetSpawnPlayerPositionEx"), &SetSpawnPlayerPositionEx)
    .Func(_SC("SetSpawnCameraPositionEx"), &SetSpawnCameraPositionEx)
    .Func(_SC("SetSpawnCameraLookAtEx"), &SetSpawnCameraLookAtEx)
    .Func(_SC("BanIP"), &BanIP)
    .Func(_SC("UnbanIP"), &UnbanIP)
    .Func(_SC("IsIPBanned"), &IsIPBanned)
    .Func(_SC("GetPlayerIdFromName"), &GetPlayerIdFromName)
    .Func(_SC("IsPlayerConnected"), &IsPlayerConnected)
    .Func(_SC("ForceAllSelect"), &ForceAllSelect)
    .Func(_SC("CheckEntityExists"), &SetKeyCodeName);

    RootTable(vm).Bind(_SC("SqServer"), srvns);

    RootTable(vm)
    .Func(_SC("FindPlayer"), &FindPlayer)
    .Func(_SC("GetKeyCodeName"), &GetKeyCodeName)
    .Func(_SC("SetKeyCodeName"), &SetKeyCodeName)
    .Func(_SC("GetModelName"), &GetModelName)
    .Func(_SC("SetModelName"), &SetModelName)
    .Func(_SC("IsModelWeapon"), &IsModelWeapon)
    .Func(_SC("IsModelActuallyWeapon"), &IsModelActuallyWeapon)
    .Func(_SC("GetSkinName"), &GetSkinName)
    .Func(_SC("SetSkinName"), &SetSkinName)
    .Func(_SC("GetSkinID"), &GetSkinID)
    .Func(_SC("IsSkinValid"), &IsSkinValid)
    .Func(_SC("GetAutomobileName"), &GetAutomobileName)
    .Func(_SC("SetAutomobileName"), &SetAutomobileName)
    .Func(_SC("GetAutomobileID"), &GetAutomobileID)
    .Func(_SC("IsAutomobileValid"), &IsAutomobileValid)
    .Func(_SC("GetWeaponName"), &GetWeaponName)
    .Func(_SC("SetWeaponName"), &SetWeaponName)
    .Func(_SC("GetWeaponID"), &GetWeaponID)
    .Func(_SC("IsWeaponValid"), &IsWeaponValid)
    .Func(_SC("WeaponToModel"), &WeaponToModel)
    .Func(_SC("IsWeaponNatural"), &IsWeaponNatural)
    .Func(_SC("PlaySound"), &PlaySound)
    .Func(_SC("PlaySoundEx"), &PlaySoundEx)
    .Func(_SC("CreateExplosion"), &CreateExplosion)
    .Func(_SC("CreateExplosionEx"), &CreateExplosionEx);
}

} // Namespace:: SqMod
<commit_msg>Implement functions to broadcast messages to all players.<commit_after>// ------------------------------------------------------------------------------------------------
#include "Core.hpp"
#include "Base/Shared.hpp"
#include "Base/Color3.hpp"
#include "Base/Color4.hpp"
#include "Base/Vector2.hpp"
#include "Base/Vector3.hpp"
#include "Entity/Player.hpp"
#include "Library/Numeric/LongInt.hpp"

// ------------------------------------------------------------------------------------------------
#include "Misc/Functions.hpp"
#include "Misc/Model.hpp"
#include "Misc/Player.hpp"
#include "Misc/Vehicle.hpp"
#include "Misc/Weapon.hpp"

// ------------------------------------------------------------------------------------------------
namespace SqMod {

// ------------------------------------------------------------------------------------------------
static const Object & FindPlayer(Object & by)
{
    switch (by.GetType())
    {
        case OT_INTEGER:
        {
            return Core::Get().GetPlayer(by.Cast< Int32 >()).mObj;
        } break;
        case OT_FLOAT:
        {
            return Core::Get().GetPlayer(std::round(by.Cast< Float32 >())).mObj;
        } break;
        case OT_STRING:
        {
            // Obtain the argument as a string
            String str(by.Cast< String >());
            // Attempt to locate the player with this name
            Int32 id = _Func->GetPlayerIdFromName(&str[0]);
            // Was there a player with this name?
            if (VALID_ENTITYEX(id, SQMOD_PLAYER_POOL))
            {
                Core::Get().GetPlayer(id).mObj;
            }
        } break;
        default: STHROWF("Unsupported search identifier");
    }
    // Default to a null object
    return NullObject();
}

// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastMsg(HSQUIRRELVM vm)
{
    const Int32 top = sq_gettop(vm);
    // Was the message color specified?
    if (top <= 1)
    {
        return sq_throwerror(vm, "Missing message color");
    }
    // Was the message value specified?
    else if (top <= 2)
    {
        return sq_throwerror(vm, "Missing message value");
    }
    // Failed to retrieve a Color4 value
    bool failed = false;
    // The message color
    Color4 color;
    // Attempt to extract the argument values
    try
    {
        color = Var< Color4 >(vm, 2).value;
    }
    catch (...)
    {
        failed = true;
    }
    // Did we failed to retrieve a Color4 instance?
    if (failed)
    {
        // Attempt to extract the argument values
        try
        {
            color = Var< Color3 >(vm, 2).value;
        }
        catch (const Sqrat::Exception & e)
        {
            // Propagate the error
            return sq_throwerror(vm, e.Message().c_str());
        }
    }
    // Attempt to generate the string value
    StackStrF val(vm, 3);
    // Have we failed to retrieve the string?
    if (SQ_FAILED(val.mRes))
    {
        return val.mRes; // Propagate the error!
    }
    // Obtain the ends of the entity pool
    Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();
    Core::Players::const_iterator end = Core::Get().GetPlayers().cend();
    // The number of players that the message was sent to
    Uint32 count = 0;
    // Process each entity in the pool
    for (; itr != end; ++itr)
    {
        // Is this player instance valid?
        if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)
        {
            // Grab the player instance
            CPlayer * player = itr->mInst;
            // Send the resulted message string
            const vcmpError result = _Func->SendClientMessage(itr->mID, color.GetRGBA(),
                                                        "%s%s%s",
                                                        player->mMessagePrefix.c_str(),
                                                        val.mPtr,
                                                        player->mMessagePostfix.c_str());
            // Check the result
            if (result == vcmpErrorTooLargeInput)
            {
                return sq_throwerror(vm, ToStrF("Client message too big [%s]", player->GetTag().c_str()));
            }
            // Add this player to the count
            ++count;
        }
    }
    // Push the count count on the stack
    sq_pushinteger(vm, count);
    // Specify that this function returned a value
    return 1;
}

// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastMsgP(HSQUIRRELVM vm)
{
    const Int32 top = sq_gettop(vm);
    // Was the index of the message prefix specified?
    if (top <= 1)
    {
        return sq_throwerror(vm, "Missing prefix index");
    }
    // Was the message value specified?
    else if (top <= 2)
    {
        return sq_throwerror(vm, "Missing message value");
    }
    // The prefix index
    Uint32 index;
    // Attempt to extract the argument values
    try
    {
        index = Var< Uint32 >(vm, 2).value;
    }
    catch (const Sqrat::Exception & e)
    {
        // Propagate the error
        return sq_throwerror(vm, e.Message().c_str());
    }
    // Perform a range check on the specified prefix index
    if (index > SQMOD_PLAYER_MSG_PREFIXES)
    {
        return sq_throwerror(vm, ToStrF("Prefix index is out of range: %u > %u",
                                        index, SQMOD_PLAYER_MSG_PREFIXES));
    }
    // Attempt to generate the string value
    StackStrF val(vm, 3);
    // Have we failed to retrieve the string?
    if (SQ_FAILED(val.mRes))
    {
        return val.mRes; // Propagate the error!
    }
    vcmpError result = vcmpErrorNone;
    // Send the resulted message string
    // Obtain the ends of the entity pool
    Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();
    Core::Players::const_iterator end = Core::Get().GetPlayers().cend();
    // The number of players that the message was sent to
    Uint32 count = 0;
    // Process each entity in the pool
    for (; itr != end; ++itr)
    {
        // Is this player instance valid?
        if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)
        {
            // Grab the player instance
            CPlayer * player = itr->mInst;
            // Send the resulted message string
            if (player->mLimitPrefixPostfixMessage)
            {
                result = _Func->SendClientMessage(itr->mID, player->mMessageColor, "%s%s",
                                                    player->mMessagePrefixes[index].c_str(), val.mPtr);
            }
            else
            {
                result = _Func->SendClientMessage(itr->mID, player->mMessageColor, "%s%s%s%s",
                                                    player->mMessagePrefix.c_str(),
                                                    player->mMessagePrefixes[index].c_str(), val.mPtr,
                                                    player->mMessagePostfix.c_str());
            }
            // Check the result
            if (result == vcmpErrorTooLargeInput)
            {
                return sq_throwerror(vm, ToStrF("Client message too big [%s]", player->GetTag().c_str()));
            }
            // Add this player to the count
            ++count;
        }
    }
    // Push the count count on the stack
    sq_pushinteger(vm, count);
    // Specify that this function returned a value
    return 1;
}

// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastMsgEx(HSQUIRRELVM vm)
{
    const Int32 top = sq_gettop(vm);
    // Was the message color specified?
    if (top <= 4)
    {
        return sq_throwerror(vm, "Missing message color");
    }
    // Was the message value specified?
    else if (top <= 5)
    {
        return sq_throwerror(vm, "Missing message value");
    }
    // The message color
    Uint32 color;
    // Attempt to extract the argument values
    try
    {
        color = SQMOD_PACK_RGBA(Var< Uint8 >(vm, 2).value,
                                Var< Uint8 >(vm, 3).value,
                                Var< Uint8 >(vm, 4).value,
                                Var< Uint8 >(vm, 5).value);
    }
    catch (const Sqrat::Exception & e)
    {
        // Propagate the error
        return sq_throwerror(vm, e.Message().c_str());
    }
    // Attempt to generate the string value
    StackStrF val(vm, 6);
    // Have we failed to retrieve the string?
    if (SQ_FAILED(val.mRes))
    {
        return val.mRes; // Propagate the error!
    }
    // Obtain the ends of the entity pool
    Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();
    Core::Players::const_iterator end = Core::Get().GetPlayers().cend();
    // The number of players that the message was sent to
    Uint32 count = 0;
    // Process each entity in the pool
    for (; itr != end; ++itr)
    {
        // Is this player instance valid?
        if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)
        {
            // Grab the player instance
            CPlayer * player = itr->mInst;
            // Send the resulted message string
            const vcmpError result = _Func->SendClientMessage(itr->mID, color,
                                                                "%s%s%s",
                                                                player->mMessagePrefix.c_str(),
                                                                val.mPtr,
                                                                player->mMessagePostfix.c_str());
            // Check the result
            if (result == vcmpErrorTooLargeInput)
            {
                return sq_throwerror(vm, ToStrF("Client message too big [%s]", player->GetTag().c_str()));
            }
            // Add this player to the count
            ++count;
        }
    }
    // Push the count count on the stack
    sq_pushinteger(vm, count);
    // Specify that this function returned a value
    return 1;
}

// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastMessage(HSQUIRRELVM vm)
{
    const Int32 top = sq_gettop(vm);
    // Was the message value specified?
    if (top <= 1)
    {
        return sq_throwerror(vm, "Missing message value");
    }
    // Attempt to generate the string value
    StackStrF val(vm, 2);
    // Have we failed to retrieve the string?
    if (SQ_FAILED(val.mRes))
    {
        return val.mRes; // Propagate the error!
    }
    // Obtain the ends of the entity pool
    Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();
    Core::Players::const_iterator end = Core::Get().GetPlayers().cend();
    // The number of players that the message was sent to
    Uint32 count = 0;
    // Process each entity in the pool
    for (; itr != end; ++itr)
    {
        // Is this player instance valid?
        if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)
        {
            // Grab the player instance
            CPlayer * player = itr->mInst;
            // Send the resulted message string
            const vcmpError result = _Func->SendClientMessage(itr->mID, player->mMessageColor,
                                                                "%s%s%s",
                                                                player->mMessagePrefix.c_str(),
                                                                val.mPtr,
                                                                player->mMessagePostfix.c_str());
            // Check the result
            if (result == vcmpErrorTooLargeInput)
            {
                return sq_throwerror(vm, ToStrF("Client message too big [%s]", player->GetTag().c_str()));
            }
            // Add this player to the count
            ++count;
        }
    }
    // Push the count count on the stack
    sq_pushinteger(vm, count);
    // Specify that this function returned a value
    return 1;
}

// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastAnnounce(HSQUIRRELVM vm)
{
    const Int32 top = sq_gettop(vm);
    // Was the announcement value specified?
    if (top <= 1)
    {
        return sq_throwerror(vm, "Missing announcement value");
    }
    // Attempt to generate the string value
    StackStrF val(vm, 2);
    // Have we failed to retrieve the string?
    if (SQ_FAILED(val.mRes))
    {
        return val.mRes; // Propagate the error!
    }
    // Obtain the ends of the entity pool
    Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();
    Core::Players::const_iterator end = Core::Get().GetPlayers().cend();
    // The number of players that the message was sent to
    Uint32 count = 0;
    // Process each entity in the pool
    for (; itr != end; ++itr)
    {
        // Is this player instance valid?
        if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)
        {
            // Grab the player instance
            CPlayer * player = itr->mInst;
            // Send the resulted announcement string
            const vcmpError result = _Func->SendGameMessage(itr->mID, player->mAnnounceStyle,
                                                            "%s%s%s",
                                                            player->mAnnouncePrefix.c_str(),
                                                            val.mPtr,
                                                            player->mAnnouncePostfix.c_str());
            // Validate the result
            if (result == vcmpErrorArgumentOutOfBounds)
            {
                return sq_throwerror(vm, ToStrF("Invalid announcement style [%s]", player->GetTag().c_str()));
            }
            else if (result == vcmpErrorTooLargeInput)
            {
                return sq_throwerror(vm, ToStrF("Game message too big [%s]", player->GetTag().c_str()));
            }
            // Add this player to the count
            ++count;
        }
    }
    // Push the count count on the stack
    sq_pushinteger(vm, count);
    // Specify that this function returned a value
    return 1;
}

// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastAnnounceEx(HSQUIRRELVM vm)
{
    const Int32 top = sq_gettop(vm);
    // Was the announcement style specified?
    if (top <= 1)
    {
        return sq_throwerror(vm, "Missing announcement style");
    }
    // Was the announcement value specified?
    else if (top <= 2)
    {
        return sq_throwerror(vm, "Missing announcement value");
    }
    // The announcement style
    Int32 style;
    // style to extract the argument values
    try
    {
        style = Var< Int32 >(vm, 2).value;
    }
    catch (const Sqrat::Exception & e)
    {
        // Propagate the error
        return sq_throwerror(vm, e.Message().c_str());
    }
    // Attempt to generate the string value
    StackStrF val(vm, 3);
    // Have we failed to retrieve the string?
    if (SQ_FAILED(val.mRes))
    {
        return val.mRes; // Propagate the error!
    }
    // Obtain the ends of the entity pool
    Core::Players::const_iterator itr = Core::Get().GetPlayers().cbegin();
    Core::Players::const_iterator end = Core::Get().GetPlayers().cend();
    // The number of players that the message was sent to
    Uint32 count = 0;
    // Process each entity in the pool
    for (; itr != end; ++itr)
    {
        // Is this player instance valid?
        if (VALID_ENTITYEX(itr->mID, SQMOD_PLAYER_POOL) && itr->mInst != nullptr)
        {
            // Grab the player instance
            CPlayer * player = itr->mInst;
            // Send the resulted announcement string
            const vcmpError result = _Func->SendGameMessage(itr->mID, style,
                                                            "%s%s%s",
                                                            player->mAnnouncePrefix.c_str(),
                                                            val.mPtr,
                                                            player->mAnnouncePostfix.c_str());
            // Validate the result
            if (result == vcmpErrorArgumentOutOfBounds)
            {
                return sq_throwerror(vm, ToStrF("Invalid announcement style [%s]", player->GetTag().c_str()));
            }
            else if (result == vcmpErrorTooLargeInput)
            {
                return sq_throwerror(vm, ToStrF("Game message too big [%s]", player->GetTag().c_str()));
            }
            // Add this player to the count
            ++count;
        }
    }
    // Push the count count on the stack
    sq_pushinteger(vm, count);
    // Specify that this function returned a value
    return 1;
}

// ================================================================================================
void Register_Misc(HSQUIRRELVM vm)
{
    Table srvns(vm);

    srvns.SquirrelFunc(_SC("SendLogMessage"), &SendLogMessage)
    .Func(_SC("GetVersion"), &GetServerVersion)
    .Func(_SC("GetSettings"), &GetServerSettings)
    .Func(_SC("GetNumberOfPlugins"), &GetNumberOfPlugins)
    .Func(_SC("GetPluginInfo"), &GetPluginInfo)
    .Func(_SC("FindPlugin"), &FindPlugin)
    .Func(_SC("SendPluginCommand"), &SendPluginCommand)
    .Func(_SC("GetTime"), &GetTime)
    .Func(_SC("GetLastError"), &GetLastError)
    .Func(_SC("GetPluginVersion"), &GetPluginVersion)
    .Func(_SC("GetPluginVersionStr"), &GetPluginVersionStr)
    .Func(_SC("GetPluginName"), &GetPluginName)
    .Func(_SC("GetPluginAuthor"), &GetPluginAuthor)
    .Func(_SC("GetPluginID"), &GetPluginID)
    .Func(_SC("GetServerPort"), &GetServerPort)
    .Func(_SC("GetServerFlags"), &GetServerFlags)
    .Func(_SC("GetMaxPlayers"), &GetMaxPlayers)
    .Func(_SC("SetMaxPlayers"), &SetMaxPlayers)
    .Func(_SC("GetServerName"), &GetServerName)
    .Func(_SC("SetServerName"), &SetServerName)
    .Func(_SC("GetPassword"), &GetServerPassword)
    .Func(_SC("SetPassword"), &SetServerPassword)
    .Func(_SC("GetGameModeText"), &GetGameModeText)
    .Func(_SC("SetGameModeText"), &SetGameModeText)
    .Func(_SC("CreateRadioStream"), &CreateRadioStream)
    .Func(_SC("CreateRadioStreamEx"), &CreateRadioStreamEx)
    .Func(_SC("RemoveRadioStream"), &RemoveRadioStream)
    .Func(_SC("Shutdown"), &ShutdownServer)
    .Func(_SC("GetOption"), &GetServerOption)
    .Func(_SC("SetOption"), &SetServerOption)
    .Func(_SC("SetOptionEx"), &SetServerOptionEx)
    .Func(_SC("GetWorldBounds"), &GetWorldBounds)
    .Func(_SC("SetWorldBounds"), &SetWorldBounds)
    .Func(_SC("SetWorldBoundsEx"), &SetWorldBoundsEx)
    .Func(_SC("GetWastedSettings"), &GetWastedSettings)
    .Func(_SC("SetWastedSettings"), &SetWastedSettings)
    .Func(_SC("GetTimeRate"), &GetTimeRate)
    .Func(_SC("SetTimeRate"), &SetTimeRate)
    .Func(_SC("GetHour"), &GetHour)
    .Func(_SC("SetHour"), &SetHour)
    .Func(_SC("GetMinute"), &GetMinute)
    .Func(_SC("SetMinute"), &SetMinute)
    .Func(_SC("GetWeather"), &GetWeather)
    .Func(_SC("SetWeather"), &SetWeather)
    .Func(_SC("GetGravity"), &GetGravity)
    .Func(_SC("SetGravity"), &SetGravity)
    .Func(_SC("GetGameSpeed"), &GetGameSpeed)
    .Func(_SC("SetGameSpeed"), &SetGameSpeed)
    .Func(_SC("GetWaterLevel"), &GetWaterLevel)
    .Func(_SC("SetWaterLevel"), &SetWaterLevel)
    .Func(_SC("GetMaximumFlightAltitude"), &GetMaximumFlightAltitude)
    .Func(_SC("SetMaximumFlightAltitude"), &SetMaximumFlightAltitude)
    .Func(_SC("GetKillCommandDelay"), &GetKillCommandDelay)
    .Func(_SC("SetKillCommandDelay"), &SetKillCommandDelay)
    .Func(_SC("GetVehiclesForcedRespawnHeight"), &GetVehiclesForcedRespawnHeight)
    .Func(_SC("SetVehiclesForcedRespawnHeight"), &SetVehiclesForcedRespawnHeight)
    .Func(_SC("CreateExplosion"), &CreateExplosion)
    .Func(_SC("CreateExplosionEx"), &CreateExplosionEx)
    .Func(_SC("PlaySound"), &PlaySound)
    .Func(_SC("PlaySoundEx"), &PlaySoundEx)
    .Func(_SC("HideMapObject"), &HideMapObject)
    .Func(_SC("HideMapObjectEx"), &SetKeyCodeName)
    .Func(_SC("HideMapObjectRaw"), &HideMapObjectRaw)
    .Func(_SC("ShowMapObject"), &ShowMapObject)
    .Func(_SC("ShowMapObjectEx"), &ShowMapObjectEx)
    .Func(_SC("ShowMapObjectRaw"), &ShowMapObjectRaw)
    .Func(_SC("ShowAllMapObjects"), &ShowAllMapObjects)
    .Func(_SC("GetWeaponDataValue"), &GetWeaponDataValue)
    .Func(_SC("SetWeaponDataValue"), &SetWeaponDataValue)
    .Func(_SC("ResetWeaponDataValue"), &ResetWeaponDataValue)
    .Func(_SC("IsWeaponDataValueModified"), &IsWeaponDataValueModified)
    .Func(_SC("ResetWeaponData"), &ResetWeaponData)
    .Func(_SC("ResetAllWeaponData"), &ResetAllWeaponData)
    .Func(_SC("AddPlayerClass"), &AddPlayerClass)
    .Func(_SC("SetSpawnPlayerPosition"), &SetSpawnPlayerPosition)
    .Func(_SC("SetSpawnCameraPosition"), &SetSpawnCameraPosition)
    .Func(_SC("SetSpawnCameraLookAt"), &SetSpawnCameraLookAt)
    .Func(_SC("SetSpawnPlayerPositionEx"), &SetSpawnPlayerPositionEx)
    .Func(_SC("SetSpawnCameraPositionEx"), &SetSpawnCameraPositionEx)
    .Func(_SC("SetSpawnCameraLookAtEx"), &SetSpawnCameraLookAtEx)
    .Func(_SC("BanIP"), &BanIP)
    .Func(_SC("UnbanIP"), &UnbanIP)
    .Func(_SC("IsIPBanned"), &IsIPBanned)
    .Func(_SC("GetPlayerIdFromName"), &GetPlayerIdFromName)
    .Func(_SC("IsPlayerConnected"), &IsPlayerConnected)
    .Func(_SC("ForceAllSelect"), &ForceAllSelect)
    .Func(_SC("CheckEntityExists"), &SetKeyCodeName);

    RootTable(vm).Bind(_SC("SqServer"), srvns);

    RootTable(vm)
    .Func(_SC("FindPlayer"), &FindPlayer)
    .Func(_SC("GetKeyCodeName"), &GetKeyCodeName)
    .Func(_SC("SetKeyCodeName"), &SetKeyCodeName)
    .Func(_SC("GetModelName"), &GetModelName)
    .Func(_SC("SetModelName"), &SetModelName)
    .Func(_SC("IsModelWeapon"), &IsModelWeapon)
    .Func(_SC("IsModelActuallyWeapon"), &IsModelActuallyWeapon)
    .Func(_SC("GetSkinName"), &GetSkinName)
    .Func(_SC("SetSkinName"), &SetSkinName)
    .Func(_SC("GetSkinID"), &GetSkinID)
    .Func(_SC("IsSkinValid"), &IsSkinValid)
    .Func(_SC("GetAutomobileName"), &GetAutomobileName)
    .Func(_SC("SetAutomobileName"), &SetAutomobileName)
    .Func(_SC("GetAutomobileID"), &GetAutomobileID)
    .Func(_SC("IsAutomobileValid"), &IsAutomobileValid)
    .Func(_SC("GetWeaponName"), &GetWeaponName)
    .Func(_SC("SetWeaponName"), &SetWeaponName)
    .Func(_SC("GetWeaponID"), &GetWeaponID)
    .Func(_SC("IsWeaponValid"), &IsWeaponValid)
    .Func(_SC("WeaponToModel"), &WeaponToModel)
    .Func(_SC("IsWeaponNatural"), &IsWeaponNatural)
    .Func(_SC("PlaySound"), &PlaySound)
    .Func(_SC("PlaySoundEx"), &PlaySoundEx)
    .Func(_SC("CreateExplosion"), &CreateExplosion)
    .Func(_SC("CreateExplosionEx"), &CreateExplosionEx)
    .SquirrelFunc(_SC("SqBroadcastMsg"), &SqBroadcastMsg)
    .SquirrelFunc(_SC("SqBroadcastMsgP"), &SqBroadcastMsgP)
    .SquirrelFunc(_SC("SqBroadcastMsgEx"), &SqBroadcastMsgEx)
    .SquirrelFunc(_SC("SqBroadcastMessage"), &SqBroadcastMessage)
    .SquirrelFunc(_SC("SqBroadcastAnnounce"), &SqBroadcastAnnounce)
    .SquirrelFunc(_SC("SqBroadcastAnnounceEx"), &SqBroadcastAnnounceEx)
    .SquirrelFunc(_SC("SqBroadcastText"), &SqBroadcastAnnounce)
    .SquirrelFunc(_SC("SqBroadcastTextEx"), &SqBroadcastAnnounceEx);
}

} // Namespace:: SqMod
<|endoftext|>


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

#ifndef _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#define _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX

#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX
#include <svx/sdr/contact/viewobjectcontact.hxx>
#endif

namespace avmedia { class MediaItem; }
class Window;

namespace sdr
{
    namespace contact
    {
        class SdrMediaWindow;

        class ViewObjectContactOfSdrMediaObj : public ViewObjectContact
        {
        public:

            ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,
                                            ViewContact& rViewContact,
                                            const ::avmedia::MediaItem& rMediaItem );

            // The destructor. When PrepareDelete() was not called before (see there)
            // warnings will be generated in debug version if there are still contacts
            // existing.
            virtual ~ViewObjectContactOfSdrMediaObj();

        public:

            Window* getWindow() const;

            bool    hasPreferredSize() const;
            Size    getPreferredSize() const;

            void    updateMediaItem( ::avmedia::MediaItem& rItem ) const;
            void    executeMediaItem( const ::avmedia::MediaItem& rItem );

        protected:

            // Prepare deletion of this object. This needs to be called always
            // before really deleting this objects. This is necessary since in a c++
            // destructor no virtual function calls are allowed. To avoid this problem,
            // it is required to first call PrepareDelete().
            virtual void PrepareDelete();

            // Paint this object. This is before evtl. SubObjects get painted. This method
            // needs to set the flag mbIsPainted and mbIsInvalidated and to set the
            // maPaintedRectangle member. This information is later used for invalidates
            // and repaints.
            virtual void PaintObject(DisplayInfo& rDisplayInfo);

        private:

            ::sdr::contact::SdrMediaWindow* mpMediaWindow;
        };
    } // end of namespace contact
} // end of namespace sdr

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

#endif // _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
<commit_msg>INTEGRATION: CWS aw039 (1.5.58); FILE MERGED 2006/12/19 12:57:05 aw 1.5.58.1: #i72701# added ShouldPaintObject to media object VC and changed VOC paint accordingly<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: viewobjectcontactofsdrmediaobj.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2007-01-22 15:13:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#define _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX

#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX
#include <svx/sdr/contact/viewobjectcontact.hxx>
#endif

namespace avmedia { class MediaItem; }
class Window;

namespace sdr
{
    namespace contact
    {
        class SdrMediaWindow;

        class ViewObjectContactOfSdrMediaObj : public ViewObjectContact
        {
        public:

            ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,
                                            ViewContact& rViewContact,
                                            const ::avmedia::MediaItem& rMediaItem );

            // The destructor. When PrepareDelete() was not called before (see there)
            // warnings will be generated in debug version if there are still contacts
            // existing.
            virtual ~ViewObjectContactOfSdrMediaObj();

        public:

            Window* getWindow() const;

            bool    hasPreferredSize() const;
            Size    getPreferredSize() const;

            void    updateMediaItem( ::avmedia::MediaItem& rItem ) const;
            void    executeMediaItem( const ::avmedia::MediaItem& rItem );

            // #i72701#
            void checkMediaWindowPosition(DisplayInfo& rDisplayInfo) const;

        protected:

            // Prepare deletion of this object. This needs to be called always
            // before really deleting this objects. This is necessary since in a c++
            // destructor no virtual function calls are allowed. To avoid this problem,
            // it is required to first call PrepareDelete().
            virtual void PrepareDelete();

            // Paint this object. This is before evtl. SubObjects get painted. This method
            // needs to set the flag mbIsPainted and mbIsInvalidated and to set the
            // maPaintedRectangle member. This information is later used for invalidates
            // and repaints.
            virtual void PaintObject(DisplayInfo& rDisplayInfo);

        private:

            ::sdr::contact::SdrMediaWindow* mpMediaWindow;
        };
    } // end of namespace contact
} // end of namespace sdr

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

#endif // _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
<|endoftext|>


<commit_before>#include "global.h"
#include "txn_table.h"
#include "tpcc_query.h"
#include "tpcc.h"
#include "ycsb_query.h"
#include "ycsb.h"
#include "query.h"
#include "txn.h"
#include "mem_alloc.h"
#include "row.h"
#include "plock.h"
#include "txn_pool.h"

#define MODIFY_START(i) {\
    pthread_mutex_lock(&pool[i].mtx);\
    while(pool[i].modify || pool[i].access > 0)\
      pthread_cond_wait(&pool[i].cond_m,&pool[i].mtx);\
    pool[i].modify = true; \
    pthread_mutex_unlock(&pool[i].mtx); }

#define MODIFY_END(i) {\
  pthread_mutex_lock(&pool[i].mtx);\
  pool[i].modify = false;\
  pthread_cond_signal(&pool[i].cond_m); \
  pthread_cond_broadcast(&pool[i].cond_a); \
  pthread_mutex_unlock(&pool[i].mtx); }

#define ACCESS_START(i) {\
  pthread_mutex_lock(&pool[i].mtx);\
  while(pool[i].modify)\
      pthread_cond_wait(&pool[i].cond_a,&pool[i].mtx);\
  pool[i].access++;\
  pthread_mutex_unlock(&pool[i].mtx); }

#define ACCESS_END(i) {\
  pthread_mutex_lock(&pool[i].mtx);\
  pool[i].access--;\
  pthread_cond_signal(&pool[i].cond_m);\
  pthread_mutex_unlock(&pool[i].mtx); }

void TxnTable::init() {
  pthread_mutex_init(&mtx,NULL);
  pthread_cond_init(&cond_m,NULL);
  pthread_cond_init(&cond_a,NULL);
  modify = false;
  access = 0;
  cnt = 0;
  table_min_ts = UINT64_MAX;
  pool_size = g_inflight_max * g_node_cnt * 2 + 1;
  pool = (pool_node_t) mem_allocator.alloc(sizeof(pool_node) * pool_size , g_thread_cnt);
  for(uint32_t i = 0; i < pool_size;i++) {
    pool[i].head = NULL;
    pool[i].tail = NULL;
    pool[i].cnt = 0;
    pthread_mutex_init(&pool[i].mtx,NULL);
    pthread_cond_init(&pool[i].cond_m,NULL);
    pthread_cond_init(&pool[i].cond_a,NULL);
    pool[i].modify = false;
    pool[i].access = 0;
    pool[i].min_ts = UINT64_MAX;
  }
}

bool TxnTable::empty(uint64_t node_id) {
  return ts_pool.empty();
}

void TxnTable::add_txn(uint64_t node_id, txn_man * txn, base_query * qry) {

  uint64_t thd_prof_start = get_sys_clock();
  txn->set_query(qry);
  uint64_t txn_id = txn->get_txn_id();
  assert(txn_id == qry->txn_id);

  txn_man * next_txn = NULL;
  assert(txn->get_txn_id() == qry->txn_id);

  MODIFY_START(txn_id % pool_size);

  txn_node_t t_node = pool[txn_id % pool_size].head;

  while (t_node != NULL) {
    if (t_node->txn->get_txn_id() == txn_id) {
      next_txn = t_node->txn;
      break;
    }
    t_node = t_node->next;
  }

  if(next_txn == NULL) {
    //t_node = (txn_node_t) mem_allocator.alloc(sizeof(struct txn_node), g_thread_cnt);
  pthread_mutex_lock(&mtx);
    ts_pool.insert(TsMapPair(txn->get_ts(),NULL));
  pthread_mutex_unlock(&mtx);
    txn_table_pool.get(t_node);
    t_node->txn = txn;
    t_node->qry = qry;
    LIST_PUT_TAIL(pool[txn_id % pool_size].head,pool[txn_id % pool_size].tail,t_node);
    pool[txn_id % pool_size].cnt++;
    if(pool[txn_id % pool_size].cnt > 1) {
      INC_STATS(0,txn_table_cflt,1);
      INC_STATS(0,txn_table_cflt_size,pool[txn_id % pool_size].cnt-1);
    }
    cnt++;
  }
  else {
    if(txn->get_ts() != t_node->txn->get_ts()) {
  pthread_mutex_lock(&mtx);
      ts_pool.erase(t_node->txn->get_ts());
      ts_pool.insert(TsMapPair(txn->get_ts(),NULL));
  pthread_mutex_unlock(&mtx);
    }
    t_node->txn = txn;
    t_node->qry = qry;
  }

  MODIFY_END(txn_id % pool_size);
  INC_STATS(0,thd_prof_txn_table_add,get_sys_clock() - thd_prof_start);
}
void TxnTable::get_txn(uint64_t node_id, uint64_t txn_id,txn_man *& txn,base_query *& qry){

  uint64_t thd_prof_start = get_sys_clock();
  txn = NULL;
  qry = NULL;
  INC_STATS(0,thd_prof_get_txn_cnt,1);
  ACCESS_START(txn_id % pool_size);

  txn_node_t t_node = pool[txn_id % pool_size].head;

  while (t_node != NULL) {
    if (t_node->txn->get_txn_id() == txn_id) {
      txn = t_node->txn;
      qry = t_node->qry;
      assert(txn->get_txn_id() == qry->txn_id);
      break;
    }
    t_node = t_node->next;
  }

  ACCESS_END(txn_id % pool_size);
  INC_STATS(0,thd_prof_txn_table_get,get_sys_clock() - thd_prof_start);

}

void TxnTable::restart_txn(uint64_t txn_id){
  MODIFY_START(txn_id % pool_size);

  txn_node_t t_node = pool[txn_id % pool_size].head;

  while (t_node != NULL) {
    if (t_node->txn->get_txn_id() == txn_id) {
      if(txn_id % g_node_cnt == g_node_id)
        t_node->qry->rtype = RTXN;
      else
        t_node->qry->rtype = RQRY;
      work_queue.enqueue(0,t_node->qry);
      break;
    }
    t_node = t_node->next;
  }

  MODIFY_END(txn_id % pool_size);

}

void TxnTable::delete_txn(uint64_t node_id, uint64_t txn_id){
  uint64_t thd_prof_start = get_sys_clock();
  uint64_t starttime = thd_prof_start;

  MODIFY_START(txn_id % pool_size);

  txn_node_t t_node = pool[txn_id % pool_size].head;

  while (t_node != NULL) {
    if (t_node->txn->get_txn_id() == txn_id) {
      LIST_REMOVE_HT(t_node,pool[txn_id % pool_size].head,pool[txn_id % pool_size].tail);
      pool[txn_id % pool_size].cnt--;
      cnt--;
      break;
    }
    t_node = t_node->next;
  }
  pthread_mutex_lock(&mtx);
  TsMap::iterator it2 = ts_pool.find(t_node->txn->get_ts());
  if(it2 != ts_pool.end())
    ts_pool.erase(it2);
  pthread_mutex_unlock(&mtx);

  MODIFY_END(txn_id % pool_size)

  if(t_node != NULL) {
    INC_STATS(0,thd_prof_txn_table1a,get_sys_clock() - thd_prof_start);
    thd_prof_start = get_sys_clock();
    assert(!t_node->txn->spec || t_node->txn->state == DONE);
#if WORKLOAD == TPCC
    /*
    t_node->txn->release();
    mem_allocator.free(t_node->txn, sizeof(tpcc_txn_man));
    if(t_node->qry->txn_id % g_node_cnt != node_id) {
      mem_allocator.free(t_node->qry, sizeof(tpcc_query));
    }
    */
    if(t_node->txn) {
      t_node->txn->release();
      txn_pool.put(t_node->txn);
    }
#elif WORKLOAD == YCSB
    if(t_node->txn) {
      //t_node->txn->release();
      //mem_allocator.free(t_node->txn, sizeof(ycsb_txn_man));
      t_node->txn->release();
      txn_pool.put(t_node->txn);
    }

    if(t_node->qry) {
      //YCSB_QUERY_FREE(t_node->qry)
      qry_pool.put(t_node->qry);
    }
#endif
    //mem_allocator.free(t_node, sizeof(struct txn_node));
    txn_table_pool.put(t_node);
    INC_STATS(0,thd_prof_txn_table2a,get_sys_clock() - thd_prof_start);
  }
  else {

    INC_STATS(0,thd_prof_txn_table1b,get_sys_clock() - thd_prof_start);
  }
  INC_STATS(0,thd_prof_txn_table2,get_sys_clock() - starttime);
}

uint64_t TxnTable::get_min_ts() {

  uint64_t min = UINT64_MAX;
  pthread_mutex_lock(&mtx);
  TsMap::iterator it = ts_pool.lower_bound(0);
  if(it != ts_pool.end())
    min = it->first;
  pthread_mutex_unlock(&mtx);
  return min;

}

void TxnTable::snapshot() {
}

<commit_msg>Removed txn_table.cnt race condition<commit_after>#include "global.h"
#include "txn_table.h"
#include "tpcc_query.h"
#include "tpcc.h"
#include "ycsb_query.h"
#include "ycsb.h"
#include "query.h"
#include "txn.h"
#include "mem_alloc.h"
#include "row.h"
#include "plock.h"
#include "txn_pool.h"

#define MODIFY_START(i) {\
    pthread_mutex_lock(&pool[i].mtx);\
    while(pool[i].modify || pool[i].access > 0)\
      pthread_cond_wait(&pool[i].cond_m,&pool[i].mtx);\
    pool[i].modify = true; \
    pthread_mutex_unlock(&pool[i].mtx); }

#define MODIFY_END(i) {\
  pthread_mutex_lock(&pool[i].mtx);\
  pool[i].modify = false;\
  pthread_cond_signal(&pool[i].cond_m); \
  pthread_cond_broadcast(&pool[i].cond_a); \
  pthread_mutex_unlock(&pool[i].mtx); }

#define ACCESS_START(i) {\
  pthread_mutex_lock(&pool[i].mtx);\
  while(pool[i].modify)\
      pthread_cond_wait(&pool[i].cond_a,&pool[i].mtx);\
  pool[i].access++;\
  pthread_mutex_unlock(&pool[i].mtx); }

#define ACCESS_END(i) {\
  pthread_mutex_lock(&pool[i].mtx);\
  pool[i].access--;\
  pthread_cond_signal(&pool[i].cond_m);\
  pthread_mutex_unlock(&pool[i].mtx); }

void TxnTable::init() {
  pthread_mutex_init(&mtx,NULL);
  pthread_cond_init(&cond_m,NULL);
  pthread_cond_init(&cond_a,NULL);
  modify = false;
  access = 0;
  cnt = 0;
  table_min_ts = UINT64_MAX;
  pool_size = g_inflight_max * g_node_cnt * 2 + 1;
  pool = (pool_node_t) mem_allocator.alloc(sizeof(pool_node) * pool_size , g_thread_cnt);
  for(uint32_t i = 0; i < pool_size;i++) {
    pool[i].head = NULL;
    pool[i].tail = NULL;
    pool[i].cnt = 0;
    pthread_mutex_init(&pool[i].mtx,NULL);
    pthread_cond_init(&pool[i].cond_m,NULL);
    pthread_cond_init(&pool[i].cond_a,NULL);
    pool[i].modify = false;
    pool[i].access = 0;
    pool[i].min_ts = UINT64_MAX;
  }
}

bool TxnTable::empty(uint64_t node_id) {
  return ts_pool.empty();
}

void TxnTable::add_txn(uint64_t node_id, txn_man * txn, base_query * qry) {

  uint64_t thd_prof_start = get_sys_clock();
  txn->set_query(qry);
  uint64_t txn_id = txn->get_txn_id();
  assert(txn_id == qry->txn_id);

  txn_man * next_txn = NULL;
  assert(txn->get_txn_id() == qry->txn_id);

  MODIFY_START(txn_id % pool_size);

  txn_node_t t_node = pool[txn_id % pool_size].head;

  while (t_node != NULL) {
    if (t_node->txn->get_txn_id() == txn_id) {
      next_txn = t_node->txn;
      break;
    }
    t_node = t_node->next;
  }

  if(next_txn == NULL) {
    //t_node = (txn_node_t) mem_allocator.alloc(sizeof(struct txn_node), g_thread_cnt);
  pthread_mutex_lock(&mtx);
    ts_pool.insert(TsMapPair(txn->get_ts(),NULL));
  pthread_mutex_unlock(&mtx);
    txn_table_pool.get(t_node);
    t_node->txn = txn;
    t_node->qry = qry;
    LIST_PUT_TAIL(pool[txn_id % pool_size].head,pool[txn_id % pool_size].tail,t_node);
    pool[txn_id % pool_size].cnt++;
    if(pool[txn_id % pool_size].cnt > 1) {
      INC_STATS(0,txn_table_cflt,1);
      INC_STATS(0,txn_table_cflt_size,pool[txn_id % pool_size].cnt-1);
    }
    ATOM_ADD(cnt,1);
  }
  else {
    if(txn->get_ts() != t_node->txn->get_ts()) {
  pthread_mutex_lock(&mtx);
      ts_pool.erase(t_node->txn->get_ts());
      ts_pool.insert(TsMapPair(txn->get_ts(),NULL));
  pthread_mutex_unlock(&mtx);
    }
    t_node->txn = txn;
    t_node->qry = qry;
  }

  MODIFY_END(txn_id % pool_size);
  INC_STATS(0,thd_prof_txn_table_add,get_sys_clock() - thd_prof_start);
}
void TxnTable::get_txn(uint64_t node_id, uint64_t txn_id,txn_man *& txn,base_query *& qry){

  uint64_t thd_prof_start = get_sys_clock();
  txn = NULL;
  qry = NULL;
  INC_STATS(0,thd_prof_get_txn_cnt,1);
  ACCESS_START(txn_id % pool_size);

  txn_node_t t_node = pool[txn_id % pool_size].head;

  while (t_node != NULL) {
    if (t_node->txn->get_txn_id() == txn_id) {
      txn = t_node->txn;
      qry = t_node->qry;
      assert(txn->get_txn_id() == qry->txn_id);
      break;
    }
    t_node = t_node->next;
  }

  ACCESS_END(txn_id % pool_size);
  INC_STATS(0,thd_prof_txn_table_get,get_sys_clock() - thd_prof_start);

}

void TxnTable::restart_txn(uint64_t txn_id){
  MODIFY_START(txn_id % pool_size);

  txn_node_t t_node = pool[txn_id % pool_size].head;

  while (t_node != NULL) {
    if (t_node->txn->get_txn_id() == txn_id) {
      if(txn_id % g_node_cnt == g_node_id)
        t_node->qry->rtype = RTXN;
      else
        t_node->qry->rtype = RQRY;
      work_queue.enqueue(0,t_node->qry);
      break;
    }
    t_node = t_node->next;
  }

  MODIFY_END(txn_id % pool_size);

}

void TxnTable::delete_txn(uint64_t node_id, uint64_t txn_id){
  uint64_t thd_prof_start = get_sys_clock();
  uint64_t starttime = thd_prof_start;

  MODIFY_START(txn_id % pool_size);

  txn_node_t t_node = pool[txn_id % pool_size].head;

  while (t_node != NULL) {
    if (t_node->txn->get_txn_id() == txn_id) {
      LIST_REMOVE_HT(t_node,pool[txn_id % pool_size].head,pool[txn_id % pool_size].tail);
      pool[txn_id % pool_size].cnt--;
      ATOM_SUB(cnt,1);
      break;
    }
    t_node = t_node->next;
  }
  pthread_mutex_lock(&mtx);
  TsMap::iterator it2 = ts_pool.find(t_node->txn->get_ts());
  if(it2 != ts_pool.end())
    ts_pool.erase(it2);
  pthread_mutex_unlock(&mtx);

  MODIFY_END(txn_id % pool_size)

  if(t_node != NULL) {
    INC_STATS(0,thd_prof_txn_table1a,get_sys_clock() - thd_prof_start);
    thd_prof_start = get_sys_clock();
    assert(!t_node->txn->spec || t_node->txn->state == DONE);
#if WORKLOAD == TPCC
    /*
    t_node->txn->release();
    mem_allocator.free(t_node->txn, sizeof(tpcc_txn_man));
    if(t_node->qry->txn_id % g_node_cnt != node_id) {
      mem_allocator.free(t_node->qry, sizeof(tpcc_query));
    }
    */
    if(t_node->txn) {
      t_node->txn->release();
      txn_pool.put(t_node->txn);
    }
#elif WORKLOAD == YCSB
    if(t_node->txn) {
      //t_node->txn->release();
      //mem_allocator.free(t_node->txn, sizeof(ycsb_txn_man));
      t_node->txn->release();
      txn_pool.put(t_node->txn);
    }

    if(t_node->qry) {
      //YCSB_QUERY_FREE(t_node->qry)
      qry_pool.put(t_node->qry);
    }
#endif
    //mem_allocator.free(t_node, sizeof(struct txn_node));
    txn_table_pool.put(t_node);
    INC_STATS(0,thd_prof_txn_table2a,get_sys_clock() - thd_prof_start);
  }
  else {

    INC_STATS(0,thd_prof_txn_table1b,get_sys_clock() - thd_prof_start);
  }
  INC_STATS(0,thd_prof_txn_table2,get_sys_clock() - starttime);
}

uint64_t TxnTable::get_min_ts() {

  uint64_t min = UINT64_MAX;
  pthread_mutex_lock(&mtx);
  TsMap::iterator it = ts_pool.lower_bound(0);
  if(it != ts_pool.end())
    min = it->first;
  pthread_mutex_unlock(&mtx);
  return min;

}

void TxnTable::snapshot() {
}

<|endoftext|>


<commit_before>#include <babylon/cameras/free_camera.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/meshes/mesh.h>
#include <babylon/postprocesses/black_and_white_post_process.h>
#include <babylon/postprocesses/blur_post_process.h>
#include <babylon/postprocesses/renderpipeline/post_process_render_effect.h>
#include <babylon/postprocesses/renderpipeline/post_process_render_pipeline.h>
#include <babylon/postprocesses/renderpipeline/post_process_render_pipeline_manager.h>
#include <babylon/samples/samples_index.h>

namespace BABYLON {
namespace Samples {

/**
 * @brief Simple post process render pipeline scene. This example demonstrates how to use the post
 * process renders pipeline.
 * @see https://www.babylonjs-playground.com/#QCGFI6
 */
class SimplePostProcessRenderPipelineScene : public IRenderableScene {

public:
  SimplePostProcessRenderPipelineScene(ICanvas* iCanvas)
      : IRenderableScene(iCanvas), _blackAndWhite{nullptr}, _horizontalBlur{nullptr}
  {
  }

  ~SimplePostProcessRenderPipelineScene() override = default;

  const char* getName() override
  {
    return "Simple Post Process Render Pipeline Scene";
  }

  void initializeScene(ICanvas* canvas, Scene* scene) override
  {
    // Create a basic scene
    auto camera = FreeCamera::New("camera1", Vector3(0.f, 5.f, -10.f), scene);
    camera->setTarget(Vector3::Zero());
    camera->attachControl(canvas, true);
    auto light           = HemisphericLight::New("light1", Vector3(0, 1, 0), scene);
    light->intensity     = 0.7f;
    auto sphere          = Mesh::CreateSphere("sphere1", 16, 2, scene);
    sphere->position().y = 1.f;
    auto ground          = Mesh::CreateGround("ground1", 6, 6, 2, scene);

    // Get the engine reference
    auto engine = scene->getEngine();

    // Create a standard pipeline
    auto standardPipeline = PostProcessRenderPipeline::New(engine, "standardPipeline");

    // Create post processes
    _blackAndWhite  = BlackAndWhitePostProcess::New("bw", 1.f, nullptr, 0, engine, false);
    _horizontalBlur = BlurPostProcess::New("hb", Vector2(1.f, 0.f), 20.f, 1.f, nullptr,
                                           std::nullopt, engine, false);

    // Create effect with multiple post processes and add to pipeline
    auto blackAndWhiteThenBlur = PostProcessRenderEffect::New(
      engine, "blackAndWhiteThenBlur", [this]() -> std::vector<PostProcessPtr> {
        return {_blackAndWhite, _horizontalBlur};
      });
    standardPipeline->addEffect(blackAndWhiteThenBlur);

    // Add pipeline to the scene's manager and attach to the camera
    scene->postProcessRenderPipelineManager()->addPipeline(standardPipeline);
    scene->postProcessRenderPipelineManager()->attachCamerasToRenderPipeline("standardPipeline",
                                                                             camera);
  }

private:
  PostProcessPtr _blackAndWhite, _horizontalBlur;

}; // end of class SimplePostProcessRenderPipelineScene

BABYLON_REGISTER_SAMPLE("Special FX", SimplePostProcessRenderPipelineScene)

} // end of namespace Samples
} // end of namespace BABYLON
<commit_msg>Using default sample mode for BlackAndWhitePostProcess<commit_after>#include <babylon/cameras/free_camera.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/meshes/mesh.h>
#include <babylon/postprocesses/black_and_white_post_process.h>
#include <babylon/postprocesses/blur_post_process.h>
#include <babylon/postprocesses/renderpipeline/post_process_render_effect.h>
#include <babylon/postprocesses/renderpipeline/post_process_render_pipeline.h>
#include <babylon/postprocesses/renderpipeline/post_process_render_pipeline_manager.h>
#include <babylon/samples/samples_index.h>

namespace BABYLON {
namespace Samples {

/**
 * @brief Simple post process render pipeline scene. This example demonstrates how to use the post
 * process renders pipeline.
 * @see https://www.babylonjs-playground.com/#QCGFI6
 */
class SimplePostProcessRenderPipelineScene : public IRenderableScene {

public:
  SimplePostProcessRenderPipelineScene(ICanvas* iCanvas)
      : IRenderableScene(iCanvas), _blackAndWhite{nullptr}, _horizontalBlur{nullptr}
  {
  }

  ~SimplePostProcessRenderPipelineScene() override = default;

  const char* getName() override
  {
    return "Simple Post Process Render Pipeline Scene";
  }

  void initializeScene(ICanvas* canvas, Scene* scene) override
  {
    // Create a basic scene
    auto camera = FreeCamera::New("camera1", Vector3(0.f, 5.f, -10.f), scene);
    camera->setTarget(Vector3::Zero());
    camera->attachControl(canvas, true);
    auto light           = HemisphericLight::New("light1", Vector3(0, 1, 0), scene);
    light->intensity     = 0.7f;
    auto sphere          = Mesh::CreateSphere("sphere1", 16, 2, scene);
    sphere->position().y = 1.f;
    auto ground          = Mesh::CreateGround("ground1", 6, 6, 2, scene);

    // Get the engine reference
    auto engine = scene->getEngine();

    // Create a standard pipeline
    auto standardPipeline = PostProcessRenderPipeline::New(engine, "standardPipeline");

    // Create post processes
    _blackAndWhite = BlackAndWhitePostProcess::New("bw", 1.f, nullptr, std::nullopt, engine, false);
    _horizontalBlur = BlurPostProcess::New("hb", Vector2(1.f, 0.f), 20.f, 1.f, nullptr,
                                           std::nullopt, engine, false);

    // Create effect with multiple post processes and add to pipeline
    auto blackAndWhiteThenBlur = PostProcessRenderEffect::New(
      engine, "blackAndWhiteThenBlur", [this]() -> std::vector<PostProcessPtr> {
        return {_blackAndWhite, _horizontalBlur};
      });
    standardPipeline->addEffect(blackAndWhiteThenBlur);

    // Add pipeline to the scene's manager and attach to the camera
    scene->postProcessRenderPipelineManager()->addPipeline(standardPipeline);
    scene->postProcessRenderPipelineManager()->attachCamerasToRenderPipeline("standardPipeline",
                                                                             camera);
  }

private:
  PostProcessPtr _blackAndWhite, _horizontalBlur;

}; // end of class SimplePostProcessRenderPipelineScene

BABYLON_REGISTER_SAMPLE("Special FX", SimplePostProcessRenderPipelineScene)

} // end of namespace Samples
} // end of namespace BABYLON
<|endoftext|>


<commit_before>//A ROOT macro that prepares Tree for TMVA training
//----------------------------------------------
//Author: Maxwell Cui
//Date: Aug 19, 2017
//----------------------------------------------

#include<iostream>
#include<cstdlib>
#include<string>
#include<fstream>

void create(TFile* inputTree, TString outputName)
{
  TTree *oldTree=new TTree;
  inputTree->GetObject("nominal_Loose",oldTree);

  //Deactive all branches
  oldTree->SetBranchStatus("*",0);

  //Active the interested branches
  oldTree->SetBranchStatus("ht",1);
  oldTree->SetBranchStatus("met_met",1);
  oldTree->SetBranchStatus("met_sumet",1);
  oldTree->SetBranchStatus("mu_pt",1);
  oldTree->SetBranchStatus("el_pt",1);
  oldTree->SetBranchStatus("mu",1);
  oldTree->SetBranchStatus("jet_pt",1);
  oldTree->SetBranchStatus("met_phi",1);
  oldTree->SetBranchStatus("SSee_2016",1);
  oldTree->SetBranchStatus("SSmm_2016",1);
  oldTree->SetBranchStatus("SSem_2016",1);
  oldTree->SetBranchStatus("eee_2016",1);
  oldTree->SetBranchStatus("eem_2016",1);
  oldTree->SetBranchStatus("emm_2016",1);
  oldTree->SetBranchStatus("mmm_2016",1);
  oldTree->SetBranchStatus("lep_pt",1);
  oldTree->SetBranchStatus("jet_mv2c10",1);   //Using MV2c10 for b-tagging
  oldTree->SetBranchStatus("weight_mc",1);

  //====================Output file==========================
  //
  TFile *outputFile=new TFile(outputName,"recreate");
  //
  //=========================================================

  //Copy to new tree
  TTree *newTree=oldTree->CloneTree();

  //Working with b-jet
  //
  // Declaration of leaf types
  Float_t         mu;
  vector<float>   *el_pt;
  vector<float>   *mu_pt;
  vector<float>   *jet_pt;
  vector<float>   *jet_mv2c10;
  Float_t         met_met;
  Float_t         met_phi;
  Float_t         met_sumet;
  Int_t           SSee_2016;
  Int_t           SSmm_2016;
  Int_t           SSem_2016;
  Int_t           eee_2016;
  Int_t           eem_2016;
  Int_t           emm_2016;
  Int_t           mmm_2016;
  vector<float>   *lep_pt;
  Float_t         ht;

  // List of branches
  TBranch        *b_mu;   //!
  TBranch        *b_el_pt;   //!
  TBranch        *b_mu_pt;   //!
  TBranch        *b_jet_pt;   //!
  TBranch        *b_jet_mv2c10;   //!
  TBranch        *b_met_met;   //!
  TBranch        *b_met_sumet;
  TBranch        *b_met_phi;   //!
  TBranch        *b_SSee_2016;   //!
  TBranch        *b_SSmm_2016;   //!
  TBranch        *b_SSem_2016;   //!
  TBranch        *b_eee_2016;   //!
  TBranch        *b_eem_2016;   //!
  TBranch        *b_emm_2016;   //!
  TBranch        *b_mmm_2016;   //!
  TBranch        *b_lep_pt;   //!
  TBranch        *b_ht;   //!

  //Set object pointer
  el_pt = 0;
  mu_pt = 0;
  jet_pt = 0;
  jet_mv2c10 = 0;
  lep_pt = 0;

  //Set branch addresses and brunch pointers
  oldTree->SetBranchAddress("mu", &mu, &b_mu);
  oldTree->SetBranchAddress("el_pt", &el_pt, &b_el_pt);
  oldTree->SetBranchAddress("mu_pt", &mu_pt, &b_mu_pt);
  oldTree->SetBranchAddress("jet_pt", &jet_pt, &b_jet_pt);
  oldTree->SetBranchAddress("jet_mv2c10", &jet_mv2c10, &b_jet_mv2c10);
  oldTree->SetBranchAddress("met_met", &met_met, &b_met_met);
  oldTree->SetBranchAddress("met_phi", &met_phi, &b_met_phi);
  oldTree->SetBranchAddress("met_sumet", &met_sumet, &b_met_sumet);
  oldTree->SetBranchAddress("SSee_2016", &SSee_2016, &b_SSee_2016);
  oldTree->SetBranchAddress("SSmm_2016", &SSmm_2016, &b_SSmm_2016);
  oldTree->SetBranchAddress("SSem_2016", &SSem_2016, &b_SSem_2016);
  oldTree->SetBranchAddress("eee_2016", &eee_2016, &b_eee_2016);
  oldTree->SetBranchAddress("eem_2016", &eem_2016, &b_eem_2016);
  oldTree->SetBranchAddress("emm_2016", &emm_2016, &b_emm_2016);
  oldTree->SetBranchAddress("mmm_2016", &mmm_2016, &b_mmm_2016);
  oldTree->SetBranchAddress("lep_pt", &lep_pt, &b_lep_pt);
  oldTree->SetBranchAddress("ht", &ht, &b_ht);

  //Declare bjet variable
  Int_t bjet;

  //Add new branch
  TBranch *bjetBranch=newTree->Branch("bjet",&bjet,"bjet/I");

  Int_t nentries=(Int_t)oldTree->GetEntries();

  //Calculate bjet, algorithm is provided by Prof. Varnes
  for(Int_t i=0;i<nentries;i++)
    {
      oldTree->GetEntry(i);
      bjet=0;
      if(SSee_2016 || SSem_2016 || SSmm_2016 || eee_2016 || eem_2016 || emm_2016 || mmm_2016)
      	{
      	  for(unsigned int ibjet=0;ibjet<jet_mv2c10->size();ibjet++)
      	    {
      	      ///     if  (jet_mv2c10->at(ibjet) > 0.1758475) {  // 85% WP
	      if  (jet_mv2c10->at(ibjet) > 0.645925)
		{  // 77% WP
		  //if (jet_mv2c10->at(ibjet) > 0.8244273) {  // 70% WP
		bjet++;
		}
      	    }
      	}
      bjetBranch->Fill();
    }

  //Working with normalization
  //
  Float_t lumi=36.1;

  //Declare leaf and branch
  Float_t         weight_mc;
  Float_t         weight_jvt;
  Float_t         weight_leptonSF_tightLeps;
  Float_t         weight_indiv_SF_MU_TTVA;
  Float_t         weight_pileup;
  Float_t         weight_bTagSF_77;

  TBranch        *b_weight_mc;
  TBranch        *b_weight_jvt;
  TBranch        *b_weight_leptonSF_tightLeps;
  TBranch        *b_weight_indiv_SF_MU_TTVA;
  TBranch        *b_weight_pileup;
  TBranch        *b_weight_bTagSF_77;

  //Set branch addresses and brunch pointers
  oldTree->SetBranchAddress("weight_mc", &weight_mc, &b_weight_mc);
  oldTree->SetBranchAddress("weight_jvt", &weight_jvt, &b_weight_jvt);
  oldTree->SetBranchAddress("weight_leptonSF_tightLeps", &weight_leptonSF_tightLeps, &b_weight_leptonSF_tightLeps);
  oldTree->SetBranchAddress("weight_indiv_SF_MU_TTVA", &weight_indiv_SF_MU_TTVA, &b_weight_indiv_SF_MU_TTVA);
  oldTree->SetBranchAddress("weight_pileup", &weight_pileup, &b_weight_pileup);
  oldTree->SetBranchAddress("weight_bTagSF_77", &weight_bTagSF_77, &b_weight_bTagSF_77);

  //Get the data...algrithm is from Prof. Varnes
  TH1F *lumInt=new TH1F;
  inputTree->GetObject("hIntLum",lumInt);
  Float_t mcnorm=lumInt->GetBinContent(1);

  //Declare variable for event weight
  Float_t evtWeight;
  TBranch *evtBranch=newTree->Branch("evtWeight",&evtWeight,"evtWeight/D");

  std::cout<<"mcnorm is: "<<mcnorm<<std::endl;

  for(Int_t j=0;j<nentries;j++)
    {
      oldTree->GetEntry(j);
      evtWeight=weight_mc*weight_jvt*(weight_leptonSF_tightLeps/weight_indiv_SF_MU_TTVA)*weight_pileup*weight_bTagSF_77*lumi/mcnorm;
      std::cout<<"The weight_jvt is: "<<weight_jvt<<std::endl;
      //std::cout<<"The event weight is: "<<evtWeight<<std::endl;
      evtBranch->Fill();
    }

  newTree->Fill();
  newTree->Print();
  newTree->Write();

  outputFile->Close();

  delete oldTree;
  delete lumInt;
}

void prepTree()
{

  //Variable 'envName' can be the environmental variable on the system that
  //includes the path to the directory of the data files.
  //Please make sure that the variable is exported.

  const char* envName="MCDATA";
  std::string dataPATH=std::getenv(envName);
  if(dataPATH.empty())
    {
      std::cout<<"\tData path not found! Please make sure you export MCDATA which contains the path of data.\n";
    }
  else
    {
      std::cout<<"\tData path is: "<<dataPATH<<std::endl<<std::endl;
    }

  std::ifstream inputFile("datafiles.txt");
  std::string fileName;

  while(std::getline(inputFile,fileName))
    {
      TString fullInput;
      fullInput=dataPATH+"/"+fileName;
      std::cout<<"Readig file: "<<fullInput<<std::endl;

      TString outputName;
      outputName="normalized_"+fileName;

      TFile *bg=new TFile(fullInput);
      create(bg,outputName);
      delete bg;

    }
  inputFile.close();
}
<commit_msg>major update<commit_after>//A ROOT macro that prepares Tree for TMVA training
//----------------------------------------------
//Author: Maxwell Cui
//Created date: Aug 19, 2017
//Latest modified: Sep 7, 2017
//----------------------------------------------

#include<iostream>
#include<cstdlib>
#include<string>
#include<fstream>

void create(TFile* inputTree, TString outputName)
{
  TTree *oldTree=new TTree;
  inputTree->GetObject("nominal_Loose",oldTree);

  //Deactive all branches
  oldTree->SetBranchStatus("*",0);

  //Active the interested branches
  oldTree->SetBranchStatus("ht",1);
  oldTree->SetBranchStatus("met_met",1);
  oldTree->SetBranchStatus("met_sumet",1);
  oldTree->SetBranchStatus("mu_pt",1);
  oldTree->SetBranchStatus("el_pt",1);
  oldTree->SetBranchStatus("mu",1);
  oldTree->SetBranchStatus("jet_pt",1);
  oldTree->SetBranchStatus("met_phi",1);
  oldTree->SetBranchStatus("SSee_2016",1);
  oldTree->SetBranchStatus("SSmm_2016",1);
  oldTree->SetBranchStatus("SSem_2016",1);
  oldTree->SetBranchStatus("eee_2016",1);
  oldTree->SetBranchStatus("eem_2016",1);
  oldTree->SetBranchStatus("emm_2016",1);
  oldTree->SetBranchStatus("mmm_2016",1);
  oldTree->SetBranchStatus("lep_pt",1);
  oldTree->SetBranchStatus("jet_mv2c10",1);   //Using MV2c10 for b-tagging

  oldTree->SetBranchStatus("weight_mc",1);
  oldTree->SetBranchStatus("weight_jvt",1);
  oldTree->SetBranchStatus("weight_leptonSF_tightLeps",1);
  oldTree->SetBranchStatus("weight_indiv_SF_MU_TTVA",1);
  oldTree->SetBranchStatus("weight_pileup",1);
  oldTree->SetBranchStatus("weight_bTagSF_77",1);

  //====================Output file==========================
  //
  TFile *outputFile=new TFile(outputName,"recreate");
  //
  //=========================================================

  //Copy to new tree
  TTree *newTree=oldTree->CloneTree();

  //Working with b-jet
  //
  // Declaration of leaf types
  Float_t         mu;
  vector<float>   *el_pt;
  vector<float>   *mu_pt;
  vector<float>   *jet_pt;
  vector<float>   *jet_mv2c10;
  Float_t         met_met;
  Float_t         met_phi;
  Float_t         met_sumet;
  Int_t           SSee_2016;
  Int_t           SSmm_2016;
  Int_t           SSem_2016;
  Int_t           eee_2016;
  Int_t           eem_2016;
  Int_t           emm_2016;
  Int_t           mmm_2016;
  vector<float>   *lep_pt;
  Float_t         ht;

  // List of branches
  TBranch        *b_mu;   //!
  TBranch        *b_el_pt;   //!
  TBranch        *b_mu_pt;   //!
  TBranch        *b_jet_pt;   //!
  TBranch        *b_jet_mv2c10;   //!
  TBranch        *b_met_met;   //!
  TBranch        *b_met_sumet;
  TBranch        *b_met_phi;   //!
  TBranch        *b_SSee_2016;   //!
  TBranch        *b_SSmm_2016;   //!
  TBranch        *b_SSem_2016;   //!
  TBranch        *b_eee_2016;   //!
  TBranch        *b_eem_2016;   //!
  TBranch        *b_emm_2016;   //!
  TBranch        *b_mmm_2016;   //!
  TBranch        *b_lep_pt;   //!
  TBranch        *b_ht;   //!

  //Set object pointer
  el_pt = 0;
  mu_pt = 0;
  jet_pt = 0;
  jet_mv2c10 = 0;
  lep_pt = 0;

  //Set branch addresses and brunch pointers
  oldTree->SetBranchAddress("mu", &mu, &b_mu);
  oldTree->SetBranchAddress("el_pt", &el_pt, &b_el_pt);
  oldTree->SetBranchAddress("mu_pt", &mu_pt, &b_mu_pt);
  oldTree->SetBranchAddress("jet_pt", &jet_pt, &b_jet_pt);
  oldTree->SetBranchAddress("jet_mv2c10", &jet_mv2c10, &b_jet_mv2c10);
  oldTree->SetBranchAddress("met_met", &met_met, &b_met_met);
  oldTree->SetBranchAddress("met_phi", &met_phi, &b_met_phi);
  oldTree->SetBranchAddress("met_sumet", &met_sumet, &b_met_sumet);
  oldTree->SetBranchAddress("SSee_2016", &SSee_2016, &b_SSee_2016);
  oldTree->SetBranchAddress("SSmm_2016", &SSmm_2016, &b_SSmm_2016);
  oldTree->SetBranchAddress("SSem_2016", &SSem_2016, &b_SSem_2016);
  oldTree->SetBranchAddress("eee_2016", &eee_2016, &b_eee_2016);
  oldTree->SetBranchAddress("eem_2016", &eem_2016, &b_eem_2016);
  oldTree->SetBranchAddress("emm_2016", &emm_2016, &b_emm_2016);
  oldTree->SetBranchAddress("mmm_2016", &mmm_2016, &b_mmm_2016);
  oldTree->SetBranchAddress("lep_pt", &lep_pt, &b_lep_pt);
  oldTree->SetBranchAddress("ht", &ht, &b_ht);

  //Declare bjet variable
  Int_t bjet;

  //Add new branch
  TBranch *bjetBranch=newTree->Branch("bjet",&bjet,"bjet/I");

  //Get the number of events
  Int_t nentries=(Int_t)oldTree->GetEntries();

  //Calculate bjet, algorithm is provided by Prof. Varnes
  for(Int_t i=0;i<nentries;i++)
    {
      oldTree->GetEntry(i);
      bjet=0;
      if(SSee_2016 || SSem_2016 || SSmm_2016 || eee_2016 || eem_2016 || emm_2016 || mmm_2016)
      	{
      	  for(unsigned int ibjet=0;ibjet<jet_mv2c10->size();ibjet++)
      	    {
      	      ///     if  (jet_mv2c10->at(ibjet) > 0.1758475) {  // 85% WP
	      if  (jet_mv2c10->at(ibjet) > 0.645925)
		{  // 77% WP
		  //if (jet_mv2c10->at(ibjet) > 0.8244273) {  // 70% WP
		bjet++;
		}
      	    }
      	}
      bjetBranch->Fill();
    }

  //Working with normalization
  //
  Float_t lumi=36.1;

  //Declare leaf and branch
  Float_t         weight_mc;
  Float_t         weight_jvt;
  Float_t         weight_leptonSF_tightLeps;
  Float_t         weight_indiv_SF_MU_TTVA;
  Float_t         weight_pileup;
  Float_t         weight_bTagSF_77;

  TBranch        *b_weight_mc;
  TBranch        *b_weight_jvt;
  TBranch        *b_weight_leptonSF_tightLeps;
  TBranch        *b_weight_indiv_SF_MU_TTVA;
  TBranch        *b_weight_pileup;
  TBranch        *b_weight_bTagSF_77;

  //Set branch addresses and brunch pointers
  oldTree->SetBranchAddress("weight_mc", &weight_mc, &b_weight_mc);
  oldTree->SetBranchAddress("weight_jvt", &weight_jvt, &b_weight_jvt);
  oldTree->SetBranchAddress("weight_leptonSF_tightLeps", &weight_leptonSF_tightLeps, &b_weight_leptonSF_tightLeps);
  oldTree->SetBranchAddress("weight_indiv_SF_MU_TTVA", &weight_indiv_SF_MU_TTVA, &b_weight_indiv_SF_MU_TTVA);
  oldTree->SetBranchAddress("weight_pileup", &weight_pileup, &b_weight_pileup);
  oldTree->SetBranchAddress("weight_bTagSF_77", &weight_bTagSF_77, &b_weight_bTagSF_77);

  //Get the data...algrithm is from Prof. Varnes
  TH1F *lumInt=new TH1F;
  inputTree->GetObject("hIntLum",lumInt);
  Float_t mcnorm=lumInt->GetBinContent(1);

  //Declare variable for event weight
  Float_t evtWeight;
  TBranch *evtBranch=newTree->Branch("evtWeight",&evtWeight,"evtWeight/F");

  std::cout<<"mcnorm is: "<<mcnorm<<std::endl;

  for(Int_t j=0;j<nentries;j++)
    {
      oldTree->GetEntry(j);

      //Calculate event weight
      evtWeight=weight_mc*weight_jvt*(weight_leptonSF_tightLeps/weight_indiv_SF_MU_TTVA)*weight_pileup*weight_bTagSF_77*lumi/mcnorm;

      std::cout<<std::endl;
      // std::cout<<"The weight_jvt is: "<<weight_jvt<<std::endl;
      // std::cout<<"The weight_mc is: "<<weight_mc<<std::endl;
      // std::cout<<"The weight_pileup is: "<<weight_pileup<<std::endl;
      // std::cout<<"The weight_indiv_SF_MU_TTVA is: "<<weight_indiv_SF_MU_TTVA<<std::endl;
      // std::cout<<"The weight_bTagSF_77 is: "<<weight_bTagSF_77<<std::endl;
      // std::cout<<"The weight_leptonSF_tightLeps is: "<<weight_leptonSF_tightLeps<<std::endl;
      std::cout<<"The event weight is: "<<evtWeight<<std::endl;

      evtBranch->Fill();
    }

  newTree->Fill();
  newTree->Print();
  newTree->Write();

  outputFile->Close();

  delete oldTree;
  delete lumInt;
}

void prepTree()
{

  //Variable 'envName' can be the environmental variable on the system that
  //includes the path to the directory of the data files.
  //Please make sure that the variable is exported.

  const char* envName="MCDATA";
  std::string dataPATH=std::getenv(envName);
  if(dataPATH.empty())
    {
      std::cout<<"\tData path not found! Please make sure you export MCDATA which contains the path of data.\n";
    }
  else
    {
      std::cout<<"\tData path is: "<<dataPATH<<std::endl<<std::endl;
    }

  std::ifstream inputFile("datafiles.txt");
  std::string fileName;

  while(std::getline(inputFile,fileName))
    {
      TString fullInput;
      fullInput=dataPATH+"/"+fileName;
      std::cout<<"Readig file: "<<fullInput<<std::endl;

      TString outputName;
      outputName="normalized_"+fileName;

      TFile *bg=new TFile(fullInput);
      create(bg,outputName);
      delete bg;

    }
  inputFile.close();
}
<|endoftext|>


<commit_before>#ifndef __PreassembledMass_INL
#define __PreassembledMass_INL

#include "PreassembledMass.h"

#include <sofa/core/objectmodel/BaseNode.h>

#include <Compliant/assembly/AssemblyVisitor.h>

namespace sofa
{

namespace component
{

namespace mass
{

/// removing no longer necessary mapped masses
class RemoveChildMassVisitor : public simulation::Visitor
{
public:
    RemoveChildMassVisitor(const core::ExecParams* params)
        : simulation::Visitor(params)
    {
    }

    virtual Result processNodeTopDown(simulation::Node* node)
    {
        core::behavior::BaseMass* mass;
        node->get(mass);
        if( !dynamic_cast<BasePreassembledMass*>(mass) )
            node->removeObject(mass);
        return RESULT_CONTINUE;
    }

};

unsigned int BasePreassembledMass::s_instanciationCounter = 0;

template < class DataTypes >
void PreassembledMass< DataTypes >::init()
{
    core::behavior::Mass<DataTypes>::init();
}

template < class DataTypes >
void PreassembledMass< DataTypes >::bwdInit()
{

    MassMatrix& massMatrix = *d_massMatrix.beginEdit();

    // if the mass matrix is not given manually
    if( massMatrix.rows() != massMatrix.cols() || massMatrix.rows()!=this->mstate->getMatrixSize() )
    {
        // perform assembly
        core::MechanicalParams mparams = *core::MechanicalParams::defaultInstance();
        mparams.setKFactor(0);
        mparams.setBFactor(0);
        mparams.setMFactor(1);
        mparams.setDt( this->getContext()->getDt() ); // should not be used but to be sure

        simulation::AssemblyVisitor assemblyVisitor( &mparams );
        this->getContext()->executeVisitor( &assemblyVisitor );
        component::linearsolver::AssembledSystem sys;
        assemblyVisitor.assemble( sys );
        massMatrix.compressedMatrix = sys.H;

        if( massMatrix.rows()!=this->mstate->getMatrixSize() )
        {
            serr<<"Are you sure that every independent dofs are in independent graph branches?\n";
            assert(false);
        }

        if( _instanciationNumber == 0 ) // only the first one (last bwdInit called) will call the mass removal
        {
    //        std::cerr<<SOFA_CLASS_METHOD<<"removing child masses"<<std::endl;

            // visitor to delete child mass
            RemoveChildMassVisitor removeChildMassVisitor( core::ExecParams::defaultInstance() );
            this->getContext()->executeVisitor( &removeChildMassVisitor );

            typename LinkMassNodes::Container massNodes = l_massNodes.getValue();
            for ( unsigned int i = 0; i < massNodes.size() ; i++)
            {
               if( massNodes[i]->isActive() ) massNodes[i]->setActive( false );
            }
        }
    }

    // for human debug
    Real totalmass = 0;
    for(size_t r=0;r<massMatrix.rows();++r)
        for(size_t c=0;c<massMatrix.cols();++c)
            totalmass+=massMatrix.element(r,c);
    sout<<"total mass: "<<totalmass/this->mstate->getMatrixBlockSize()<<sendl;

    d_massMatrix.endEdit();
}

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

// -- Mass interface
template < class DataTypes >
void PreassembledMass< DataTypes >::addMDx( const core::MechanicalParams*, DataVecDeriv& res, const DataVecDeriv& dx, double factor )
{
    if( factor == 1.0 )
    {
        d_massMatrix.getValue().addMult( res, dx );
    }
    else
    {
        d_massMatrix.getValue().addMult( res, dx, factor );
    }
}

template < class DataTypes >
void PreassembledMass< DataTypes >::accFromF( const core::MechanicalParams*, DataVecDeriv& /*acc*/, const DataVecDeriv& /*f*/ )
{
    serr<<"accFromF not yet implemented (the matrix inversion is needed)"<<sendl;
}

template < class DataTypes >
double PreassembledMass< DataTypes >::getKineticEnergy( const core::MechanicalParams*, const DataVecDeriv& v ) const
{
    const VecDeriv& _v = v.getValue();
    double e = 0;

    VecDeriv Mv;
    d_massMatrix.getValue().mult( Mv, _v );

    for( unsigned int i=0 ; i<_v.size() ; i++ )
        e += _v[i] * Mv[i];

    return e/2;
}

template < class DataTypes >
double PreassembledMass< DataTypes >::getPotentialEnergy( const core::MechanicalParams* mparams, const DataVecCoord& x ) const
{
    serr<<SOFA_CLASS_METHOD<<"not implemented!\n";
    return core::behavior::Mass< DataTypes >::getPotentialEnergy( mparams, x );

//    const VecCoord& _x = x.getValue();

//    VecCoord Mx/* = d_massMatrix * _x*/;
//    d_massMatrix.mult( Mx, _x );

//    SReal e = 0;
//    // gravity
//    Vec3d g ( this->getContext()->getGravity() );
//    Deriv theGravity;
//    DataTypes::set ( theGravity, g[0], g[1], g[2] );
//    for( unsigned int i=0 ; i<_x.size() ; i++ )
//    {
//        e -= theGravity*Mx[i];
//    }
//    return e;
}

template < class DataTypes >
void PreassembledMass< DataTypes >::addGravityToV(const core::MechanicalParams* mparams, DataVecDeriv& d_v)
{
    if(mparams)
    {
        VecDeriv& v = *d_v.beginEdit();

        // gravity
        Vec3 g ( this->getContext()->getGravity() * (mparams->dt()) );
        Deriv theGravity;
        DataTypes::set ( theGravity, g[0], g[1], g[2]);
        Deriv hg = theGravity * (mparams->dt());

        // add weight force
        for (unsigned int i=0; i<v.size(); i++)
        {
            v[i] += hg;
        }
        d_v.endEdit();
    }
}

template < class DataTypes >
void PreassembledMass< DataTypes >::addForce(const core::MechanicalParams* /*mparams*/, DataVecDeriv& f, const DataVecCoord& /*x*/, const DataVecDeriv& /*v*/)
{
    //if gravity was added separately (in solver's "solve" method), then nothing to do here
    if(this->m_separateGravity.getValue()) return;

    VecDeriv& _f = *f.beginEdit();

    // gravity
    Vec3 g ( this->getContext()->getGravity() );
//    Deriv theGravity;
//    DataTypes::set( theGravity, g[0], g[1], g[2] );
    // add weight
//    d_massMatrix.template addMul_by_line<Real,VecDeriv,Deriv>( _f, theGravity );

    //TODO optimize this!!!
    VecDeriv gravities(_f.size());
    for(size_t i=0 ; i<_f.size() ; ++i )
        DataTypes::set( gravities[i], g[0], g[1], g[2] );
    d_massMatrix.getValue().addMult( _f, gravities );

    f.endEdit();
}

template < class DataTypes >
void PreassembledMass< DataTypes >::addMToMatrix(const core::MechanicalParams *mparams, const sofa::core::behavior::MultiMatrixAccessor* matrix)
{
    sofa::core::behavior::MultiMatrixAccessor::MatrixRef r = matrix->getMatrix(this->mstate);
    Real mFactor = (Real)mparams->mFactorIncludingRayleighDamping(this->rayleighMass.getValue());
    d_massMatrix.getValue().addToBaseMatrix( r.matrix, mFactor, r.offset );
}

} // namespace mass

} // namespace component

} // namespace sofa

#endif // __PreassembledMass_INL
<commit_msg>[PreassembledMass] fixing warnings<commit_after>#ifndef __PreassembledMass_INL
#define __PreassembledMass_INL

#include "PreassembledMass.h"

#include <sofa/core/objectmodel/BaseNode.h>

#include <Compliant/assembly/AssemblyVisitor.h>

namespace sofa
{

namespace component
{

namespace mass
{

/// removing no longer necessary mapped masses
class RemoveChildMassVisitor : public simulation::Visitor
{
public:
    RemoveChildMassVisitor(const core::ExecParams* params)
        : simulation::Visitor(params)
    {
    }

    virtual Result processNodeTopDown(simulation::Node* node)
    {
        core::behavior::BaseMass* mass;
        node->get(mass);
        if( !dynamic_cast<BasePreassembledMass*>(mass) )
            node->removeObject(mass);
        return RESULT_CONTINUE;
    }

};

unsigned int BasePreassembledMass::s_instanciationCounter = 0;

template < class DataTypes >
void PreassembledMass< DataTypes >::init()
{
    core::behavior::Mass<DataTypes>::init();
}

template < class DataTypes >
void PreassembledMass< DataTypes >::bwdInit()
{

    MassMatrix& massMatrix = *d_massMatrix.beginEdit();

    // if the mass matrix is not given manually
    if( massMatrix.rows() != massMatrix.cols() || massMatrix.rows()!=(typename MassMatrix::Index)this->mstate->getMatrixSize() )
    {
        // perform assembly
        core::MechanicalParams mparams = *core::MechanicalParams::defaultInstance();
        mparams.setKFactor(0);
        mparams.setBFactor(0);
        mparams.setMFactor(1);
        mparams.setDt( this->getContext()->getDt() ); // should not be used but to be sure

        simulation::AssemblyVisitor assemblyVisitor( &mparams );
        this->getContext()->executeVisitor( &assemblyVisitor );
        component::linearsolver::AssembledSystem sys;
        assemblyVisitor.assemble( sys );
        massMatrix.compressedMatrix = sys.H;

        if( massMatrix.rows()!=(typename MassMatrix::Index)this->mstate->getMatrixSize() )
        {
            serr<<"Are you sure that every independent dofs are in independent graph branches?\n";
            assert(false);
        }

        if( _instanciationNumber == 0 ) // only the first one (last bwdInit called) will call the mass removal
        {
    //        std::cerr<<SOFA_CLASS_METHOD<<"removing child masses"<<std::endl;

            // visitor to delete child mass
            RemoveChildMassVisitor removeChildMassVisitor( core::ExecParams::defaultInstance() );
            this->getContext()->executeVisitor( &removeChildMassVisitor );

            typename LinkMassNodes::Container massNodes = l_massNodes.getValue();
            for ( unsigned int i = 0; i < massNodes.size() ; i++)
            {
               if( massNodes[i]->isActive() ) massNodes[i]->setActive( false );
            }
        }
    }

    // for human debug
    Real totalmass = 0;
    for(typename MassMatrix::Index r=0;r<massMatrix.rows();++r)
        for(typename MassMatrix::Index c=0;c<massMatrix.cols();++c)
            totalmass+=massMatrix.element(r,c);
    sout<<"total mass: "<<totalmass/this->mstate->getMatrixBlockSize()<<sendl;

    d_massMatrix.endEdit();
}

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

// -- Mass interface
template < class DataTypes >
void PreassembledMass< DataTypes >::addMDx( const core::MechanicalParams*, DataVecDeriv& res, const DataVecDeriv& dx, double factor )
{
    if( factor == 1.0 )
    {
        d_massMatrix.getValue().addMult( res, dx );
    }
    else
    {
        d_massMatrix.getValue().addMult( res, dx, factor );
    }
}

template < class DataTypes >
void PreassembledMass< DataTypes >::accFromF( const core::MechanicalParams*, DataVecDeriv& /*acc*/, const DataVecDeriv& /*f*/ )
{
    serr<<"accFromF not yet implemented (the matrix inversion is needed)"<<sendl;
}

template < class DataTypes >
double PreassembledMass< DataTypes >::getKineticEnergy( const core::MechanicalParams*, const DataVecDeriv& v ) const
{
    const VecDeriv& _v = v.getValue();
    double e = 0;

    VecDeriv Mv;
    d_massMatrix.getValue().mult( Mv, _v );

    for( unsigned int i=0 ; i<_v.size() ; i++ )
        e += _v[i] * Mv[i];

    return e/2;
}

template < class DataTypes >
double PreassembledMass< DataTypes >::getPotentialEnergy( const core::MechanicalParams* mparams, const DataVecCoord& x ) const
{
    serr<<SOFA_CLASS_METHOD<<"not implemented!\n";
    return core::behavior::Mass< DataTypes >::getPotentialEnergy( mparams, x );

//    const VecCoord& _x = x.getValue();

//    VecCoord Mx/* = d_massMatrix * _x*/;
//    d_massMatrix.mult( Mx, _x );

//    SReal e = 0;
//    // gravity
//    Vec3d g ( this->getContext()->getGravity() );
//    Deriv theGravity;
//    DataTypes::set ( theGravity, g[0], g[1], g[2] );
//    for( unsigned int i=0 ; i<_x.size() ; i++ )
//    {
//        e -= theGravity*Mx[i];
//    }
//    return e;
}

template < class DataTypes >
void PreassembledMass< DataTypes >::addGravityToV(const core::MechanicalParams* mparams, DataVecDeriv& d_v)
{
    if(mparams)
    {
        VecDeriv& v = *d_v.beginEdit();

        // gravity
        Vec3 g ( this->getContext()->getGravity() * (mparams->dt()) );
        Deriv theGravity;
        DataTypes::set ( theGravity, g[0], g[1], g[2]);
        Deriv hg = theGravity * (mparams->dt());

        // add weight force
        for (unsigned int i=0; i<v.size(); i++)
        {
            v[i] += hg;
        }
        d_v.endEdit();
    }
}

template < class DataTypes >
void PreassembledMass< DataTypes >::addForce(const core::MechanicalParams* /*mparams*/, DataVecDeriv& f, const DataVecCoord& /*x*/, const DataVecDeriv& /*v*/)
{
    //if gravity was added separately (in solver's "solve" method), then nothing to do here
    if(this->m_separateGravity.getValue()) return;

    VecDeriv& _f = *f.beginEdit();

    // gravity
    Vec3 g ( this->getContext()->getGravity() );
//    Deriv theGravity;
//    DataTypes::set( theGravity, g[0], g[1], g[2] );
    // add weight
//    d_massMatrix.template addMul_by_line<Real,VecDeriv,Deriv>( _f, theGravity );

    //TODO optimize this!!!
    VecDeriv gravities(_f.size());
    for(size_t i=0 ; i<_f.size() ; ++i )
        DataTypes::set( gravities[i], g[0], g[1], g[2] );
    d_massMatrix.getValue().addMult( _f, gravities );

    f.endEdit();
}

template < class DataTypes >
void PreassembledMass< DataTypes >::addMToMatrix(const core::MechanicalParams *mparams, const sofa::core::behavior::MultiMatrixAccessor* matrix)
{
    sofa::core::behavior::MultiMatrixAccessor::MatrixRef r = matrix->getMatrix(this->mstate);
    Real mFactor = (Real)mparams->mFactorIncludingRayleighDamping(this->rayleighMass.getValue());
    d_massMatrix.getValue().addToBaseMatrix( r.matrix, mFactor, r.offset );
}

} // namespace mass

} // namespace component

} // namespace sofa

#endif // __PreassembledMass_INL
<|endoftext|>


<commit_before>#ifndef __AIRINV_AIRINV_TYPES_HPP
#define __AIRINV_AIRINV_TYPES_HPP

// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <map>
// Boost
#include <boost/shared_ptr.hpp>
// StdAir
#include <stdair/stdair_exceptions.hpp>
#include <stdair/stdair_inventory_types.hpp>

namespace AIRINV {

  // Forward declarations
  class AIRINV_Service;

  // ///////// Exceptions ///////////
  class SegmentDateNotFoundException : public stdair::ParserException {
  public:
    /** Constructor. */
    SegmentDateNotFoundException (const std::string& iWhat)
      : stdair::ParserException (iWhat) {}
  };

  class BookingException : public stdair::RootException {
  };

  // //////// Type definitions /////////
  /** Pointer on the AIRINV Service handler. */
  typedef boost::shared_ptr<AIRINV_Service> AIRINV_ServicePtr_T;

  /** Typedef which defines a map of airline codes and the corresponding
      airline inventories. */
  typedef std::map<const stdair::AirlineCode_T,
                   AIRINV_ServicePtr_T> AIRINV_ServicePtr_Map_T;

  /** Define the FRAT5 curve. */
  typedef std::map<const stdair::DTD_T, double> FRAT5Curve_T;
}
#endif // __AIRINV_AIRINV_TYPES_HPP

<commit_msg>[Dev] Implemented, for DSim and SimCRS, the option of building the BOM tree either from parsing input files or from built-in samples.<commit_after>#ifndef __AIRINV_AIRINV_TYPES_HPP
#define __AIRINV_AIRINV_TYPES_HPP

// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <map>
// Boost
#include <boost/shared_ptr.hpp>
// StdAir
#include <stdair/stdair_exceptions.hpp>
#include <stdair/stdair_inventory_types.hpp>

namespace AIRINV {

  // Forward declarations
  class AIRINV_Service;
  class AIRINV_Master_Service;

  // ///////// Exceptions ///////////
  /**
   * Specific exception when some BOM objects can not be found within
   * the inventory.
   */
  class SegmentDateNotFoundException : public stdair::ParserException {
  public:
    /**
     * Constructor.
     */
    SegmentDateNotFoundException (const std::string& iWhat)
      : stdair::ParserException (iWhat) {}
  };

  /**
   * Specific exception related to bookings made against the inventory.
   */
  class BookingException : public stdair::RootException {
  };

  // //////// Type definitions /////////
  /**
   * (Smart) Pointer on the AirInv (slave) service handler.
   */
  typedef boost::shared_ptr<AIRINV_Service> AIRINV_ServicePtr_T;

  /**
   * (Smart) Pointer on the AirInv master service handler.
   */
  typedef boost::shared_ptr<AIRINV_Master_Service> AIRINV_Master_ServicePtr_T;

  /**
   * Type defining a map of airline codes and the corresponding
   * airline inventories.
   */
  typedef std::map<const stdair::AirlineCode_T,
                   AIRINV_ServicePtr_T> AIRINV_ServicePtr_Map_T;

  /**
   * Define the FRAT5 curve.
   */
  typedef std::map<const stdair::DTD_T, double> FRAT5Curve_T;

}
#endif // __AIRINV_AIRINV_TYPES_HPP

<|endoftext|>