<commit_before>// Copyright (c) 2012-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <bloom.h>

#include <primitives/transaction.h>
#include <hash.h>
#include <script/script.h>
#include <script/standard.h>
#include <random.h>
#include <streams.h>

#include <math.h>
#include <stdlib.h>

#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
#define LN2 0.6931471805599453094172321214581765680755001343602552

CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
    /**
     * The ideal size for a bloom filter with a given number of elements and false positive rate is:
     * - nElements * log(fp rate) / ln(2)^2
     * We ignore filter parameters which will create a bloom filter larger than the protocol limits
     */
    vData(std::min((unsigned int)(-1  / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
    /**
     * The ideal number of hash functions is filter size * ln(2) / number of elements
     * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
     * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
     */
    isFull(false),
    isEmpty(false),
    nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
    nTweak(nTweakIn),
    nFlags(nFlagsIn)
{
}

// Private constructor used by CRollingBloomFilter
CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn) :
    vData((unsigned int)(-1  / LN2SQUARED * nElements * log(nFPRate)) / 8),
    isFull(false),
    isEmpty(true),
    nHashFuncs((unsigned int)(vData.size() * 8 / nElements * LN2)),
    nTweak(nTweakIn),
    nFlags(BLOOM_UPDATE_NONE)
{
}

inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
{
    // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
    return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
}

void CBloomFilter::insert(const std::vector<unsigned char>& vKey)
{
    if (isFull)
        return;
    for (unsigned int i = 0; i < nHashFuncs; i++)
    {
        unsigned int nIndex = Hash(i, vKey);
        // Sets bit nIndex of vData
        vData[nIndex >> 3] |= (1 << (7 & nIndex));
    }
    isEmpty = false;
}

void CBloomFilter::insert(const COutPoint& outpoint)
{
    CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    stream << outpoint;
    std::vector<unsigned char> data(stream.begin(), stream.end());
    insert(data);
}

void CBloomFilter::insert(const uint256& hash)
{
    std::vector<unsigned char> data(hash.begin(), hash.end());
    insert(data);
}

bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
{
    if (isFull)
        return true;
    if (isEmpty)
        return false;
    for (unsigned int i = 0; i < nHashFuncs; i++)
    {
        unsigned int nIndex = Hash(i, vKey);
        // Checks bit nIndex of vData
        if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
            return false;
    }
    return true;
}

bool CBloomFilter::contains(const COutPoint& outpoint) const
{
    CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    stream << outpoint;
    std::vector<unsigned char> data(stream.begin(), stream.end());
    return contains(data);
}

bool CBloomFilter::contains(const uint256& hash) const
{
    std::vector<unsigned char> data(hash.begin(), hash.end());
    return contains(data);
}

void CBloomFilter::clear()
{
    vData.assign(vData.size(),0);
    isFull = false;
    isEmpty = true;
}

void CBloomFilter::reset(const unsigned int nNewTweak)
{
    clear();
    nTweak = nNewTweak;
}

bool CBloomFilter::IsWithinSizeConstraints() const
{
    return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
}

bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
{
    bool fFound = false;
    // Match if the filter contains the hash of tx
    //  for finding tx when they appear in a block
    if (isFull)
        return true;
    if (isEmpty)
        return false;
    const uint256& hash = tx.GetHash();
    if (contains(hash))
        fFound = true;

    for (unsigned int i = 0; i < tx.vout.size(); i++)
    {
        const CTxOut& txout = tx.vout[i];
        // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
        // If this matches, also add the specific output that was matched.
        // This means clients don't have to update the filter themselves when a new relevant tx
        // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
        CScript::const_iterator pc = txout.scriptPubKey.begin();
        std::vector<unsigned char> data;
        while (pc < txout.scriptPubKey.end())
        {
            opcodetype opcode;
            if (!txout.scriptPubKey.GetOp(pc, opcode, data))
                break;
            if (data.size() != 0 && contains(data))
            {
                fFound = true;
                if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
                    insert(COutPoint(hash, i));
                else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
                {
                    txnouttype type;
                    std::vector<std::vector<unsigned char> > vSolutions;
                    if (Solver(txout.scriptPubKey, type, vSolutions) &&
                            (type == TX_PUBKEY || type == TX_MULTISIG))
                        insert(COutPoint(hash, i));
                }
                break;
            }
        }
    }

    if (fFound)
        return true;

    for (const CTxIn& txin : tx.vin)
    {
        // Match if the filter contains an outpoint tx spends
        if (contains(txin.prevout))
            return true;

        // Match if the filter contains any arbitrary script data element in any scriptSig in tx
        CScript::const_iterator pc = txin.scriptSig.begin();
        std::vector<unsigned char> data;
        while (pc < txin.scriptSig.end())
        {
            opcodetype opcode;
            if (!txin.scriptSig.GetOp(pc, opcode, data))
                break;
            if (data.size() != 0 && contains(data))
                return true;
        }
    }

    return false;
}

void CBloomFilter::UpdateEmptyFull()
{
    bool full = true;
    bool empty = true;
    for (unsigned int i = 0; i < vData.size(); i++)
    {
        full &= vData[i] == 0xff;
        empty &= vData[i] == 0;
    }
    isFull = full;
    isEmpty = empty;
}

CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
{
    double logFpRate = log(fpRate);
    /* The optimal number of hash functions is log(fpRate) / log(0.5), but
     * restrict it to the range 1-50. */
    nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
    /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
    nEntriesPerGeneration = (nElements + 1) / 2;
    uint32_t nMaxElements = nEntriesPerGeneration * 3;
    /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
     * =>          pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
     * =>          1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
     * =>          log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
     * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
     * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
     */
    uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
    data.clear();
    /* For each data element we need to store 2 bits. If both bits are 0, the
     * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
     * treated as set in generation 1, 2, or 3 respectively.
     * These bits are stored in separate integers: position P corresponds to bit
     * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
    data.resize(((nFilterBits + 63) / 64) << 1);
    reset();
}

/* Similar to CBloomFilter::Hash */
static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {
    return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
}

void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
{
    if (nEntriesThisGeneration == nEntriesPerGeneration) {
        nEntriesThisGeneration = 0;
        nGeneration++;
        if (nGeneration == 4) {
            nGeneration = 1;
        }
        uint64_t nGenerationMask1 = -(uint64_t)(nGeneration & 1);
        uint64_t nGenerationMask2 = -(uint64_t)(nGeneration >> 1);
        /* Wipe old entries that used this generation number. */
        for (uint32_t p = 0; p < data.size(); p += 2) {
            uint64_t p1 = data[p], p2 = data[p + 1];
            uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
            data[p] = p1 & mask;
            data[p + 1] = p2 & mask;
        }
    }
    nEntriesThisGeneration++;

    for (int n = 0; n < nHashFuncs; n++) {
        uint32_t h = RollingBloomHash(n, nTweak, vKey);
        int bit = h & 0x3F;
        uint32_t pos = (h >> 6) % data.size();
        /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
        data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;
        data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;
    }
}

void CRollingBloomFilter::insert(const uint256& hash)
{
    std::vector<unsigned char> data(hash.begin(), hash.end());
    insert(data);
}

bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
{
    for (int n = 0; n < nHashFuncs; n++) {
        uint32_t h = RollingBloomHash(n, nTweak, vKey);
        int bit = h & 0x3F;
        uint32_t pos = (h >> 6) % data.size();
        /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
        if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
            return false;
        }
    }
    return true;
}

bool CRollingBloomFilter::contains(const uint256& hash) const
{
    std::vector<unsigned char> data(hash.begin(), hash.end());
    return contains(data);
}

void CRollingBloomFilter::reset()
{
    nTweak = GetRand(std::numeric_limits<unsigned int>::max());
    nEntriesThisGeneration = 0;
    nGeneration = 1;
    for (std::vector<uint64_t>::iterator it = data.begin(); it != data.end(); it++) {
        *it = 0;
    }
}
<commit_msg>Fix msvc compiler error C4146 (minus operator applied to unsigned type)<commit_after>// Copyright (c) 2012-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <bloom.h>

#include <primitives/transaction.h>
#include <hash.h>
#include <script/script.h>
#include <script/standard.h>
#include <random.h>
#include <streams.h>

#include <math.h>
#include <stdlib.h>

#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
#define LN2 0.6931471805599453094172321214581765680755001343602552

CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn, unsigned char nFlagsIn) :
    /**
     * The ideal size for a bloom filter with a given number of elements and false positive rate is:
     * - nElements * log(fp rate) / ln(2)^2
     * We ignore filter parameters which will create a bloom filter larger than the protocol limits
     */
    vData(std::min((unsigned int)(-1  / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
    /**
     * The ideal number of hash functions is filter size * ln(2) / number of elements
     * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
     * See https://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
     */
    isFull(false),
    isEmpty(false),
    nHashFuncs(std::min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
    nTweak(nTweakIn),
    nFlags(nFlagsIn)
{
}

// Private constructor used by CRollingBloomFilter
CBloomFilter::CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweakIn) :
    vData((unsigned int)(-1  / LN2SQUARED * nElements * log(nFPRate)) / 8),
    isFull(false),
    isEmpty(true),
    nHashFuncs((unsigned int)(vData.size() * 8 / nElements * LN2)),
    nTweak(nTweakIn),
    nFlags(BLOOM_UPDATE_NONE)
{
}

inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
{
    // 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
    return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
}

void CBloomFilter::insert(const std::vector<unsigned char>& vKey)
{
    if (isFull)
        return;
    for (unsigned int i = 0; i < nHashFuncs; i++)
    {
        unsigned int nIndex = Hash(i, vKey);
        // Sets bit nIndex of vData
        vData[nIndex >> 3] |= (1 << (7 & nIndex));
    }
    isEmpty = false;
}

void CBloomFilter::insert(const COutPoint& outpoint)
{
    CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    stream << outpoint;
    std::vector<unsigned char> data(stream.begin(), stream.end());
    insert(data);
}

void CBloomFilter::insert(const uint256& hash)
{
    std::vector<unsigned char> data(hash.begin(), hash.end());
    insert(data);
}

bool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const
{
    if (isFull)
        return true;
    if (isEmpty)
        return false;
    for (unsigned int i = 0; i < nHashFuncs; i++)
    {
        unsigned int nIndex = Hash(i, vKey);
        // Checks bit nIndex of vData
        if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))
            return false;
    }
    return true;
}

bool CBloomFilter::contains(const COutPoint& outpoint) const
{
    CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    stream << outpoint;
    std::vector<unsigned char> data(stream.begin(), stream.end());
    return contains(data);
}

bool CBloomFilter::contains(const uint256& hash) const
{
    std::vector<unsigned char> data(hash.begin(), hash.end());
    return contains(data);
}

void CBloomFilter::clear()
{
    vData.assign(vData.size(),0);
    isFull = false;
    isEmpty = true;
}

void CBloomFilter::reset(const unsigned int nNewTweak)
{
    clear();
    nTweak = nNewTweak;
}

bool CBloomFilter::IsWithinSizeConstraints() const
{
    return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
}

bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)
{
    bool fFound = false;
    // Match if the filter contains the hash of tx
    //  for finding tx when they appear in a block
    if (isFull)
        return true;
    if (isEmpty)
        return false;
    const uint256& hash = tx.GetHash();
    if (contains(hash))
        fFound = true;

    for (unsigned int i = 0; i < tx.vout.size(); i++)
    {
        const CTxOut& txout = tx.vout[i];
        // Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
        // If this matches, also add the specific output that was matched.
        // This means clients don't have to update the filter themselves when a new relevant tx
        // is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
        CScript::const_iterator pc = txout.scriptPubKey.begin();
        std::vector<unsigned char> data;
        while (pc < txout.scriptPubKey.end())
        {
            opcodetype opcode;
            if (!txout.scriptPubKey.GetOp(pc, opcode, data))
                break;
            if (data.size() != 0 && contains(data))
            {
                fFound = true;
                if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
                    insert(COutPoint(hash, i));
                else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
                {
                    txnouttype type;
                    std::vector<std::vector<unsigned char> > vSolutions;
                    if (Solver(txout.scriptPubKey, type, vSolutions) &&
                            (type == TX_PUBKEY || type == TX_MULTISIG))
                        insert(COutPoint(hash, i));
                }
                break;
            }
        }
    }

    if (fFound)
        return true;

    for (const CTxIn& txin : tx.vin)
    {
        // Match if the filter contains an outpoint tx spends
        if (contains(txin.prevout))
            return true;

        // Match if the filter contains any arbitrary script data element in any scriptSig in tx
        CScript::const_iterator pc = txin.scriptSig.begin();
        std::vector<unsigned char> data;
        while (pc < txin.scriptSig.end())
        {
            opcodetype opcode;
            if (!txin.scriptSig.GetOp(pc, opcode, data))
                break;
            if (data.size() != 0 && contains(data))
                return true;
        }
    }

    return false;
}

void CBloomFilter::UpdateEmptyFull()
{
    bool full = true;
    bool empty = true;
    for (unsigned int i = 0; i < vData.size(); i++)
    {
        full &= vData[i] == 0xff;
        empty &= vData[i] == 0;
    }
    isFull = full;
    isEmpty = empty;
}

CRollingBloomFilter::CRollingBloomFilter(const unsigned int nElements, const double fpRate)
{
    double logFpRate = log(fpRate);
    /* The optimal number of hash functions is log(fpRate) / log(0.5), but
     * restrict it to the range 1-50. */
    nHashFuncs = std::max(1, std::min((int)round(logFpRate / log(0.5)), 50));
    /* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements / 2 entries. */
    nEntriesPerGeneration = (nElements + 1) / 2;
    uint32_t nMaxElements = nEntriesPerGeneration * 3;
    /* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits), nHashFuncs)
     * =>          pow(fpRate, 1.0 / nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements / nFilterBits)
     * =>          1.0 - pow(fpRate, 1.0 / nHashFuncs) = exp(-nHashFuncs * nMaxElements / nFilterBits)
     * =>          log(1.0 - pow(fpRate, 1.0 / nHashFuncs)) = -nHashFuncs * nMaxElements / nFilterBits
     * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - pow(fpRate, 1.0 / nHashFuncs))
     * =>          nFilterBits = -nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs))
     */
    uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements / log(1.0 - exp(logFpRate / nHashFuncs)));
    data.clear();
    /* For each data element we need to store 2 bits. If both bits are 0, the
     * bit is treated as unset. If the bits are (01), (10), or (11), the bit is
     * treated as set in generation 1, 2, or 3 respectively.
     * These bits are stored in separate integers: position P corresponds to bit
     * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. */
    data.resize(((nFilterBits + 63) / 64) << 1);
    reset();
}

/* Similar to CBloomFilter::Hash */
static inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {
    return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);
}

void CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)
{
    if (nEntriesThisGeneration == nEntriesPerGeneration) {
        nEntriesThisGeneration = 0;
        nGeneration++;
        if (nGeneration == 4) {
            nGeneration = 1;
        }
        uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);
        uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);
        /* Wipe old entries that used this generation number. */
        for (uint32_t p = 0; p < data.size(); p += 2) {
            uint64_t p1 = data[p], p2 = data[p + 1];
            uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);
            data[p] = p1 & mask;
            data[p + 1] = p2 & mask;
        }
    }
    nEntriesThisGeneration++;

    for (int n = 0; n < nHashFuncs; n++) {
        uint32_t h = RollingBloomHash(n, nTweak, vKey);
        int bit = h & 0x3F;
        uint32_t pos = (h >> 6) % data.size();
        /* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. */
        data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;
        data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;
    }
}

void CRollingBloomFilter::insert(const uint256& hash)
{
    std::vector<unsigned char> data(hash.begin(), hash.end());
    insert(data);
}

bool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const
{
    for (int n = 0; n < nHashFuncs; n++) {
        uint32_t h = RollingBloomHash(n, nTweak, vKey);
        int bit = h & 0x3F;
        uint32_t pos = (h >> 6) % data.size();
        /* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey */
        if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {
            return false;
        }
    }
    return true;
}

bool CRollingBloomFilter::contains(const uint256& hash) const
{
    std::vector<unsigned char> data(hash.begin(), hash.end());
    return contains(data);
}

void CRollingBloomFilter::reset()
{
    nTweak = GetRand(std::numeric_limits<unsigned int>::max());
    nEntriesThisGeneration = 0;
    nGeneration = 1;
    for (std::vector<uint64_t>::iterator it = data.begin(); it != data.end(); it++) {
        *it = 0;
    }
}
<|endoftext|>


<commit_before>#include <node.h>
#include <v8.h>
#include <phidget21.h>

using namespace v8;

// ------------------------------------------
// Globals
// ------------------------------------------

CPhidgetBridgeHandle bridge = 0;

// ------------------------------------------
// Event handlers
// ------------------------------------------

int CCONV AttachHandler(CPhidgetHandle ADVSERVO, void *userptr)
{
    int serialNo;
    const char *name;

    CPhidget_getDeviceName (ADVSERVO, &name);
    CPhidget_getSerialNumber(ADVSERVO, &serialNo);
    printf("%s %10d attached!\n", name, serialNo);

    return 0;
}

int CCONV DetachHandler(CPhidgetHandle ADVSERVO, void *userptr)
{
    int serialNo;
    const char *name;

    CPhidget_getDeviceName (ADVSERVO, &name);
    CPhidget_getSerialNumber(ADVSERVO, &serialNo);
    printf("%s %10d detached!\n", name, serialNo);

    return 0;
}

int CCONV ErrorHandler(CPhidgetHandle ADVSERVO, void *userptr, int ErrorCode, const char *Description)
{
    printf("Error handled. %d - %s\n", ErrorCode, Description);
    return 0;
}

int CCONV BridgeDataHandler(CPhidgetBridgeHandle ADVSERVO, void *usrptr, int Index, double Value)
{
    printf("Bridge: %d > Current Data: %f\n", Index, Value);
    return 0;
}

int display_properties(CPhidgetBridgeHandle phid)
{
    int serialNo, version;
    int numSensor, rateMax, rateMin;
    const char* ptr;

    CPhidget_getDeviceType((CPhidgetHandle)phid, &ptr);
    CPhidget_getSerialNumber((CPhidgetHandle)phid, &serialNo);
    CPhidget_getDeviceVersion((CPhidgetHandle)phid, &version);

    CPhidgetBridge_getInputCount((CPhidgetBridgeHandle) phid, &numSensor);
    CPhidgetBridge_getDataRateMax((CPhidgetBridgeHandle) phid, &rateMax);
    CPhidgetBridge_getDataRateMin((CPhidgetBridgeHandle) phid, &rateMin);

    printf("%s\n", ptr);
    printf("Serial Number: %10d\nVersion: %8d\n# Sensor: %d\nData Rate: %d ~ %d\n",
                    serialNo, version, numSensor, rateMax, rateMin);

    return 0;
}

// ------------------------------------------
// Method abstractions
// ------------------------------------------

Handle<Value>
attach(const Arguments& args)
{
    HandleScope scope;

    int result;
    const char *err;
    CPhidgetBridgeHandle bridge;
    //CPhidget_enableLogging(PHIDGET_LOG_VERBOSE, NULL);

    CPhidgetBridge_create(&bridge);

    CPhidget_set_OnAttach_Handler((CPhidgetHandle)bridge, AttachHandler, NULL);
    CPhidget_set_OnDetach_Handler((CPhidgetHandle)bridge, DetachHandler, NULL);
    CPhidget_set_OnError_Handler((CPhidgetHandle)bridge, ErrorHandler, NULL);

    // CPhidgetBridge_set_OnBridgeData_Handler(bridge, data, NULL);

    CPhidget_open((CPhidgetHandle)bridge, -1);

    //Wait for 10 seconds, otherwise exit
    if(result = CPhidget_waitForAttachment((CPhidgetHandle)bridge, 10000))
    {

        CPhidget_getErrorDescription(result, &err);
        printf("Problem waiting for attachment: %s\n", err);
        return ThrowException(Exception::Error(String::New("Could not attach to device.")));
    }

    // Display the properties of the attached device
    display_properties(bridge);

    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
close(const Arguments& args)
{
    HandleScope scope;

    CPhidget_close((CPhidgetHandle)bridge);
    CPhidget_delete((CPhidgetHandle)bridge);
    printf("Phidget Bridge is closed.\n");

    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
getValue(const Arguments& args)
{
    double value;

    HandleScope scope;
    CPhidgetBridge_getBridgeValue(bridge, args[0]->Int32Value(), &value);
    return scope.Close(Number::New(value));
}

Handle<Value>
getMax(const Arguments& args)
{
    double max;

    HandleScope scope;
    CPhidgetBridge_getBridgeMax(bridge, args[0]->Int32Value(), &max);
    return scope.Close(Integer::NewFromUnsigned(max));
}

Handle<Value>
getMin(const Arguments& args)
{
    double min;

    HandleScope scope;
    CPhidgetBridge_getBridgeMin(bridge, args[0]->Int32Value(), &min);
    return scope.Close(Integer::NewFromUnsigned(min));
}

Handle<Value>
setEnabled(const Arguments& args)
{
    HandleScope scope;
    CPhidgetBridge_setEnabled(bridge, args[0]->Int32Value(), args[1]->Int32Value());
    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
getEnabled(const Arguments& args)
{
    int enabled;
    HandleScope scope;
    CPhidgetBridge_getEnabled(bridge, args[0]->Int32Value(), &enabled);
    if(enabled)
        return scope.Close(Boolean::New(true));
    else
        return scope.Close(Boolean::New(false));
}

Handle<Value>
setGain(const Arguments& args)
{
    CPhidgetBridge_Gain gain;
    switch(args[1]->Int32Value()) {
        case 1:
            gain = PHIDGET_BRIDGE_GAIN_1;
            break;
        case 2:
            gain = PHIDGET_BRIDGE_GAIN_8;
            break;
        case 3:
            gain = PHIDGET_BRIDGE_GAIN_16;
            break;
        case 4:
            gain = PHIDGET_BRIDGE_GAIN_32;
            break;
        case 5:
            gain = PHIDGET_BRIDGE_GAIN_64;
            break;
        case 6:
            gain = PHIDGET_BRIDGE_GAIN_128;
            break;
        default:
            gain = PHIDGET_BRIDGE_GAIN_UNKNOWN;
    }
    HandleScope scope;
    CPhidgetBridge_setGain(bridge, args[0]->Int32Value(), gain);
    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
getGain(const Arguments& args)
{
    CPhidgetBridge_Gain gain;
    HandleScope scope;
    CPhidgetBridge_getGain(bridge, args[0]->Int32Value(), &gain);
    return scope.Close(Integer::NewFromUnsigned(gain));
}

Handle<Value>
setDataRate(const Arguments& args)
{
    HandleScope scope;
    CPhidgetBridge_setDataRate(bridge, args[0]->Int32Value());
    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
getDataRate(const Arguments& args)
{
    int dataRate;
    HandleScope scope;
    CPhidgetBridge_getDataRate(bridge, &dataRate);
    return scope.Close(Integer::NewFromUnsigned(dataRate));
}

// ------------------------------------------
// Module
// ------------------------------------------

void init(Handle<Object> target)
{
    // Connection
    target->Set(String::New("attach"), FunctionTemplate::New(attach)->GetFunction());
    target->Set(String::New("close"), FunctionTemplate::New(close)->GetFunction());

    // Bridge manipulation
    target->Set(String::New("setEnabled"), FunctionTemplate::New(setEnabled)->GetFunction());
    target->Set(String::New("setGain"), FunctionTemplate::New(setGain)->GetFunction());
    target->Set(String::New("setDataRate"), FunctionTemplate::New(setDataRate)->GetFunction());

    // Status
    target->Set(String::New("getValue"), FunctionTemplate::New(getValue)->GetFunction());
    target->Set(String::New("getMax"), FunctionTemplate::New(getMax)->GetFunction());
    target->Set(String::New("getMin"), FunctionTemplate::New(getMin)->GetFunction());
    target->Set(String::New("getEnabled"), FunctionTemplate::New(getEnabled)->GetFunction());
    target->Set(String::New("getGain"), FunctionTemplate::New(getGain)->GetFunction());
    target->Set(String::New("getDataRate"), FunctionTemplate::New(getDataRate)->GetFunction());
}

NODE_MODULE(binding_bridge, init);
<commit_msg>add library<commit_after>#include <node.h>
#include <v8.h>
#include <phidget21.h>

using namespace v8;

// ------------------------------------------
// Globals
// ------------------------------------------

CPhidgetBridgeHandle bridge = 0;

// ------------------------------------------
// Event handlers
// ------------------------------------------

int CCONV AttachHandler(CPhidgetHandle ADVSERVO, void *userptr)
{
    int serialNo;
    const char *name;

    CPhidget_getDeviceName (ADVSERVO, &name);
    CPhidget_getSerialNumber(ADVSERVO, &serialNo);
    printf("%s %10d attached!\n", name, serialNo);

    return 0;
}

int CCONV DetachHandler(CPhidgetHandle ADVSERVO, void *userptr)
{
    int serialNo;
    const char *name;

    CPhidget_getDeviceName (ADVSERVO, &name);
    CPhidget_getSerialNumber(ADVSERVO, &serialNo);
    printf("%s %10d detached!\n", name, serialNo);

    return 0;
}

int CCONV ErrorHandler(CPhidgetHandle ADVSERVO, void *userptr, int ErrorCode, const char *Description)
{
    printf("Error handled. %d - %s\n", ErrorCode, Description);
    return 0;
}

int CCONV BridgeDataHandler(CPhidgetBridgeHandle ADVSERVO, void *usrptr, int Index, double Value)
{
    printf("Bridge: %d > Current Data: %f\n", Index, Value);
    return 0;

}

int display_properties(CPhidgetBridgeHandle phid)
{
    int serialNo, version;
    int numSensor, rateMax, rateMin;
    const char* ptr;

    CPhidget_getDeviceType((CPhidgetHandle)phid, &ptr);
    CPhidget_getSerialNumber((CPhidgetHandle)phid, &serialNo);
    CPhidget_getDeviceVersion((CPhidgetHandle)phid, &version);

    CPhidgetBridge_getInputCount((CPhidgetBridgeHandle) phid, &numSensor);
    CPhidgetBridge_getDataRateMax((CPhidgetBridgeHandle) phid, &rateMax);
    CPhidgetBridge_getDataRateMin((CPhidgetBridgeHandle) phid, &rateMin);

    printf("%s\n", ptr);
    printf("Serial Number: %10d\nVersion: %8d\n# Sensor: %d\nData Rate: %d ~ %d\n",
                    serialNo, version, numSensor, rateMax, rateMin);

    return 0;
}

// ------------------------------------------
// Method abstractions
// ------------------------------------------

Handle<Value>
attach(const Arguments& args)
{
    HandleScope scope;

    int result;
    const char *err;
    CPhidgetBridgeHandle bridge;
    //CPhidget_enableLogging(PHIDGET_LOG_VERBOSE, NULL);

    CPhidgetBridge_create(&bridge);

    CPhidget_set_OnAttach_Handler((CPhidgetHandle)bridge, AttachHandler, NULL);
    CPhidget_set_OnDetach_Handler((CPhidgetHandle)bridge, DetachHandler, NULL);
    CPhidget_set_OnError_Handler((CPhidgetHandle)bridge, ErrorHandler, NULL);

    CPhidgetBridge_set_OnBridgeData_Handler(bridge, BridgeDataHandler, NULL);

    CPhidget_open((CPhidgetHandle)bridge, -1);

    //Wait for 10 seconds, otherwise exit
    if(result = CPhidget_waitForAttachment((CPhidgetHandle)bridge, 10000))
    {

        CPhidget_getErrorDescription(result, &err);
        printf("Problem waiting for attachment: %s\n", err);
        return ThrowException(Exception::Error(String::New("Could not attach to device.")));
    }

    // Display the properties of the attached device
    display_properties(bridge);

    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
close(const Arguments& args)
{
    HandleScope scope;

    CPhidget_close((CPhidgetHandle)bridge);
    CPhidget_delete((CPhidgetHandle)bridge);
    printf("Phidget Bridge is closed.\n");

    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
getValue(const Arguments& args)
{
    double value;

    HandleScope scope;
    CPhidgetBridge_getBridgeValue(bridge, args[0]->Int32Value(), &value);
    return scope.Close(Number::New(value));
}

Handle<Value>
getMax(const Arguments& args)
{
    double max;

    HandleScope scope;
    CPhidgetBridge_getBridgeMax(bridge, args[0]->Int32Value(), &max);
    return scope.Close(Integer::NewFromUnsigned(max));
}

Handle<Value>
getMin(const Arguments& args)
{
    double min;

    HandleScope scope;
    CPhidgetBridge_getBridgeMin(bridge, args[0]->Int32Value(), &min);
    return scope.Close(Integer::NewFromUnsigned(min));
}

Handle<Value>
setEnabled(const Arguments& args)
{
    HandleScope scope;
    CPhidgetBridge_setEnabled(bridge, args[0]->Int32Value(), args[1]->Int32Value());
    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
getEnabled(const Arguments& args)
{
    int enabled;
    HandleScope scope;
    CPhidgetBridge_getEnabled(bridge, args[0]->Int32Value(), &enabled);
    if(enabled)
        return scope.Close(Boolean::New(true));
    else
        return scope.Close(Boolean::New(false));
}

Handle<Value>
setGain(const Arguments& args)
{
    CPhidgetBridge_Gain gain;
    switch(args[1]->Int32Value()) {
        case 1:
            gain = PHIDGET_BRIDGE_GAIN_1;
            break;
        case 2:
            gain = PHIDGET_BRIDGE_GAIN_8;
            break;
        case 3:
            gain = PHIDGET_BRIDGE_GAIN_16;
            break;
        case 4:
            gain = PHIDGET_BRIDGE_GAIN_32;
            break;
        case 5:
            gain = PHIDGET_BRIDGE_GAIN_64;
            break;
        case 6:
            gain = PHIDGET_BRIDGE_GAIN_128;
            break;
        default:
            gain = PHIDGET_BRIDGE_GAIN_UNKNOWN;
    }
    HandleScope scope;
    CPhidgetBridge_setGain(bridge, args[0]->Int32Value(), gain);
    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
getGain(const Arguments& args)
{
    CPhidgetBridge_Gain gain;
    HandleScope scope;
    CPhidgetBridge_getGain(bridge, args[0]->Int32Value(), &gain);
    return scope.Close(Integer::NewFromUnsigned(gain));
}

Handle<Value>
setDataRate(const Arguments& args)
{
    HandleScope scope;
    CPhidgetBridge_setDataRate(bridge, args[0]->Int32Value());
    return scope.Close(Integer::NewFromUnsigned(0));
}

Handle<Value>
getDataRate(const Arguments& args)
{
    int dataRate;
    HandleScope scope;
    CPhidgetBridge_getDataRate(bridge, &dataRate);
    return scope.Close(Integer::NewFromUnsigned(dataRate));
}

// ------------------------------------------
// Module
// ------------------------------------------

void init(Handle<Object> target)
{
    // Connection
    target->Set(String::New("attach"), FunctionTemplate::New(attach)->GetFunction());
    target->Set(String::New("close"), FunctionTemplate::New(close)->GetFunction());

    // Bridge manipulation
    target->Set(String::New("setEnabled"), FunctionTemplate::New(setEnabled)->GetFunction());
    target->Set(String::New("setGain"), FunctionTemplate::New(setGain)->GetFunction());
    target->Set(String::New("setDataRate"), FunctionTemplate::New(setDataRate)->GetFunction());

    // Status
    target->Set(String::New("getValue"), FunctionTemplate::New(getValue)->GetFunction());
    target->Set(String::New("getMax"), FunctionTemplate::New(getMax)->GetFunction());
    target->Set(String::New("getMin"), FunctionTemplate::New(getMin)->GetFunction());
    target->Set(String::New("getEnabled"), FunctionTemplate::New(getEnabled)->GetFunction());
    target->Set(String::New("getGain"), FunctionTemplate::New(getGain)->GetFunction());
    target->Set(String::New("getDataRate"), FunctionTemplate::New(getDataRate)->GetFunction());
}

NODE_MODULE(binding_bridge, init);
<|endoftext|>


<commit_before>/*
** Copyright (c) 2015 Boise Center Aerospace Laboratory
**
** Author: Kyle Shannon <kyle at pobox dot com>
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "pulsereader.hpp"

/*
** This program opens and reads a pulse waves file, and outputs pertinent
** information for each in/out waveform.  The output should be consumable by
** matlab.
*/

void Usage() {
    printf("pw input.pls output_prefix\n");
    exit(1);
}

int main(int argc, char *argv[]) {
    PULSEreadOpener pOpener;
    PULSEreader *pReader;
    WAVESsampling *sampling;
    int i, j, k;
    char *szPulseOut, *szWaveOut, *szWaveIn, *szBase;
    FILE *pout;
    FILE *wout;
    FILE **wins;
    int nwins = 1;

    /* start with one incoming file */
    wins = (FILE**)malloc(sizeof(FILE*) * nwins);

    if(argc < 3) {
        Usage();
    }
    pOpener.set_file_name(argv[1]);
    pReader = pOpener.open();
    if(pReader == 0)
    {
        printf("Could not open file\n");
        return 1;
    }

    /* Open n files for output */
    szPulseOut = (char*)calloc(8192, 1);
    szWaveIn = (char*)calloc(8192, 1);
    szWaveOut = (char*)calloc(8192, 1);
    szBase = argv[2];
    sprintf(szPulseOut, "%s_PULSE.csv", szBase);
    sprintf(szWaveIn, "%s_WAVE_IN.txt", szBase);
    sprintf(szWaveOut, "%s_WAVE_OUT.txt", szBase);

    pout = fopen(szPulseOut, "w");
    fprintf(pout, "id,");
    fprintf(pout, "gps,");
    fprintf(pout, "anchor_x,anchor_y,anchor_z,");
    fprintf(pout, "target_x,target_y,target_z,");
    fprintf(pout, "first_return_x,first_return_y,first_return_z,");
    fprintf(pout, "last_return_x,last_return_y,last_return_z,");
    fprintf(pout, "edge,scan_dir,"); /* bit, written as uint8 */
    fprintf(pout, "facet,"); /* 2 bit, written as uint8 */
    fprintf(pout, "intensity\n"); /* uint8 */

    const char szPulseFormat[] = "%lld," \
                                 "%lf," \
                                 "%lf,%lf,%lf," \
                                 "%lf,%lf,%lf," \
                                 "%lf,%lf,%lf," \
                                 "%lf,%lf,%lf," \
                                 "%d,%d," \
                                 "%d," \
                                 "%d\n";

    for(i = 0; i < nwins; i++) {
        sprintf(szWaveIn, "%s_WAVE_IN_%d.txt", szBase, i);
        wins[i] = fopen(szWaveIn, "w");
    }
    wout = fopen(szWaveOut, "w");

    double gpsTime;
    double xa, ya, za;
    double xt, yt, zt;
    double dx, dy, dz;
    double xf, yf, zf;
    double xl, yl, zl;
    unsigned char edge;
    unsigned char scan_dir;
    unsigned char intensity;
    long long p = 0;
    int rc = 0;
    int fi = 0;
    while(pReader->read_pulse()) {
        /* Write line to pulse file */
        gpsTime = pReader->pulse.T * pReader->header.t_scale_factor + pReader->header.t_offset;
        xa = pReader->pulse.anchor_X * pReader->header.x_scale_factor + pReader->header.x_offset;
        ya = pReader->pulse.anchor_X * pReader->header.y_scale_factor + pReader->header.y_offset;
        za = pReader->pulse.anchor_X * pReader->header.z_scale_factor + pReader->header.z_offset;
        xt = pReader->pulse.target_X * pReader->header.x_scale_factor + pReader->header.x_offset;
        yt = pReader->pulse.target_X * pReader->header.y_scale_factor + pReader->header.y_offset;
        zt = pReader->pulse.target_X * pReader->header.z_scale_factor + pReader->header.z_offset;
        dx = (xt - xa) / 1000;
        dy = (yt - ya) / 1000;
        dz = (zt - za) / 1000;
        xf = xa + pReader->pulse.first_returning_sample * dx;
        yf = ya + pReader->pulse.first_returning_sample * dy;
        zf = za + pReader->pulse.first_returning_sample * dz;
        xl = xa + pReader->pulse.last_returning_sample * dx;
        yl = ya + pReader->pulse.last_returning_sample * dy;
        zl = za + pReader->pulse.last_returning_sample * dz;

        edge = pReader->pulse.edge_of_scan_line;
        scan_dir = pReader->pulse.scan_direction;
        intensity = pReader->pulse.intensity;

        rc = fprintf(pout, szPulseFormat, p,
                                          gpsTime,
                                          xa, ya, za,
                                          xt, yt, zt,
                                          xf, yf, zf,
                                          xl, yl, zl,
                                          edge, scan_dir,
                                          pReader->pulse.mirror_facet,
                                          intensity);

        if(pReader->read_waves()) {
            for(i = 0; i < pReader->waves->get_number_of_samplings(); i++) {
                sampling = pReader->waves->get_sampling(i);
                if(sampling->get_type() == PULSEWAVES_OUTGOING) {
                    fprintf(wout, "%lld ", p);
                    for(j = 0; j < sampling->get_number_of_segments(); j++ ) {
                        fi = 0;
                        fprintf(wout, "%lld ", p);
                        for(k = 0; k < sampling->get_number_of_samples(); k++) {
                            fprintf(wout, "%u ", sampling->get_sample(k));
                        }
                    }
                    fprintf(wout, "\n");
                } else { /* PULSEWAVES_INCOMING */
                    for(j = 0; j < sampling->get_number_of_segments(); j++ ) {
                        /* Need new file? */
                        if(j >= nwins) {
                            wins = (FILE**)realloc(wins, sizeof(FILE*) * ++nwins);
                            sprintf(szWaveIn, "%s_WAVE_IN_%d.txt", szBase, nwins-1);
                            wins[j] = fopen(szWaveIn, "w");
                            printf("Creating new incoming wave file for %d: %s\n",
                                   j, szWaveIn);
                        }
                        fprintf(wins[j], "%lld ", p);
                        for(k = 0; k < sampling->get_number_of_samples(); k++) {
                            fprintf(wins[j], "%u ", sampling->get_sample(k));
                        }
                        fprintf(wins[j], "\n");
                    }
                }
            }
        } else {
            /* No data??? */
        }
        p++;
    }

    free(szPulseOut);
    free(szWaveIn);
    free(szWaveOut);
    pReader->close();
    delete pReader;

    fclose(pout);
    fclose(wout);
    for(i = 0; i < nwins; i++) {
        fclose(wins[i]);
    }
    free(wins);

    return 0;
}

<commit_msg>blurb about missing data<commit_after>/*
** Copyright (c) 2015 Boise Center Aerospace Laboratory
**
** Author: Kyle Shannon <kyle at pobox dot com>
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "pulsereader.hpp"

/*
** This program opens and reads a pulse waves file, and outputs pertinent
** information for each in/out waveform.  The output should be consumable by
** matlab.
*/

void Usage() {
    printf("pw input.pls output_prefix\n");
    exit(1);
}

int main(int argc, char *argv[]) {
    PULSEreadOpener pOpener;
    PULSEreader *pReader;
    WAVESsampling *sampling;
    int i, j, k;
    char *szPulseOut, *szWaveOut, *szWaveIn, *szBase;
    FILE *pout;
    FILE *wout;
    FILE **wins;
    int nwins = 1;

    /* start with one incoming file */
    wins = (FILE**)malloc(sizeof(FILE*) * nwins);

    if(argc < 3) {
        Usage();
    }
    pOpener.set_file_name(argv[1]);
    pReader = pOpener.open();
    if(pReader == 0)
    {
        printf("Could not open file\n");
        return 1;
    }

    /* Open n files for output */
    szPulseOut = (char*)calloc(8192, 1);
    szWaveIn = (char*)calloc(8192, 1);
    szWaveOut = (char*)calloc(8192, 1);
    szBase = argv[2];
    sprintf(szPulseOut, "%s_PULSE.csv", szBase);
    sprintf(szWaveIn, "%s_WAVE_IN.txt", szBase);
    sprintf(szWaveOut, "%s_WAVE_OUT.txt", szBase);

    pout = fopen(szPulseOut, "w");
    fprintf(pout, "id,");
    fprintf(pout, "gps,");
    fprintf(pout, "anchor_x,anchor_y,anchor_z,");
    fprintf(pout, "target_x,target_y,target_z,");
    fprintf(pout, "first_return_x,first_return_y,first_return_z,");
    fprintf(pout, "last_return_x,last_return_y,last_return_z,");
    fprintf(pout, "edge,scan_dir,"); /* bit, written as uint8 */
    fprintf(pout, "facet,"); /* 2 bit, written as uint8 */
    fprintf(pout, "intensity\n"); /* uint8 */

    const char szPulseFormat[] = "%lld," \
                                 "%lf," \
                                 "%lf,%lf,%lf," \
                                 "%lf,%lf,%lf," \
                                 "%lf,%lf,%lf," \
                                 "%lf,%lf,%lf," \
                                 "%d,%d," \
                                 "%d," \
                                 "%d\n";

    for(i = 0; i < nwins; i++) {
        sprintf(szWaveIn, "%s_WAVE_IN_%d.txt", szBase, i);
        wins[i] = fopen(szWaveIn, "w");
    }
    wout = fopen(szWaveOut, "w");

    double gpsTime;
    double xa, ya, za;
    double xt, yt, zt;
    double dx, dy, dz;
    double xf, yf, zf;
    double xl, yl, zl;
    unsigned char edge;
    unsigned char scan_dir;
    unsigned char intensity;
    long long p = 0;
    int rc = 0;
    int fi = 0;
    while(pReader->read_pulse()) {
        /* Write line to pulse file */
        gpsTime = pReader->pulse.T * pReader->header.t_scale_factor + pReader->header.t_offset;
        xa = pReader->pulse.anchor_X * pReader->header.x_scale_factor + pReader->header.x_offset;
        ya = pReader->pulse.anchor_X * pReader->header.y_scale_factor + pReader->header.y_offset;
        za = pReader->pulse.anchor_X * pReader->header.z_scale_factor + pReader->header.z_offset;
        xt = pReader->pulse.target_X * pReader->header.x_scale_factor + pReader->header.x_offset;
        yt = pReader->pulse.target_X * pReader->header.y_scale_factor + pReader->header.y_offset;
        zt = pReader->pulse.target_X * pReader->header.z_scale_factor + pReader->header.z_offset;
        dx = (xt - xa) / 1000;
        dy = (yt - ya) / 1000;
        dz = (zt - za) / 1000;
        xf = xa + pReader->pulse.first_returning_sample * dx;
        yf = ya + pReader->pulse.first_returning_sample * dy;
        zf = za + pReader->pulse.first_returning_sample * dz;
        xl = xa + pReader->pulse.last_returning_sample * dx;
        yl = ya + pReader->pulse.last_returning_sample * dy;
        zl = za + pReader->pulse.last_returning_sample * dz;

        edge = pReader->pulse.edge_of_scan_line;
        scan_dir = pReader->pulse.scan_direction;
        intensity = pReader->pulse.intensity;

        rc = fprintf(pout, szPulseFormat, p,
                                          gpsTime,
                                          xa, ya, za,
                                          xt, yt, zt,
                                          xf, yf, zf,
                                          xl, yl, zl,
                                          edge, scan_dir,
                                          pReader->pulse.mirror_facet,
                                          intensity);

        if(pReader->read_waves()) {
            for(i = 0; i < pReader->waves->get_number_of_samplings(); i++) {
                sampling = pReader->waves->get_sampling(i);
                if(sampling->get_type() == PULSEWAVES_OUTGOING) {
                    fprintf(wout, "%lld ", p);
                    for(j = 0; j < sampling->get_number_of_segments(); j++ ) {
                        fi = 0;
                        fprintf(wout, "%lld ", p);
                        for(k = 0; k < sampling->get_number_of_samples(); k++) {
                            fprintf(wout, "%u ", sampling->get_sample(k));
                        }
                    }
                    fprintf(wout, "\n");
                } else { /* PULSEWAVES_INCOMING */
                    for(j = 0; j < sampling->get_number_of_segments(); j++ ) {
                        /* Need new file? */
                        if(j >= nwins) {
                            wins = (FILE**)realloc(wins, sizeof(FILE*) * ++nwins);
                            sprintf(szWaveIn, "%s_WAVE_IN_%d.txt", szBase, nwins-1);
                            wins[j] = fopen(szWaveIn, "w");
                            printf("Creating new incoming wave file for %d: %s\n",
                                   j, szWaveIn);
                        }
                        fprintf(wins[j], "%lld ", p);
                        for(k = 0; k < sampling->get_number_of_samples(); k++) {
                            fprintf(wins[j], "%u ", sampling->get_sample(k));
                        }
                        fprintf(wins[j], "\n");
                    }
                }
            }
        } else {
            /* No data??? */
            printf("NO DATA!\n");
        }
        p++;
    }

    free(szPulseOut);
    free(szWaveIn);
    free(szWaveOut);
    pReader->close();
    delete pReader;

    fclose(pout);
    fclose(wout);
    for(i = 0; i < nwins; i++) {
        fclose(wins[i]);
    }
    free(wins);

    return 0;
}

<|endoftext|>


<commit_before>#include "vm.h"

int *text,            // text segment
    *old_text,        // for dump text segment
    *stack;           // stack

char *data;           // data segment
const int stack_size = 1024;

int *eip,
	*eax,
	*ebx,
	*ecx,
	*edx,
	*ebp,
	*esp;

void eval();
void entry();

int main() {
	text = new int[stack_size];
	old_text = new int[stack_size];
	stack = new int[stack_size];
	data = new char[stack_size];

	eax = new int();
	ebx = new int();
	ebx = new int();
	edx = new int();

	ebx = stack;
	esp = stack;

	size_t i = 0;
	eip = text;
	text[i++] = LOADA; // LOADA 10
	text[i++] = 10;
	text[i++] = LOADB;
	text[i++] = 20;
	text[i++] = ADD;
	text[i++] = HALT;

	entry();
}

void entry() {
	eval();
}

void eval() {
	int op, *tmp;
	while (1) {
		op = *eip;
		//std::cout << "current op: " << op << std::endl;
		if (op == HALT) {
			std::cout << "Result: " << *eax << std::endl;
			break;
		}
		switch (op) {
			case ADD:
				*eax = *eax + *ebx;
				break;
			case SUB:
				*eax = *eax - *ebx;
				break;
			case LOADA:
				eip++;
				*eax = *eip;
				break;
			case LOADB:
				eip++;
				*ebx = *eip;
				break;
			default:
				std::cout << "Wrong op!" << std::endl;
		}
		eip++;
	}
}

<commit_msg>refactor<commit_after>#include "vm.h"

int *text,            // text segment
    *old_text,        // for dump text segment
    *stack;           // stack

char *data;           // data segment
const int stack_size = 1024;

int *eip,
	*eax,
	*ebx,
	*ecx,
	*edx,
	*ebp,
	*esp;

void init();
void test();
void eval();
void entry();

int main() {
	init();
	test();
	entry();
}

void test() {
	size_t i = 0;
	eip = text;
	text[i++] = LOADA; // LOADA 10
	text[i++] = 10;
	text[i++] = LOADB;
	text[i++] = 20;
	text[i++] = ADD;
	text[i++] = HALT;
}
void init() {
	text = new int[stack_size];
	old_text = new int[stack_size];
	stack = new int[stack_size];
	data = new char[stack_size];

	eax = new int();
	ebx = new int();
	ebx = new int();
	edx = new int();

	ebx = stack;
	esp = stack;
}
void entry() {
	eval();
}

void eval() {
	int op, *tmp;
	while (1) {
		op = *eip;
		//std::cout << "current op: " << op << std::endl;
		if (op == HALT) {
			std::cout << "Result: " << *eax << std::endl;
			break;
		}
		switch (op) {
			case ADD:
				*eax = *eax + *ebx;
				break;
			case SUB:
				*eax = *eax - *ebx;
				break;
			case LOADA:
				eip++;
				*eax = *eip;
				break;
			case LOADB:
				eip++;
				*ebx = *eip;
				break;
			default:
				std::cout << "Wrong op!" << std::endl;
		}
		eip++;
	}
}

<|endoftext|>


<commit_before>#include "vm.h"

int *text,            // text segment
    *old_text,        // for dump text segment
    *stack;           // stack

char *data;           // data segment
const int stack_size = 1024;

int *eip,
	*eax,
	*ebx,
	*ecx,
	*edx,
	*ebp,
	*esp;

void eval();
void entry();

int main() {
	text = new int[stack_size];
	old_text = new int[stack_size];
	stack = new int[stack_size];
	data = new char[stack_size];

	ebx = stack;
	esp = stack;

	size_t i = 0;
	text[i++] = LOADA; // LOADA 10
	text[i++] = 10;
	text[i++] = LOADB;
	text[i++] = 20;
	text[i++] = ADD;
	text[i++] = HALT;

	entry();
}

void entry() {
	eval();
}

void eval() {
	int op, *tmp;
	while (1) {
		eip++;
		switch (op) {
			case ADD:
				*eax = *eax + *ebx;
				break;
			case SUB:
				*eax = *eax - *ebx;
				break;
			case LOADA:
				eip++;
				*eax = *eip;
				break;
			case HALT:
				std::cout << "Result: " << *eax << std::endl;
			default:
				std::cout << "Wrong op!" << std::endl;
		}
	}
}

<commit_msg>now vm can work at least<commit_after>#include "vm.h"

int *text,            // text segment
    *old_text,        // for dump text segment
    *stack;           // stack

char *data;           // data segment
const int stack_size = 1024;

int *eip,
	*eax,
	*ebx,
	*ecx,
	*edx,
	*ebp,
	*esp;

void eval();
void entry();

int main() {
	text = new int[stack_size];
	old_text = new int[stack_size];
	stack = new int[stack_size];
	data = new char[stack_size];

	eax = new int();
	ebx = new int();
	ebx = new int();
	edx = new int();

	ebx = stack;
	esp = stack;

	size_t i = 0;
	eip = text;
	text[i++] = LOADA; // LOADA 10
	text[i++] = 10;
	text[i++] = LOADB;
	text[i++] = 20;
	text[i++] = ADD;
	text[i++] = HALT;

	entry();
}

void entry() {
	eval();
}

void eval() {
	int op, *tmp;
	while (1) {
		op = *eip;
		//std::cout << "current op: " << op << std::endl;
		if (op == HALT) {
			std::cout << "Result: " << *eax << std::endl;
			break;
		}
		switch (op) {
			case ADD:
				*eax = *eax + *ebx;
				break;
			case SUB:
				*eax = *eax - *ebx;
				break;
			case LOADA:
				eip++;
				*eax = *eip;
				break;
			case LOADB:
				eip++;
				*ebx = *eip;
				break;
			default:
				std::cout << "Wrong op!" << std::endl;
		}
		eip++;
	}
}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "scatter-asm/ssasm_pre.h"d
#include "scatter-asm/ssutil.h"
#include "scatter-asm/ssbase_type.h"
#include "scatter-asm/sslang.h"
#include "scatter-asm/sssystem.h"
#include "scatter-asm/sslexeme.h"
#include "scatter-asm/ssasm.h"

#include "scatter-vm/ssvm_pre.h"
#include "scatter-vm/sslang_vm.h"
#include "scatter-vm/ssvm.h"

FILE*  g_SourceFile;
char   g_SourceFileName[MAX_FILENAME_SIZE];
int    g_SourceCodeLines;
char** g_SourceCode;
char   g_ExeFileName[MAX_FILENAME_SIZE];
char   g_ExeInfoFilename[MAX_FILENAME_SIZE];

LinkList g_FunctionTable;
LinkList g_StringTable;
LinkList g_LabelTable;
LinkList g_SymbolTable;
LinkList g_HostAPICallTable;

Lexer  g_Lexer;
ScriptHeader g_ScriptHeader;
ASM_Instr* g_InstrStream;

int g_InstrStreamSize;
int g_IsSetStackSizeFound;
int g_currentInstrIndex;

InstrLookup g_InstrTable[MAX_INSTR_LOOKUP_COUNT];

Script g_Script;

void asm_run();
void vm_run(char* exeFilename);
void compile();

int main(int argc, char* argv[])
{

	char option[3];
	if (argv[1][0] == '-')
	{
		strcpy(option, argv[1]);
		option[2] = '\0';
		switch (option[1])
		{
		case 'c':
			break;
		case 'a':
			{
				strcpy(g_SourceFileName, argv[2]);

				if (argv[3])
				{
					strcpy(g_ExeFileName, argv[3]);
					if (! strstr(g_ExeFileName, EXE_EXTENSION))
						strcat(g_ExeFileName, EXE_EXTENSION);
				}
				else
				{
					int ExtOffset = strrchr(g_SourceFileName, '.') - g_SourceFileName;
					strncpy(g_ExeFileName, g_SourceFileName, ExtOffset);
					g_ExeFileName[ExtOffset] = '\0';
					strcat(g_ExeFileName, EXE_EXTENSION);
				}

				asm_run();
			}
			break;
		case 'o':
			break;
		default:
			break;
		}
	}
	else
	{
		if (argc < 2)
		{
			printf("Wrong usage !\n");
			return 0;
		}

		char* exeFilename = (char*) malloc(strlen(argv[1]) + 1);
		strcpy(exeFilename, argv[1]);

		vm_run(exeFilename);
	}

}

void asm_run()
{
	strcpy(g_ExeInfoFilename, g_ExeFileName);
	strcat(g_ExeInfoFilename, ".info");

	ASM_Init();

	LoadSourceFile();

	AssembleSourceFile();

	BuildSSE();

	BuildSSE_Info();

	ASM_ShutDown();
}

void vm_run(char* exeFilename)
{
	VM_Init();

	int errorCode = LoadScript(exeFilename);

	if (errorCode != LOAD_OK)
	{
		printf("Error: ");
		switch (errorCode)
		{
		case LOAD_ERROR_FAIL_FILE_OPEN:
			printf("Can not open sse file");
			break;

		case LOAD_ERROR_INVALID_SSE:
			printf("Invalid sse file");
			break;

		case LOAD_ERROR_UNSOPPORTED_VERSION:
			printf("Unsupported sse version");
			break;

		default:
			break;
		}
		printf(".\n");
	}

	ResetScript();

	RunScript();

	VM_ShutDown();
}
void compile()
{

}<commit_msg>remove type error<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "scatter-asm/ssasm_pre.h"
#include "scatter-asm/ssutil.h"
#include "scatter-asm/ssbase_type.h"
#include "scatter-asm/sslang.h"
#include "scatter-asm/sssystem.h"
#include "scatter-asm/sslexeme.h"
#include "scatter-asm/ssasm.h"

#include "scatter-vm/ssvm_pre.h"
#include "scatter-vm/sslang_vm.h"
#include "scatter-vm/ssvm.h"

FILE*  g_SourceFile;
char   g_SourceFileName[MAX_FILENAME_SIZE];
int    g_SourceCodeLines;
char** g_SourceCode;
char   g_ExeFileName[MAX_FILENAME_SIZE];
char   g_ExeInfoFilename[MAX_FILENAME_SIZE];

LinkList g_FunctionTable;
LinkList g_StringTable;
LinkList g_LabelTable;
LinkList g_SymbolTable;
LinkList g_HostAPICallTable;

Lexer  g_Lexer;
ScriptHeader g_ScriptHeader;
ASM_Instr* g_InstrStream;

int g_InstrStreamSize;
int g_IsSetStackSizeFound;
int g_currentInstrIndex;

InstrLookup g_InstrTable[MAX_INSTR_LOOKUP_COUNT];

Script g_Script;

void asm_run();
void vm_run(char* exeFilename);
void compile();

int main(int argc, char* argv[])
{

	char option[3];
	if (argv[1][0] == '-')
	{
		strcpy(option, argv[1]);
		option[2] = '\0';
		switch (option[1])
		{
		case 'c':
			break;
		case 'a':
			{
				strcpy(g_SourceFileName, argv[2]);

				if (argv[3])
				{
					strcpy(g_ExeFileName, argv[3]);
					if (! strstr(g_ExeFileName, EXE_EXTENSION))
						strcat(g_ExeFileName, EXE_EXTENSION);
				}
				else
				{
					int ExtOffset = strrchr(g_SourceFileName, '.') - g_SourceFileName;
					strncpy(g_ExeFileName, g_SourceFileName, ExtOffset);
					g_ExeFileName[ExtOffset] = '\0';
					strcat(g_ExeFileName, EXE_EXTENSION);
				}

				asm_run();
			}
			break;
		case 'o':
			break;
		default:
			break;
		}
	}
	else
	{
		if (argc < 2)
		{
			printf("Wrong usage !\n");
			return 0;
		}

		char* exeFilename = (char*) malloc(strlen(argv[1]) + 1);
		strcpy(exeFilename, argv[1]);

		vm_run(exeFilename);
	}

}

void asm_run()
{
	strcpy(g_ExeInfoFilename, g_ExeFileName);
	strcat(g_ExeInfoFilename, ".info");

	ASM_Init();

	LoadSourceFile();

	AssembleSourceFile();

	BuildSSE();

	BuildSSE_Info();

	ASM_ShutDown();
}

void vm_run(char* exeFilename)
{
	VM_Init();

	int errorCode = LoadScript(exeFilename);

	if (errorCode != LOAD_OK)
	{
		printf("Error: ");
		switch (errorCode)
		{
		case LOAD_ERROR_FAIL_FILE_OPEN:
			printf("Can not open sse file");
			break;

		case LOAD_ERROR_INVALID_SSE:
			printf("Invalid sse file");
			break;

		case LOAD_ERROR_UNSOPPORTED_VERSION:
			printf("Unsupported sse version");
			break;

		default:
			break;
		}
		printf(".\n");
	}

	ResetScript();

	RunScript();

	VM_ShutDown();
}
void compile()
{

}<|endoftext|>


<commit_before>
#include <iostream>
#include "path.h"

namespace
{
	constexpr double PI = 3.14159265358979323846;
}

namespace core
{

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

path::path( void )
{
}

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

path::path( const point &p )
{
	move_to( p );
}

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

path::~path( void )
{
}

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

void path::move_to( const point &p )
{
	add( p );
	_last = p;
	_actions.push_back( action::MOVE );
}

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

void path::line_to( const point &p )
{
	add( p );
	_last = p;
	_actions.push_back( action::LINE );
}

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

void path::quadratic_to( const point &p1, const point &p2 )
{
	add( p1, p2 );
	_last = p2;
	_actions.push_back( action::QUADRATIC );
}

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

void path::cubic_to( const point &p1, const point &p2, const point &p3 )
{
	add( p1, p2, p3 );
	_last = p3;
	_actions.push_back( action::CUBIC );
}

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

void path::arc_to( const point &center, double radius, double angle1, double angle2 )
{
	add( center, radius, angle1, angle2 );
	_last = center + point::polar( radius, angle2 );
	_actions.push_back( action::ARC );
}

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

void path::close( void )
{
	if ( _start < _actions.size() )
	{
		_actions.push_back( action::CLOSE );
		_start = _actions.size();
	}
}

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

void path::circle( const point &center, double radius )
{
	move_to( { center.x() + radius, center.y() } );
	arc_to( center, radius, 0.0, PI * 2.0 );
	close();
}

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

void path::rectangle( const point &p1, const point &p2 )
{
	const double x1 = std::min( p1.x(), p2.x() );
	const double y1 = std::min( p1.y(), p2.y() );
	const double x2 = std::max( p1.x(), p2.x() );
	const double y2 = std::max( p1.y(), p2.y() );

	move_to( { x1, y1 } );
	line_to( { x2, y1 } );
	line_to( { x2, y2 } );
	line_to( { x1, y2 } );
	close();
}

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

void path::rounded_rect( const point &p1, const point &p2, double r )
{
	const double x1 = std::min( p1.x(), p2.x() );
	const double y1 = std::min( p1.y(), p2.y() );
	const double x2 = std::max( p1.x(), p2.x() ) - 1.0;
	const double y2 = std::max( p1.y(), p2.y() ) - 1.0;

	const double degrees = PI / 180.0;

	move_to( { x1 + r, y1 } );
	arc_to( { x2 - r, y1 + r }, r, -90.0 * degrees, 0.0 * degrees );
	arc_to( { x2 - r, y2 - r }, r, 0.0 * degrees, 90.0 * degrees );
	arc_to( { x1 + r, y2 - r }, r, 90.0 * degrees, 180.0 * degrees );
	arc_to( { x1 + r, y1 + r }, r, 180.0 * degrees, 270.0 * degrees );
	close();
}

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

void path::rounded_rect( const point &p1, double w, double h, double r )
{
	rounded_rect( p1, { p1.x() + w - 1.0, p1.y() + h - 1.0 }, r );
}

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

std::ostream &operator<<( std::ostream &out, const path &p )
{
	class printer
	{
	public:
		printer( std::ostream &o )
			: out( o )
		{
		}

		void move_to( const point &p )
		{
			out << "Move( " << p << " )\n";
		}

		void line_to( const point &p )
		{
			out << "Line( " << p << " )\n";
		}

		void quadratic_to( const point &p1, const point &p2 )
		{
			out << "Quadratic( " << p1 << ", " << p2 << " )\n";
		}

		void cubic_to( const point &p1, const point &p2, const point &p3 )
		{
			out << "Cubic( " << p1 << ", " << p2 << ", " << p3 << " )\n";
		}

		void arc_to( const point &center, double radius, double angle1, double angle2 )
		{
			out << "Arc( " << center << ", " << radius << ", " << angle1 * 180 / PI << ", " << angle2 * 180 / PI << " )\n";
		}

		void close( void )
		{
			out << "Close()\n";
		}

	private:
		std::ostream &out;
	};

	printer show( out );
	p.replay( show );

	return out;
}

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

}

<commit_msg>Fixed const expression.<commit_after>
#include <iostream>
#include "path.h"

namespace
{
	constexpr double PI = 3.14159265358979323846;
}

namespace core
{

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

path::path( void )
{
}

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

path::path( const point &p )
{
	move_to( p );
}

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

path::~path( void )
{
}

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

void path::move_to( const point &p )
{
	add( p );
	_last = p;
	_actions.push_back( action::MOVE );
}

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

void path::line_to( const point &p )
{
	add( p );
	_last = p;
	_actions.push_back( action::LINE );
}

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

void path::quadratic_to( const point &p1, const point &p2 )
{
	add( p1, p2 );
	_last = p2;
	_actions.push_back( action::QUADRATIC );
}

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

void path::cubic_to( const point &p1, const point &p2, const point &p3 )
{
	add( p1, p2, p3 );
	_last = p3;
	_actions.push_back( action::CUBIC );
}

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

void path::arc_to( const point &center, double radius, double angle1, double angle2 )
{
	add( center, radius, angle1, angle2 );
	_last = center + point::polar( radius, angle2 );
	_actions.push_back( action::ARC );
}

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

void path::close( void )
{
	if ( _start < _actions.size() )
	{
		_actions.push_back( action::CLOSE );
		_start = _actions.size();
	}
}

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

void path::circle( const point &center, double radius )
{
	move_to( { center.x() + radius, center.y() } );
	arc_to( center, radius, 0.0, PI * 2.0 );
	close();
}

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

void path::rectangle( const point &p1, const point &p2 )
{
	const double x1 = std::min( p1.x(), p2.x() );
	const double y1 = std::min( p1.y(), p2.y() );
	const double x2 = std::max( p1.x(), p2.x() );
	const double y2 = std::max( p1.y(), p2.y() );

	move_to( { x1, y1 } );
	line_to( { x2, y1 } );
	line_to( { x2, y2 } );
	line_to( { x1, y2 } );
	close();
}

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

void path::rounded_rect( const point &p1, const point &p2, double r )
{
	const double x1 = std::min( p1.x(), p2.x() );
	const double y1 = std::min( p1.y(), p2.y() );
	const double x2 = std::max( p1.x(), p2.x() ) - 1.0;
	const double y2 = std::max( p1.y(), p2.y() ) - 1.0;

	constexpr double degrees = PI / 180.0;

	move_to( { x1 + r, y1 } );
	arc_to( { x2 - r, y1 + r }, r, -90.0 * degrees, 0.0 * degrees );
	arc_to( { x2 - r, y2 - r }, r, 0.0 * degrees, 90.0 * degrees );
	arc_to( { x1 + r, y2 - r }, r, 90.0 * degrees, 180.0 * degrees );
	arc_to( { x1 + r, y1 + r }, r, 180.0 * degrees, 270.0 * degrees );
	close();
}

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

void path::rounded_rect( const point &p1, double w, double h, double r )
{
	rounded_rect( p1, { p1.x() + w - 1.0, p1.y() + h - 1.0 }, r );
}

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

std::ostream &operator<<( std::ostream &out, const path &p )
{
	class printer
	{
	public:
		printer( std::ostream &o )
			: out( o )
		{
		}

		void move_to( const point &p )
		{
			out << "Move( " << p << " )\n";
		}

		void line_to( const point &p )
		{
			out << "Line( " << p << " )\n";
		}

		void quadratic_to( const point &p1, const point &p2 )
		{
			out << "Quadratic( " << p1 << ", " << p2 << " )\n";
		}

		void cubic_to( const point &p1, const point &p2, const point &p3 )
		{
			out << "Cubic( " << p1 << ", " << p2 << ", " << p3 << " )\n";
		}

		void arc_to( const point &center, double radius, double angle1, double angle2 )
		{
			out << "Arc( " << center << ", " << radius << ", " << angle1 * 180 / PI << ", " << angle2 * 180 / PI << " )\n";
		}

		void close( void )
		{
			out << "Close()\n";
		}

	private:
		std::ostream &out;
	};

	printer show( out );
	p.replay( show );

	return out;
}

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

}

<|endoftext|>


<commit_before>#include "InOutManager.h"
#include "SelfPositionManager.h"
#include "ETSumoStrategy.h"
#include "HSLColor.h"
#include "ColorDecision.h"
#include "SerialData.h"
#include "PIDDataManager.h"
#include "Strategy.h"
#include "StrategyManager.h"
#include "PrizeStrategy.h"

#define OSHIDASHI_SPEED 20 // 押し出し動作時のスピード

#define FIRST_TURN_SPEED 32 // 高速旋回時の出力
#define TURN_SPEED 20 // 旋回時の出力

#define LEFT_ANGLE 90   // 左ブロック方向
#define RIGHT_ANGLE 270 // 右ブロック方向
#define FORWARD_ANGLE 1 // 正面方向

#define ONLINE 25	  // 黒線上での輝度値
#define NotONLINE 60  // 黒線以外での輝度値
//#define EDGE_LINE 120 // 黒線との境界線
#define EDGE_LINE 120 // 黒線との境界線

#define NOT_BLOCK_DISTANCE 8 // ブロックを認識していないときの距離
#define BLOCK_DISTANCE 3	 // ブロックを認識した時の距離

void ETSumoStrategy::Run()
{
	// 使用するシングルトンクラスのインスタンスを取得
	InOutManager *IOManager = InOutManager::GetInstance();
	SelfPositionManager *SpManager = SelfPositionManager::GetInstance();
	HSLColorKind DetectColor = IOManager->HSLKind;

	SpManager->ParticleFilterON = false;
ACTION :

	PIDData pid = PIDDataManager::GetInstance()->GetPIDData(ETSumoPIDState);
	PIDData pidH = PIDDataManager::GetInstance()->GetPIDData(ETSumoHighPIDState);

	int currentAngle = SpManager->RobotAngle;
	Point currentPoint = SpManager->RobotPoint;

	switch (CurrentState) {
	// 初回土俵入り時
	case FirstOnArena:
		// 黒線認識したら、初回黒線横断中に遷移
		if (IOManager->InputData.ReflectLight < ONLINE) {
			// ライントレース中なので、角度は常にライン方向
			SpManager->ResetAngle(FORWARD_ANGLE);
			SpManager->ResetY(2920);

			CurrentState = FirstOverLine;
			goto ACTION;
		}
		// 黒線まではラインの右エッジに沿ってライントレース
		if(CurrentArena == 0) {
			IOManager->LineTraceAction(pidH, EDGE_LINE, false);
		} else {
			IOManager->LineTraceAction(pid, EDGE_LINE, false);
		}
		break;

	// 初回黒線横断時
	case FirstOverLine:
		// 黒線を抜けたら、初回左ブロック方向旋回状態に遷移
		if (IOManager->InputData.ReflectLight > NotONLINE) {
			CurrentState = FirstTurnLeftPlace;
			goto ACTION;
		}
		// 黒線認識までは普通に直進
		IOManager->Forward(pid.BasePower);
		break;

	// 初回左ブロック旋回中
	case FirstTurnLeftPlace:
		// 左ブロック方向を向いたら、左ブロックまで直進中に遷移
		if(abs(currentAngle - LEFT_ANGLE) < 5){
			CurrentState = ForwardLeftPlace;
			goto ACTION;
		}

		IOManager->OutputData.LeftMotorPower = -1 * 0.25 * TURN_SPEED;
		IOManager->OutputData.RightMotorPower = TURN_SPEED;
		break;

		// 左ブロックまで直進
	case ForwardLeftPlace:
		// 超音波センサでブロックを認識した場合には、色認識に移行
		if (IOManager->InputData.SonarDistance <= BLOCK_DISTANCE) {
			CurrentState = DetectLeftBlock;
			// ブロック位置に到達したので、座標を修正
			SpManager->ResetY(2790);
			IOManager->Stop();
			break;
		}

		// ラインの右側をトレースしながらブロックに接近
		IOManager->LineTraceAction(pid, EDGE_LINE, false);

		// ライントレース中なので、角度は常にライン沿い
		SpManager->ResetAngle(LEFT_ANGLE);
		break;

	// 左ブロック色認識
	case DetectLeftBlock:
		// アームを上昇させて、色認識種別をブロックに変更
		IOManager->UpARMMotor();
		IOManager->HSLTargetType = BlockColor;

		// 色が一致している場合には、カウントを進める
		if (DetectColor == PrevColor && DetectColor != HSLBlack) {
			ColorDetectCount++;
			if (ColorDetectCount > 5) {
				ColorDetectCount = 0;
				ColorChangeCount = 0;
				// 色認識が完了したため、アームを下降させる
				IOManager->DownARMMotor();
				// フィールドの色と土俵の色が一致した場合、寄り切り
				if (ArenaArray[CurrentArena].LeftPlaceColor == DetectColor) {
					CurrentState = YORIKIRILeft;
				} else {
					// フィールドの色と土俵の色が異なる場合、押し出し
					CurrentState = OSHIDASHILeft;
				}
				break;
			}
		} else {
			PrevColor = DetectColor;
			ColorChangeCount++;

			// 色の変更を繰り返す場合には、強制的に次の認識色とする
			if(ColorChangeCount > 50) {
				ColorDetectCount = 11;
			} else {
				ColorDetectCount = 0;
			}
		}
		break;

	// 左ブロックを寄り切り
	case YORIKIRILeft:
		// ある程度旋回してから、黒線上に乗ったら右ブロックへの直進状態に移行
		if (IOManager->InputData.ReflectLight < EDGE_LINE &&
			abs(currentAngle - RIGHT_ANGLE) < 45) {
			CurrentState = ForwardRightPlace;
			goto ACTION;
		} else if (abs(currentAngle - RIGHT_ANGLE) < 25) {
			// 右ブロック方向を向くまで旋回
			IOManager->TurnCW(TURN_SPEED);
		} else {
			// 右ブロック方向を向くまで旋回（離れているため高速
			IOManager->TurnCW(FIRST_TURN_SPEED);
		}
		break;

	// 左ブロックを押し出し
	case OSHIDASHILeft:
		// 一定距離進んだら後退
		if(currentPoint.Y < 2750) {
			CurrentState = OSHIDASHILeftBack;
			IOManager->UpARMMotor();
			goto ACTION;
		}
		IOManager->Forward(OSHIDASHI_SPEED);
		break;
	case OSHIDASHILeftBack:
		// 一定距離後退したら、以降は寄り切りと一緒
		if(currentPoint.Y > 2775){
			IOManager->DownARMMotor();
			CurrentState = YORIKIRILeft;
			goto ACTION;
		}
		IOManager->Back(pid.BasePower);
		break;
	/// 右ブロックまで前進
	case ForwardRightPlace:
		// 超音波センサでブロックを認識した場合には、色認識に移行
		if (IOManager->InputData.SonarDistance <= BLOCK_DISTANCE) {
			CurrentState = DetectRightBlock;
			// 右ブロックを検知したため、座標を修正
			SpManager->ResetY(3050);
			IOManager->Stop();
			break;
		}

		// ラインに沿って右ブロック置き場に接近
		IOManager->LineTraceAction(pid, EDGE_LINE, true);
		// ライントレース中なので常に角度はライン沿い
		SpManager->ResetAngle(RIGHT_ANGLE);

		break;
	// 右ブロック色認識
	case DetectRightBlock:
		// アームを上昇させて、色認識種別をブロックに変更
		IOManager->UpARMMotor();
		IOManager->HSLTargetType = BlockColor;

		// 色が一致している場合には、カウントを進める
		if (DetectColor == PrevColor && DetectColor != HSLBlack) {
			ColorDetectCount++;
			if (ColorDetectCount > 5) {
				ColorDetectCount = 0;
				ColorChangeCount = 0;
				// 色認識が完了したため、アームを下降させる
				IOManager->DownARMMotor();
				// フィールドの色と土俵の色が一致した場合、寄り切り
				if (ArenaArray[CurrentArena].RightPlaceColor == DetectColor) {
					CurrentState = YORIKIRIRight;
				} else {
					// フィールドの色と土俵の色が異なる場合、押し出し
					CurrentState = OSHIDASHIRight;
				}
				break;
			}
		} else {
			// 色が異なった場合には再度カウント
			PrevColor = DetectColor;
			ColorChangeCount++;

			// 色の変更を繰り返す場合には、強制的に次の認識色とする
			if(ColorChangeCount > 50) {
				ColorDetectCount = 11;
			} else {
				ColorDetectCount = 0;
			}
			break;
		}
		break;

	// 右ブロックを寄り切り
	case YORIKIRIRight:
		// 斜め方向を向いたらフィールド走行状態に遷移
		if (abs(currentAngle - (LEFT_ANGLE)) < 10) {
			CurrentState = ForwardCenterFromRight;
			goto ACTION;
		} else if(abs(currentAngle - (LEFT_ANGLE)) < 25) {
			// 中央方向を向くまで旋回
			IOManager->TurnCCW(TURN_SPEED);
		} else {
			// 中央方向を向くまで旋回 (離れているので高速)
			IOManager->TurnCCW(FIRST_TURN_SPEED);
		}
		break;

	// 右ブロックを押し出し
	case OSHIDASHIRight:
		// 一定距離進んだら後退
		if(currentPoint.Y > 3090) {
			IOManager->UpARMMotor();
			CurrentState = OSHIDASHIRightBack;
			goto ACTION;
		}
		IOManager->Forward(OSHIDASHI_SPEED);
		break;
	case OSHIDASHIRightBack:
		// 一定距離後退したら、以降は寄り切りと一緒
		if(currentPoint.Y < 3070){
			IOManager->DownARMMotor();

			CurrentState = YORIKIRIRight;
			goto ACTION;
		}
		IOManager->Back(pid.BasePower);
		break;

	// 中央方向へ前進
	case ForwardCenterFromRight:
		// 黒線認識したら、前方旋回中状態に遷移
		if (IOManager->InputData.ReflectLight < ONLINE) {
			// 最後の土俵の場合には、懸賞運搬戦略に遷移
			if(CurrentArena == 3) {
				// 座標をクリア
				SpManager->ResetX(2470);
				SpManager->ResetY(2900);
				SpManager->ResetAngle(LEFT_ANGLE);

				IOManager->Stop();
				IOManager->WriteOutputMotor();
			    dly_tsk(100);

				Manager->SetStrategy(new PrizeStrategy(Manager));
				break;
			}
			dly_tsk(50);
			CurrentState = TurnForward;
			SpManager->ResetAngle(LEFT_ANGLE);
			break;
		}
		IOManager->LineTraceAction(pid, EDGE_LINE, false);
		break;

	case TurnForward:
		// 黒線上に乗ったら一枚の土俵攻略が終了
//		if (currentAngle > 305 && currentAngle < 355) {
		if (currentAngle < 6 || currentAngle > 350) {
			CurrentArena++;

			// 2枚目の攻略が完了した場合には、線路をまたぐ直進処理に遷移
			if(CurrentArena == 2) {
				SpManager->Distance = 0;
				CurrentState = ForwardRail;
				// 座標修正
				SpManager->ResetX(1920);
				goto ACTION;
			} else {
				// 2枚目でなければ、通常の処理に遷移
				CurrentState = FirstOnArena;
				goto ACTION;
			}
			break;
		}

		// 正面を向くまで旋回
		IOManager->OutputData.LeftMotorPower = TURN_SPEED;
		IOManager->OutputData.RightMotorPower =  -1 * 0.5 * TURN_SPEED;

		break;

	case ForwardRail:
		if(currentPoint.X > 2120) {
			// 線路を跨いだので、通常のライントレースに遷移
			CurrentState = FirstOnArena;
			goto ACTION;
		}

		// 最初はライントレース
		if(SpManager->Distance < 90) {
			IOManager->LineTraceAction(pid, EDGE_LINE, false);
		} else if(SpManager->Distance < 130){
			IOManager->Forward(25);
		} else {
			IOManager->LineTraceAction(pid, EDGE_LINE, false);
		}

		break;
	default:
		break;
	}
}<commit_msg>ET相撲の挙動を調整<commit_after>#include "InOutManager.h"
#include "SelfPositionManager.h"
#include "ETSumoStrategy.h"
#include "HSLColor.h"
#include "ColorDecision.h"
#include "SerialData.h"
#include "PIDDataManager.h"
#include "Strategy.h"
#include "StrategyManager.h"
#include "PrizeStrategy.h"

#define OSHIDASHI_SPEED 20 // 押し出し動作時のスピード

#define FIRST_TURN_SPEED 32 // 高速旋回時の出力
#define TURN_SPEED 20 // 旋回時の出力

#define LEFT_ANGLE 90   // 左ブロック方向
#define RIGHT_ANGLE 270 // 右ブロック方向
#define FORWARD_ANGLE 1 // 正面方向

#define ONLINE 25	  // 黒線上での輝度値
#define NotONLINE 60  // 黒線以外での輝度値
//#define EDGE_LINE 120 // 黒線との境界線
#define EDGE_LINE 120 // 黒線との境界線

#define NOT_BLOCK_DISTANCE 8 // ブロックを認識していないときの距離
#define BLOCK_DISTANCE 3	 // ブロックを認識した時の距離

void ETSumoStrategy::Run()
{
	// 使用するシングルトンクラスのインスタンスを取得
	InOutManager *IOManager = InOutManager::GetInstance();
	SelfPositionManager *SpManager = SelfPositionManager::GetInstance();
	HSLColorKind DetectColor = IOManager->HSLKind;

	SpManager->ParticleFilterON = false;
ACTION :

	PIDData pid = PIDDataManager::GetInstance()->GetPIDData(ETSumoPIDState);
	PIDData pidH = PIDDataManager::GetInstance()->GetPIDData(ETSumoHighPIDState);

	int currentAngle = SpManager->RobotAngle;
	Point currentPoint = SpManager->RobotPoint;

	switch (CurrentState) {
	// 初回土俵入り時
	case FirstOnArena:
		// 黒線認識したら、初回黒線横断中に遷移
		if (IOManager->InputData.ReflectLight < ONLINE) {
			// ライントレース中なので、角度は常にライン方向
			SpManager->ResetAngle(FORWARD_ANGLE);
			SpManager->ResetY(2920);

			CurrentState = FirstOverLine;
			goto ACTION;
		}
		// 黒線まではラインの右エッジに沿ってライントレース
		if(CurrentArena == 0) {
			IOManager->LineTraceAction(pidH, EDGE_LINE, false);
		} else {
			IOManager->LineTraceAction(pid, EDGE_LINE, false);
		}
		break;

	// 初回黒線横断時
	case FirstOverLine:
		// 黒線を抜けたら、初回左ブロック方向旋回状態に遷移
		if (IOManager->InputData.ReflectLight > NotONLINE) {
			CurrentState = FirstTurnLeftPlace;
			goto ACTION;
		}
		// 黒線認識までは普通に直進
		IOManager->Forward(pid.BasePower);
		break;

	// 初回左ブロック旋回中
	case FirstTurnLeftPlace:
		// 左ブロック方向を向いたら、左ブロックまで直進中に遷移
		if(abs(currentAngle - LEFT_ANGLE) < 5){
			CurrentState = ForwardLeftPlace;
			goto ACTION;
		}

		IOManager->OutputData.LeftMotorPower = -1 * 0.25 * TURN_SPEED;
		IOManager->OutputData.RightMotorPower = TURN_SPEED;
		break;

		// 左ブロックまで直進
	case ForwardLeftPlace:
		// 超音波センサでブロックを認識した場合には、色認識に移行
		if (IOManager->InputData.SonarDistance <= BLOCK_DISTANCE) {
			CurrentState = DetectLeftBlock;
			// ブロック位置に到達したので、座標を修正
			SpManager->ResetY(2790);
			IOManager->Stop();
			break;
		}

		// ラインの右側をトレースしながらブロックに接近
		IOManager->LineTraceAction(pid, EDGE_LINE, false);

		// ライントレース中なので、角度は常にライン沿い
		SpManager->ResetAngle(LEFT_ANGLE);
		break;

	// 左ブロック色認識
	case DetectLeftBlock:
		// アームを上昇させて、色認識種別をブロックに変更
		IOManager->UpARMMotor();
		IOManager->HSLTargetType = BlockColor;

		// 色が一致している場合には、カウントを進める
		if (DetectColor == PrevColor && DetectColor != HSLBlack) {
			ColorDetectCount++;
			if (ColorDetectCount > 5) {
				ColorDetectCount = 0;
				ColorChangeCount = 0;
				// 色認識が完了したため、アームを下降させる
				IOManager->DownARMMotor();
				// フィールドの色と土俵の色が一致した場合、寄り切り
				if (ArenaArray[CurrentArena].LeftPlaceColor == DetectColor) {
					CurrentState = YORIKIRILeft;
				} else {
					// フィールドの色と土俵の色が異なる場合、押し出し
					CurrentState = OSHIDASHILeft;
				}
				break;
			}
		} else {
			PrevColor = DetectColor;
			ColorChangeCount++;

			// 色の変更を繰り返す場合には、強制的に次の認識色とする
			if(ColorChangeCount > 50) {
				ColorDetectCount = 11;
			} else {
				ColorDetectCount = 0;
			}
		}
		break;

	// 左ブロックを寄り切り
	case YORIKIRILeft:
		// ある程度旋回してから、黒線上に乗ったら右ブロックへの直進状態に移行
		if (IOManager->InputData.ReflectLight < EDGE_LINE &&
			abs(currentAngle - RIGHT_ANGLE) < 45) {
			CurrentState = ForwardRightPlace;
			goto ACTION;
		} else if (abs(currentAngle - RIGHT_ANGLE) < 25) {
			// 右ブロック方向を向くまで旋回
			IOManager->TurnCW(TURN_SPEED);
		} else {
			// 右ブロック方向を向くまで旋回（離れているため高速
			IOManager->TurnCW(FIRST_TURN_SPEED);
		}
		break;

	// 左ブロックを押し出し
	case OSHIDASHILeft:
		// 一定距離進んだら後退
		if(currentPoint.Y < 2750) {
			CurrentState = OSHIDASHILeftBack;
			IOManager->UpARMMotor();
			IOManager->DownARMMotor();
			goto ACTION;
		}
		IOManager->Forward(OSHIDASHI_SPEED);
		break;
	case OSHIDASHILeftBack:
		// 一定距離後退したら、以降は寄り切りと一緒
		if(currentPoint.Y > 2775){
			CurrentState = YORIKIRILeft;
			goto ACTION;
		}
		IOManager->Back(pid.BasePower);
		break;
	/// 右ブロックまで前進
	case ForwardRightPlace:
		// 超音波センサでブロックを認識した場合には、色認識に移行
		if (IOManager->InputData.SonarDistance <= BLOCK_DISTANCE) {
			CurrentState = DetectRightBlock;
			// 右ブロックを検知したため、座標を修正
			SpManager->ResetY(3050);
			IOManager->Stop();
			break;
		}

		// ラインに沿って右ブロック置き場に接近
		IOManager->LineTraceAction(pid, EDGE_LINE, true);
		// ライントレース中なので常に角度はライン沿い
		SpManager->ResetAngle(RIGHT_ANGLE);

		break;
	// 右ブロック色認識
	case DetectRightBlock:
		// アームを上昇させて、色認識種別をブロックに変更
		IOManager->UpARMMotor();
		IOManager->HSLTargetType = BlockColor;

		// 色が一致している場合には、カウントを進める
		if (DetectColor == PrevColor && DetectColor != HSLBlack) {
			ColorDetectCount++;
			if (ColorDetectCount > 5) {
				ColorDetectCount = 0;
				ColorChangeCount = 0;
				// 色認識が完了したため、アームを下降させる
				IOManager->DownARMMotor();
				// フィールドの色と土俵の色が一致した場合、寄り切り
				if (ArenaArray[CurrentArena].RightPlaceColor == DetectColor) {
					CurrentState = YORIKIRIRight;
				} else {
					// フィールドの色と土俵の色が異なる場合、押し出し
					CurrentState = OSHIDASHIRight;
				}
				break;
			}
		} else {
			// 色が異なった場合には再度カウント
			PrevColor = DetectColor;
			ColorChangeCount++;

			// 色の変更を繰り返す場合には、強制的に次の認識色とする
			if(ColorChangeCount > 50) {
				ColorDetectCount = 11;
			} else {
				ColorDetectCount = 0;
			}
			break;
		}
		break;

	// 右ブロックを寄り切り
	case YORIKIRIRight:
		// 斜め方向を向いたらフィールド走行状態に遷移
		if (abs(currentAngle - (LEFT_ANGLE)) < 15) {
			CurrentState = ForwardCenterFromRight;
			goto ACTION;
		} else if(abs(currentAngle - (LEFT_ANGLE)) < 35) {
			// 中央方向を向くまで旋回
			IOManager->TurnCCW(TURN_SPEED);
		} else {
			// 中央方向を向くまで旋回 (離れているので高速)
			IOManager->TurnCCW(FIRST_TURN_SPEED);
		}
		break;

	// 右ブロックを押し出し
	case OSHIDASHIRight:
		// 一定距離進んだら後退
		if(currentPoint.Y > 3090) {
			IOManager->UpARMMotor();
			CurrentState = OSHIDASHIRightBack;
			IOManager->DownARMMotor();
			goto ACTION;
		}
		IOManager->Forward(OSHIDASHI_SPEED);
		break;
	case OSHIDASHIRightBack:
		// 一定距離後退したら、以降は寄り切りと一緒
		if(currentPoint.Y < 3070){

			CurrentState = YORIKIRIRight;
			goto ACTION;
		}
		IOManager->Back(pid.BasePower);
		break;

	// 中央方向へ前進
	case ForwardCenterFromRight:
		// 黒線認識したら、前方旋回中状態に遷移
		if (IOManager->InputData.ReflectLight < ONLINE) {
			// 最後の土俵の場合には、懸賞運搬戦略に遷移
			if(CurrentArena == 3) {
				// 座標をクリア
				SpManager->ResetX(2470);
				SpManager->ResetY(2900);
				SpManager->ResetAngle(LEFT_ANGLE);

				IOManager->Stop();
				IOManager->WriteOutputMotor();
			    dly_tsk(100);

				Manager->SetStrategy(new PrizeStrategy(Manager));
				break;
			}
			CurrentState = TurnForward;
			SpManager->ResetAngle(LEFT_ANGLE);
			break;
		}
		IOManager->LineTraceAction(pid, EDGE_LINE, false);
		break;

	case TurnForward:
		// 黒線上に乗ったら一枚の土俵攻略が終了
//		if (currentAngle > 305 && currentAngle < 355) {
		if (currentAngle < 6 || currentAngle > 350) {
			CurrentArena++;

			// 2枚目の攻略が完了した場合には、線路をまたぐ直進処理に遷移
			if(CurrentArena == 2) {
				SpManager->Distance = 0;
				CurrentState = ForwardRail;
				// 座標修正
				SpManager->ResetX(1920);
				goto ACTION;
			} else {
				// 2枚目でなければ、通常の処理に遷移
				CurrentState = FirstOnArena;
				goto ACTION;
			}
			break;
		}

		// 正面を向くまで旋回
		IOManager->OutputData.LeftMotorPower = TURN_SPEED;
		IOManager->OutputData.RightMotorPower =  -1 * 0.5 * TURN_SPEED;

		break;

	case ForwardRail:
		if(currentPoint.X > 2120) {
			// 線路を跨いだので、通常のライントレースに遷移
			CurrentState = FirstOnArena;
			goto ACTION;
		}

		// 最初はライントレース
		if(SpManager->Distance < 90) {
			IOManager->LineTraceAction(pid, EDGE_LINE, false);
		} else if(SpManager->Distance < 130){
			IOManager->Forward(25);
		} else {
			IOManager->LineTraceAction(pid, EDGE_LINE, false);
		}

		break;
	default:
		break;
	}
}<|endoftext|>


<commit_before><commit_msg>A quick fix for Issue 16597. Our autofill code handles keyboard events by itself and it prevents dispatch a return key to WebKit when the key is comsumed by the autofill. Unfortunately, this code is enclosed with "#if defined(OS_WIN)" and "#endif". This change just activates this code on Linux.<commit_after><|endoftext|>


<commit_before><commit_msg>This CL fixes "RTL: Form autofill pop-up is not right aligned".<commit_after><|endoftext|>