<commit_before>/* primitives.tcc                                 -*- C++ -*-
   Rémi Attab (remi.attab@gmail.com), 19 Apr 2014
   FreeBSD-style copyright and disclaimer apply

   Reflection utilities for primitives.
*/

#pragma once

#include "reflect.h"
#include "reflect/basics.h"
#include "reflect/plumbing.h"

#include <limits>

namespace reflect {

/******************************************************************************/
/* REFLECT LIMIT                                                              */
/******************************************************************************/

#define reflectLimit(name) \
    type_->add(#name, [] { return std::numeric_limits<T_>::name(); });

/******************************************************************************/
/* REFLECT NUMBER                                                             */
/******************************************************************************/

template<typename T_>
void reflectNumberImpl(Type* type_)
{
    reflectPlumbing();

    reflectLimit(min);
    reflectLimit(max);

    reflectTrait(primitive);

    if (std::numeric_limits<T_>::is_integer) {
        reflectTrait(integer);

        if (std::numeric_limits<T_>::is_signed)
            reflectTrait(signed);
        else reflectTrait(unsigned);
    }

    else reflectTrait(float);
}

#define reflectNumber(num) \
    reflectClassImpl(num) { reflectNumberImpl<T_>(type_); }

} // reflect
<commit_msg>Added bool traits.<commit_after>/* primitives.tcc                                 -*- C++ -*-
   Rémi Attab (remi.attab@gmail.com), 19 Apr 2014
   FreeBSD-style copyright and disclaimer apply

   Reflection utilities for primitives.
*/

#pragma once

#include "reflect.h"
#include "reflect/basics.h"
#include "reflect/plumbing.h"

#include <limits>

namespace reflect {

/******************************************************************************/
/* REFLECT LIMIT                                                              */
/******************************************************************************/

#define reflectLimit(name) \
    type_->add(#name, [] { return std::numeric_limits<T_>::name(); });

/******************************************************************************/
/* REFLECT NUMBER                                                             */
/******************************************************************************/

template<typename T_>
void reflectNumberImpl(Type* type_)
{
    reflectPlumbing();

    reflectLimit(min);
    reflectLimit(max);

    reflectTrait(primitive);

    if (std::is_same<T_, bool>::value)
        reflectTrait(bool);

    else if (std::numeric_limits<T_>::is_integer) {
        reflectTrait(integer);

        if (std::numeric_limits<T_>::is_signed)
            reflectTrait(signed);
        else reflectTrait(unsigned);
    }

    else reflectTrait(float);
}

#define reflectNumber(num) \
    reflectClassImpl(num) { reflectNumberImpl<T_>(type_); }

} // reflect
<|endoftext|>


<commit_before>#include <v8.h>
#include <node.h>
#include <objc/objc.h>
#include <objc/message.h>
#include <objc/runtime.h>
#include <ffi/ffi.h>
#include "objc.h"
#include "helpers.h"

// Debug
#import <Foundation/Foundation.h>
#include <stdio.h>

using namespace node;
using namespace v8;

namespace node_objc {

  v8::Handle<Value> node_objc_getClass (const Arguments& args) {
    HandleScope scope;
    String::Utf8Value classStr(args[0]->ToString());
    // get the requested Class
    Class c = objc_getClass(*classStr);
    // if null was returned, then return JavaScript null
    if (!c) {
      return Null();
    }
    return scope.Close(WrapId(c));
  }

  // For debugging libffi...
  id fake_msgSend (id ref, SEL sel, ...) {
    int j;
    va_list ap;
    va_start(ap, sel); //Requires the last fixed parameter (to get the address)
    for(j=0; j<1; j++) {
      const char * param = va_arg(ap, const char *); //Requires the type to cast to. Increments ap to the next argument.
      NSLog(@"string: %s", param);
    }
    va_end(ap);
    return ref;
  }

  v8::Handle<Value> node_objc_msgSend (const Arguments& args) {
    HandleScope scope;

    ffi_cif cif;
    int argv = args.Length();
    ffi_type  **arg_types;
    void      **arg_values;
    ffi_status status;
    id result;

    arg_types  = (ffi_type **) malloc(argv*sizeof(ffi_type *));
    arg_values = (void **) malloc(argv*sizeof(void *));

    arg_types[0] = &ffi_type_pointer;
    arg_types[1] = &ffi_type_pointer;

    id ref = UnwrapId(args[0]->ToObject());
    SEL sel = UnwrapSel(args[1]->ToObject());
    arg_values[0] = &ref;
    arg_values[1] = &sel;

    Local<Value> val;
    for (int i=2; i < argv; i++) {
      val = args[i];
      arg_types[i] = &ffi_type_pointer;
      if (val->IsString()) {
        String::Utf8Value strVal(val->ToObject());
        const char * cStrVal = *strVal;
        arg_values[i] = &cStrVal;
      } else {

      }
    }

    if ((status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argv, &ffi_type_pointer, arg_types)) != FFI_OK) {
      return v8::ThrowException(v8::Exception::Error(v8::String::New("`ffi_prep_cif` failed!")));
    }

    @try {
      ffi_call(&cif, FFI_FN(objc_msgSend), &result, arg_values);
    }
    @catch (NSException *e) {
      return v8::ThrowException(NSExceptionToV8Error(e));
    }

    //NSLog(@"Length: %d", [result length]);

    v8::Handle<Object> wrap = WrapId(result);

    free(arg_types);
    free(arg_values);
    return scope.Close(wrap);
  }

  v8::Handle<Value> node_sel_registerName (const Arguments& args) {
    HandleScope scope;
    String::Utf8Value selStr(args[0]->ToString());
    SEL sel = sel_registerName(*selStr);
    if (!sel) {
      return Null();
    }
    return scope.Close(WrapSel(sel));
  }

  v8::Handle<Value> node_NSLog (const Arguments& args) {
    HandleScope scope;

    id ref = UnwrapId(args[0]->ToObject());
    NSLog(@"%@", ref);
    return Undefined();
  }

  // INIT function
  void objcInit (v8::Handle<v8::Object> target) {
    HandleScope scope;
    NODE_SET_METHOD(target, "objc_getClass", node_objc_getClass);
    NODE_SET_METHOD(target, "objc_msgSend", node_objc_msgSend);
    NODE_SET_METHOD(target, "sel_registerName", node_sel_registerName);
    NODE_SET_METHOD(target, "NSLog", node_NSLog);
  }

} // namespace node_objc
<commit_msg>Pass 'id' values properly as arguments<commit_after>#include <v8.h>
#include <node.h>
#include <objc/objc.h>
#include <objc/message.h>
#include <objc/runtime.h>
#include <ffi/ffi.h>
#include "objc.h"
#include "helpers.h"

// Debug
#import <Foundation/Foundation.h>
#include <stdio.h>

using namespace node;
using namespace v8;

namespace node_objc {

  v8::Handle<Value> node_objc_getClass (const Arguments& args) {
    HandleScope scope;
    String::Utf8Value classStr(args[0]->ToString());
    // get the requested Class
    Class c = objc_getClass(*classStr);
    // if null was returned, then return JavaScript null
    if (!c) {
      return Null();
    }
    return scope.Close(WrapId(c));
  }

  // For debugging libffi...
  id fake_msgSend (id ref, SEL sel, ...) {
    int j;
    va_list ap;
    va_start(ap, sel); //Requires the last fixed parameter (to get the address)
    for(j=0; j<1; j++) {
      const char * param = va_arg(ap, const char *); //Requires the type to cast to. Increments ap to the next argument.
      NSLog(@"string: %s", param);
    }
    va_end(ap);
    return ref;
  }

  v8::Handle<Value> node_objc_msgSend (const Arguments& args) {
    HandleScope scope;

    ffi_cif cif;
    int argv = args.Length();
    ffi_type  **arg_types;
    void      **arg_values;
    ffi_status status;
    id result;

    arg_types  = (ffi_type **) malloc(argv*sizeof(ffi_type *));
    arg_values = (void **) malloc(argv*sizeof(void *));

    arg_types[0] = &ffi_type_pointer;
    arg_types[1] = &ffi_type_pointer;

    id ref = UnwrapId(args[0]->ToObject());
    SEL sel = UnwrapSel(args[1]->ToObject());
    arg_values[0] = &ref;
    arg_values[1] = &sel;

    Local<Value> val;
    for (int i=2; i < argv; i++) {
      val = args[i];
      arg_types[i] = &ffi_type_pointer;
      if (val->IsString()) {
        String::Utf8Value strVal(val->ToObject());
        const char * cStrVal = *strVal;
        arg_values[i] = &cStrVal;
      } else {
        id val = UnwrapId(args[i]->ToObject());
        arg_values[i] = &val;
      }
    }

    if ((status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argv, &ffi_type_pointer, arg_types)) != FFI_OK) {
      return v8::ThrowException(v8::Exception::Error(v8::String::New("`ffi_prep_cif` failed!")));
    }

    @try {
      ffi_call(&cif, FFI_FN(objc_msgSend), &result, arg_values);
    }
    @catch (NSException *e) {
      return v8::ThrowException(NSExceptionToV8Error(e));
    }

    //NSLog(@"Length: %d", [result length]);

    v8::Handle<Object> wrap = WrapId(result);

    free(arg_types);
    free(arg_values);
    return scope.Close(wrap);
  }

  v8::Handle<Value> node_sel_registerName (const Arguments& args) {
    HandleScope scope;
    String::Utf8Value selStr(args[0]->ToString());
    SEL sel = sel_registerName(*selStr);
    if (!sel) {
      return Null();
    }
    return scope.Close(WrapSel(sel));
  }

  v8::Handle<Value> node_NSLog (const Arguments& args) {
    HandleScope scope;

    id ref = UnwrapId(args[0]->ToObject());
    NSLog(@"%@", ref);
    return Undefined();
  }

  // INIT function
  void objcInit (v8::Handle<v8::Object> target) {
    HandleScope scope;
    NODE_SET_METHOD(target, "objc_getClass", node_objc_getClass);
    NODE_SET_METHOD(target, "objc_msgSend", node_objc_msgSend);
    NODE_SET_METHOD(target, "sel_registerName", node_sel_registerName);
    NODE_SET_METHOD(target, "NSLog", node_NSLog);
  }

} // namespace node_objc
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include "chainparamsbase.h"

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
	return CalculateNextWorkRequired(pindexLast, params);
}
// SYSCOIN DGW diff algo
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, const Consensus::Params& params)
{

	/* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dashpay.io */
    // Genesis block

	const arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit);
    if (pindexLast == NULL)
        return nProofOfWorkLimit.GetCompact();
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;
    const CBlockIndex *BlockLastSolved = pindexLast;
    const CBlockIndex *BlockReading = pindexLast;
    int64_t nActualTimespan = 0;
    int64_t LastBlockTime = 0;
    int64_t PastBlocksMin = 24;
    int64_t PastBlocksMax = 24;
    int64_t CountBlocks = 0;
    arith_uint256 PastDifficultyAverage;
    arith_uint256 PastDifficultyAveragePrev;

    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) {
        return nProofOfWorkLimit.GetCompact();
    }

    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
        CountBlocks++;

        if(CountBlocks <= PastBlocksMin) {
            if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
            else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1); }
            PastDifficultyAveragePrev = PastDifficultyAverage;
        }

        if(LastBlockTime > 0){
            int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());
            nActualTimespan += Diff;
        }
        LastBlockTime = BlockReading->GetBlockTime();

        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
        BlockReading = BlockReading->pprev;
    }

    arith_uint256 bnNew(PastDifficultyAverage);

    int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing;

    if (nActualTimespan < _nTargetTimespan/3)
        nActualTimespan = _nTargetTimespan/3;
    if (nActualTimespan > _nTargetTimespan*3)
        nActualTimespan = _nTargetTimespan*3;

    // Retarget
    bnNew *= nActualTimespan;
    bnNew /= _nTargetTimespan;

    if (bnNew > nProofOfWorkLimit){
        bnNew = nProofOfWorkLimit;
    }

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
        return error("CheckProofOfWork(): nBits below minimum work");

    // Check proof of work matches claimed amount
	std::string chain = ChainNameFromCommandLine();
    if (UintToArith256(hash) > bnTarget)
        return error("CheckProofOfWork(): hash doesn't match nBits");

    return true;
}

arith_uint256 GetBlockProof(const CBlockIndex& block)
{
    arith_uint256 bnTarget;
    bool fNegative;
    bool fOverflow;
    bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
    if (fNegative || fOverflow || bnTarget == 0)
        return 0;
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for a arith_uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (nTarget+1) + 1.
    return (~bnTarget / (bnTarget + 1)) + 1;
}

int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
    arith_uint256 r;
    int sign = 1;
    if (to.nChainWork > from.nChainWork) {
        r = to.nChainWork - from.nChainWork;
    } else {
        r = from.nChainWork - to.nChainWork;
        sign = -1;
    }
    r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
    if (r.bits() > 63) {
        return sign * std::numeric_limits<int64_t>::max();
    }
    return sign * r.GetLow64();
}
<commit_msg>typo<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include "chainparamsbase.h"

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
	return CalculateNextWorkRequired(pindexLast, params);
}
// SYSCOIN DGW diff algo
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{

	/* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dashpay.io */
    // Genesis block

	const arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit);
    if (pindexLast == NULL)
        return nProofOfWorkLimit.GetCompact();
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;
    const CBlockIndex *BlockLastSolved = pindexLast;
    const CBlockIndex *BlockReading = pindexLast;
    int64_t nActualTimespan = 0;
    int64_t LastBlockTime = 0;
    int64_t PastBlocksMin = 24;
    int64_t PastBlocksMax = 24;
    int64_t CountBlocks = 0;
    arith_uint256 PastDifficultyAverage;
    arith_uint256 PastDifficultyAveragePrev;

    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) {
        return nProofOfWorkLimit.GetCompact();
    }

    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
        CountBlocks++;

        if(CountBlocks <= PastBlocksMin) {
            if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
            else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1); }
            PastDifficultyAveragePrev = PastDifficultyAverage;
        }

        if(LastBlockTime > 0){
            int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());
            nActualTimespan += Diff;
        }
        LastBlockTime = BlockReading->GetBlockTime();

        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
        BlockReading = BlockReading->pprev;
    }

    arith_uint256 bnNew(PastDifficultyAverage);

    int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing;

    if (nActualTimespan < _nTargetTimespan/3)
        nActualTimespan = _nTargetTimespan/3;
    if (nActualTimespan > _nTargetTimespan*3)
        nActualTimespan = _nTargetTimespan*3;

    // Retarget
    bnNew *= nActualTimespan;
    bnNew /= _nTargetTimespan;

    if (bnNew > nProofOfWorkLimit){
        bnNew = nProofOfWorkLimit;
    }

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
        return error("CheckProofOfWork(): nBits below minimum work");

    // Check proof of work matches claimed amount
	std::string chain = ChainNameFromCommandLine();
    if (UintToArith256(hash) > bnTarget)
        return error("CheckProofOfWork(): hash doesn't match nBits");

    return true;
}

arith_uint256 GetBlockProof(const CBlockIndex& block)
{
    arith_uint256 bnTarget;
    bool fNegative;
    bool fOverflow;
    bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
    if (fNegative || fOverflow || bnTarget == 0)
        return 0;
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for a arith_uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (nTarget+1) + 1.
    return (~bnTarget / (bnTarget + 1)) + 1;
}

int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
    arith_uint256 r;
    int sign = 1;
    if (to.nChainWork > from.nChainWork) {
        r = to.nChainWork - from.nChainWork;
    } else {
        r = from.nChainWork - to.nChainWork;
        sign = -1;
    }
    r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
    if (r.bits() > 63) {
        return sign * std::numeric_limits<int64_t>::max();
    }
    return sign * r.GetLow64();
}
<|endoftext|>


<commit_before>/*
 * ============================================================================
 *
 *       Filename:  qcpp.hh
 *    Description:  Global header to include all subheaders
 *        License:  GPLv3+
 *         Author:  Kevin Murray, spam@kdmurray.id.au
 *
 * ============================================================================
 */

#ifndef QCPP_HH
#define QCPP_HH

#include "qc-config.hh"
#include "qc-io.hh"
#include "qc-processor.hh"
#include "qc-length.hh"

#endif /* QCPP_HH */
<commit_msg>Add qc-gbs to catch-all header<commit_after>/*
 * ============================================================================
 *
 *       Filename:  qcpp.hh
 *    Description:  Global header to include all subheaders
 *        License:  GPLv3+
 *         Author:  Kevin Murray, spam@kdmurray.id.au
 *
 * ============================================================================
 */

#ifndef QCPP_HH
#define QCPP_HH

#include "qc-config.hh"
#include "qc-io.hh"
#include "qc-gbs.hh"
#include "qc-processor.hh"
#include "qc-length.hh"

#endif /* QCPP_HH */
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkStructuredGrid.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkStructuredGrid.hh"
#include "vtkVertex.hh"
#include "vtkLine.hh"
#include "vtkQuad.hh"
#include "vtkHexahedron.hh"

vtkStructuredGrid::vtkStructuredGrid()
{
  this->Dimensions[0] = 1;
  this->Dimensions[1] = 1;
  this->Dimensions[2] = 1;
  this->DataDescription = VTK_SINGLE_POINT;

  this->Blanking = 0;
  this->PointVisibility = NULL;
}

vtkStructuredGrid::vtkStructuredGrid(const vtkStructuredGrid& sg) :
vtkPointSet(sg)
{
  this->Dimensions[0] = sg.Dimensions[0];
  this->Dimensions[1] = sg.Dimensions[1];
  this->Dimensions[2] = sg.Dimensions[2];
  this->DataDescription = sg.DataDescription;

  this->Blanking = sg.Blanking;
  if ( sg.PointVisibility != NULL )
    {
    this->PointVisibility->UnRegister((vtkObject *)this);
    this->PointVisibility = sg.PointVisibility;
    this->PointVisibility->Register((vtkObject *)this);
    }
  else
    {
    this->PointVisibility = NULL;
    }
}

vtkStructuredGrid::~vtkStructuredGrid()
{
  this->Initialize();
  if (this->PointVisibility)
    {
    this->PointVisibility->UnRegister((vtkObject *)this);
    }
  this->PointVisibility = NULL;
}

// Description:
// Copy the geometric and topological structure of an input structured grid.
void vtkStructuredGrid::CopyStructure(vtkDataSet *ds)
{
  vtkStructuredGrid *sg=(vtkStructuredGrid *)ds;
  vtkPointSet::CopyStructure(ds);

  for (int i=0; i<3; i++)
    {
    this->Dimensions[i] = sg->Dimensions[i];
    }
  this->DataDescription = sg->DataDescription;

  this->Blanking = sg->Blanking;
  if ( sg->PointVisibility != NULL &&
  sg->PointVisibility != this->PointVisibility )
    {
    if ( this->PointVisibility )
      {
      this->PointVisibility->UnRegister((vtkObject *)this);
      }
    this->PointVisibility = sg->PointVisibility;
    this->PointVisibility->Register((vtkObject *)this);
    }
}

void vtkStructuredGrid::Initialize()
{
  vtkPointSet::Initialize();
  if ( this->PointVisibility )
    this->PointVisibility->UnRegister(this);
  this->PointVisibility = NULL;
  this->Blanking = 0;
}

int vtkStructuredGrid::GetCellType(int vtkNotUsed(cellId))
{
  switch (this->DataDescription)
    {
    case VTK_SINGLE_POINT:
      return VTK_VERTEX;

    case VTK_X_LINE: case VTK_Y_LINE: case VTK_Z_LINE:
      return VTK_LINE;

    case VTK_XY_PLANE: case VTK_YZ_PLANE: case VTK_XZ_PLANE:
      return VTK_QUAD;

    case VTK_XYZ_GRID:
      return VTK_HEXAHEDRON;

    default:
      vtkErrorMacro(<<"Bad data description!");
      return VTK_NULL_ELEMENT;
    }
}

vtkCell *vtkStructuredGrid::GetCell(int cellId)
{
  static vtkVertex vertex;
  static vtkLine line;
  static vtkQuad quad;
  static vtkHexahedron hexa;
  static vtkCell *cell;
  int idx;
  int i, j, k;
  int d01, offset1, offset2;

  // Make sure data is defined
  if ( ! this->Points )
    {
    vtkErrorMacro (<<"No data");
    return NULL;
    }

  switch (this->DataDescription)
    {
    case VTK_SINGLE_POINT: // cellId can only be = 0
      cell = &vertex;
      cell->PointIds.InsertId(0,0);
      break;

    case VTK_X_LINE:
      cell = &line;
      cell->PointIds.InsertId(0,cellId);
      cell->PointIds.InsertId(1,cellId+1);
      break;

    case VTK_Y_LINE:
      cell = &line;
      cell->PointIds.InsertId(0,cellId);
      cell->PointIds.InsertId(1,cellId+1);
      break;

    case VTK_Z_LINE:
      cell = &line;
      cell->PointIds.InsertId(0,cellId);
      cell->PointIds.InsertId(1,cellId+1);
      break;

    case VTK_XY_PLANE:
      cell = &quad;
      i = cellId % (this->Dimensions[0]-1);
      j = cellId / (this->Dimensions[0]-1);
      idx = i + j*this->Dimensions[0];
      offset1 = 1;
      offset2 = this->Dimensions[0];

      cell->PointIds.InsertId(0,idx);
      cell->PointIds.InsertId(1,idx+offset1);
      cell->PointIds.InsertId(2,idx+offset1+offset2);
      cell->PointIds.InsertId(3,idx+offset2);
      break;

    case VTK_YZ_PLANE:
      cell = &quad;
      j = cellId % (this->Dimensions[1]-1);
      k = cellId / (this->Dimensions[1]-1);
      idx = j + k*this->Dimensions[1];
      offset1 = 1;
      offset2 = this->Dimensions[1];

      cell->PointIds.InsertId(0,idx);
      cell->PointIds.InsertId(1,idx+offset1);
      cell->PointIds.InsertId(2,idx+offset1+offset2);
      cell->PointIds.InsertId(3,idx+offset2);
      break;

    case VTK_XZ_PLANE:
      cell = &quad;
      i = cellId % (this->Dimensions[0]-1);
      k = cellId / (this->Dimensions[0]-1);
      idx = i + k*this->Dimensions[0];
      offset1 = 1;
      offset2 = this->Dimensions[0];

      cell->PointIds.InsertId(0,idx);
      cell->PointIds.InsertId(1,idx+offset1);
      cell->PointIds.InsertId(2,idx+offset1+offset2);
      cell->PointIds.InsertId(3,idx+offset2);
      break;

    case VTK_XYZ_GRID:
      cell = &hexa;
      d01 = this->Dimensions[0]*this->Dimensions[1];
      i = cellId % (this->Dimensions[0] - 1);
      j = (cellId / (this->Dimensions[0] - 1)) % (this->Dimensions[1] - 1);
      k = cellId / ((this->Dimensions[0] - 1) * (this->Dimensions[1] - 1));
      idx = i+ j*this->Dimensions[0] + k*d01;
      offset1 = 1;
      offset2 = this->Dimensions[0];

      cell->PointIds.InsertId(0,idx);
      cell->PointIds.InsertId(1,idx+offset1);
      cell->PointIds.InsertId(2,idx+offset1+offset2);
      cell->PointIds.InsertId(3,idx+offset2);
      idx += d01;
      cell->PointIds.InsertId(4,idx);
      cell->PointIds.InsertId(5,idx+offset1);
      cell->PointIds.InsertId(6,idx+offset1+offset2);
      cell->PointIds.InsertId(7,idx+offset2);
      break;
    }

  // Extract point coordinates and point ids. NOTE: the ordering of the VlQuad
  // and vtkHexahedron cells are tricky.
  for (i=0; i<cell->PointIds.GetNumberOfIds(); i++)
    {
    idx = cell->PointIds.GetId(i);
    cell->Points.InsertPoint(i,this->Points->GetPoint(idx));
    }

  return cell;
}

// Description:
// Turn on data blanking. Data blanking is the ability to turn off
// portions of the grid when displaying or operating on it. Some data
// (like finite difference data) routinely turns off data to simulate
// solid obstacles.
void vtkStructuredGrid::BlankingOn()
{
  if (!this->Blanking)
    {
    this->Blanking = 1;
    this->Modified();

    if ( !this->PointVisibility )
      {
      this->AllocatePointVisibility();
      }
    }
}

void vtkStructuredGrid::AllocatePointVisibility()
{
  if ( !this->PointVisibility )
    {
    this->PointVisibility =
      new vtkBitScalars(this->GetNumberOfPoints(),1000);
    this->PointVisibility->Register((vtkObject *)this);
    for (int i=0; i<this->GetNumberOfPoints(); i++)
      {
      this->PointVisibility->InsertScalar(i,1);
      }
    this->PointVisibility->Delete();
    }
}

// Description:
// Turn off data blanking.
void vtkStructuredGrid::BlankingOff()
{
  if (this->Blanking)
    {
    this->Blanking = 0;
    this->Modified();
    }
}

// Description:
// Turn off a particular data point.
void vtkStructuredGrid::BlankPoint(int ptId)
{
  if ( !this->PointVisibility ) this->AllocatePointVisibility();
  this->PointVisibility->InsertScalar(ptId,0);
}

// Description:
// Turn on a particular data point.
void vtkStructuredGrid::UnBlankPoint(int ptId)
{
  if ( !this->PointVisibility ) this->AllocatePointVisibility();
  this->PointVisibility->InsertScalar(ptId,1);
}

// Description:
// Set dimensions of structured grid dataset.
void vtkStructuredGrid::SetDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;
  this->SetDimensions(dim);
}

// Description:
// Set dimensions of structured grid dataset.
void vtkStructuredGrid::SetDimensions(int dim[3])
{
  int returnStatus=this->StructuredData.SetDimensions(dim,this->Dimensions);

  if ( returnStatus > -1 )
    {
    this->DataDescription = returnStatus;
    this->Modified();
    }
}

void vtkStructuredGrid::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPointSet::PrintSelf(os,indent);

  os << indent << "Dimensions: (" << this->Dimensions[0] << ", "
                                  << this->Dimensions[1] << ", "
                                  << this->Dimensions[2] << ")\n";

  os << indent << "Blanking: " << (this->Blanking ? "On\n" : "Off\n");
}

<commit_msg>PERF: Removed NumberOfIds method call from for loop test.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkStructuredGrid.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkStructuredGrid.hh"
#include "vtkVertex.hh"
#include "vtkLine.hh"
#include "vtkQuad.hh"
#include "vtkHexahedron.hh"

vtkStructuredGrid::vtkStructuredGrid()
{
  this->Dimensions[0] = 1;
  this->Dimensions[1] = 1;
  this->Dimensions[2] = 1;
  this->DataDescription = VTK_SINGLE_POINT;

  this->Blanking = 0;
  this->PointVisibility = NULL;
}

vtkStructuredGrid::vtkStructuredGrid(const vtkStructuredGrid& sg) :
vtkPointSet(sg)
{
  this->Dimensions[0] = sg.Dimensions[0];
  this->Dimensions[1] = sg.Dimensions[1];
  this->Dimensions[2] = sg.Dimensions[2];
  this->DataDescription = sg.DataDescription;

  this->Blanking = sg.Blanking;
  if ( sg.PointVisibility != NULL )
    {
    this->PointVisibility->UnRegister((vtkObject *)this);
    this->PointVisibility = sg.PointVisibility;
    this->PointVisibility->Register((vtkObject *)this);
    }
  else
    {
    this->PointVisibility = NULL;
    }
}

vtkStructuredGrid::~vtkStructuredGrid()
{
  this->Initialize();
  if (this->PointVisibility)
    {
    this->PointVisibility->UnRegister((vtkObject *)this);
    }
  this->PointVisibility = NULL;
}

// Description:
// Copy the geometric and topological structure of an input structured grid.
void vtkStructuredGrid::CopyStructure(vtkDataSet *ds)
{
  vtkStructuredGrid *sg=(vtkStructuredGrid *)ds;
  vtkPointSet::CopyStructure(ds);

  for (int i=0; i<3; i++)
    {
    this->Dimensions[i] = sg->Dimensions[i];
    }
  this->DataDescription = sg->DataDescription;

  this->Blanking = sg->Blanking;
  if ( sg->PointVisibility != NULL &&
  sg->PointVisibility != this->PointVisibility )
    {
    if ( this->PointVisibility )
      {
      this->PointVisibility->UnRegister((vtkObject *)this);
      }
    this->PointVisibility = sg->PointVisibility;
    this->PointVisibility->Register((vtkObject *)this);
    }
}

void vtkStructuredGrid::Initialize()
{
  vtkPointSet::Initialize();
  if ( this->PointVisibility )
    this->PointVisibility->UnRegister(this);
  this->PointVisibility = NULL;
  this->Blanking = 0;
}

int vtkStructuredGrid::GetCellType(int vtkNotUsed(cellId))
{
  switch (this->DataDescription)
    {
    case VTK_SINGLE_POINT:
      return VTK_VERTEX;

    case VTK_X_LINE: case VTK_Y_LINE: case VTK_Z_LINE:
      return VTK_LINE;

    case VTK_XY_PLANE: case VTK_YZ_PLANE: case VTK_XZ_PLANE:
      return VTK_QUAD;

    case VTK_XYZ_GRID:
      return VTK_HEXAHEDRON;

    default:
      vtkErrorMacro(<<"Bad data description!");
      return VTK_NULL_ELEMENT;
    }
}

vtkCell *vtkStructuredGrid::GetCell(int cellId)
{
  static vtkVertex vertex;
  static vtkLine line;
  static vtkQuad quad;
  static vtkHexahedron hexa;
  static vtkCell *cell;
  int idx;
  int i, j, k;
  int d01, offset1, offset2;

  // Make sure data is defined
  if ( ! this->Points )
    {
    vtkErrorMacro (<<"No data");
    return NULL;
    }

  switch (this->DataDescription)
    {
    case VTK_SINGLE_POINT: // cellId can only be = 0
      cell = &vertex;
      cell->PointIds.InsertId(0,0);
      break;

    case VTK_X_LINE:
      cell = &line;
      cell->PointIds.InsertId(0,cellId);
      cell->PointIds.InsertId(1,cellId+1);
      break;

    case VTK_Y_LINE:
      cell = &line;
      cell->PointIds.InsertId(0,cellId);
      cell->PointIds.InsertId(1,cellId+1);
      break;

    case VTK_Z_LINE:
      cell = &line;
      cell->PointIds.InsertId(0,cellId);
      cell->PointIds.InsertId(1,cellId+1);
      break;

    case VTK_XY_PLANE:
      cell = &quad;
      i = cellId % (this->Dimensions[0]-1);
      j = cellId / (this->Dimensions[0]-1);
      idx = i + j*this->Dimensions[0];
      offset1 = 1;
      offset2 = this->Dimensions[0];

      cell->PointIds.InsertId(0,idx);
      cell->PointIds.InsertId(1,idx+offset1);
      cell->PointIds.InsertId(2,idx+offset1+offset2);
      cell->PointIds.InsertId(3,idx+offset2);
      break;

    case VTK_YZ_PLANE:
      cell = &quad;
      j = cellId % (this->Dimensions[1]-1);
      k = cellId / (this->Dimensions[1]-1);
      idx = j + k*this->Dimensions[1];
      offset1 = 1;
      offset2 = this->Dimensions[1];

      cell->PointIds.InsertId(0,idx);
      cell->PointIds.InsertId(1,idx+offset1);
      cell->PointIds.InsertId(2,idx+offset1+offset2);
      cell->PointIds.InsertId(3,idx+offset2);
      break;

    case VTK_XZ_PLANE:
      cell = &quad;
      i = cellId % (this->Dimensions[0]-1);
      k = cellId / (this->Dimensions[0]-1);
      idx = i + k*this->Dimensions[0];
      offset1 = 1;
      offset2 = this->Dimensions[0];

      cell->PointIds.InsertId(0,idx);
      cell->PointIds.InsertId(1,idx+offset1);
      cell->PointIds.InsertId(2,idx+offset1+offset2);
      cell->PointIds.InsertId(3,idx+offset2);
      break;

    case VTK_XYZ_GRID:
      cell = &hexa;
      d01 = this->Dimensions[0]*this->Dimensions[1];
      i = cellId % (this->Dimensions[0] - 1);
      j = (cellId / (this->Dimensions[0] - 1)) % (this->Dimensions[1] - 1);
      k = cellId / ((this->Dimensions[0] - 1) * (this->Dimensions[1] - 1));
      idx = i+ j*this->Dimensions[0] + k*d01;
      offset1 = 1;
      offset2 = this->Dimensions[0];

      cell->PointIds.InsertId(0,idx);
      cell->PointIds.InsertId(1,idx+offset1);
      cell->PointIds.InsertId(2,idx+offset1+offset2);
      cell->PointIds.InsertId(3,idx+offset2);
      idx += d01;
      cell->PointIds.InsertId(4,idx);
      cell->PointIds.InsertId(5,idx+offset1);
      cell->PointIds.InsertId(6,idx+offset1+offset2);
      cell->PointIds.InsertId(7,idx+offset2);
      break;
    }

  // Extract point coordinates and point ids. NOTE: the ordering of the vtkQuad
  // and vtkHexahedron cells are tricky.
  int NumberOfIds = cell->PointIds.GetNumberOfIds();
  for (i=0; i<NumberOfIds; i++)
    {
    idx = cell->PointIds.GetId(i);
    cell->Points.InsertPoint(i,this->Points->GetPoint(idx));
    }

  return cell;
}

// Description:
// Turn on data blanking. Data blanking is the ability to turn off
// portions of the grid when displaying or operating on it. Some data
// (like finite difference data) routinely turns off data to simulate
// solid obstacles.
void vtkStructuredGrid::BlankingOn()
{
  if (!this->Blanking)
    {
    this->Blanking = 1;
    this->Modified();

    if ( !this->PointVisibility )
      {
      this->AllocatePointVisibility();
      }
    }
}

void vtkStructuredGrid::AllocatePointVisibility()
{
  if ( !this->PointVisibility )
    {
    this->PointVisibility =
      new vtkBitScalars(this->GetNumberOfPoints(),1000);
    this->PointVisibility->Register((vtkObject *)this);
    for (int i=0; i<this->GetNumberOfPoints(); i++)
      {
      this->PointVisibility->InsertScalar(i,1);
      }
    this->PointVisibility->Delete();
    }
}

// Description:
// Turn off data blanking.
void vtkStructuredGrid::BlankingOff()
{
  if (this->Blanking)
    {
    this->Blanking = 0;
    this->Modified();
    }
}

// Description:
// Turn off a particular data point.
void vtkStructuredGrid::BlankPoint(int ptId)
{
  if ( !this->PointVisibility ) this->AllocatePointVisibility();
  this->PointVisibility->InsertScalar(ptId,0);
}

// Description:
// Turn on a particular data point.
void vtkStructuredGrid::UnBlankPoint(int ptId)
{
  if ( !this->PointVisibility ) this->AllocatePointVisibility();
  this->PointVisibility->InsertScalar(ptId,1);
}

// Description:
// Set dimensions of structured grid dataset.
void vtkStructuredGrid::SetDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;
  this->SetDimensions(dim);
}

// Description:
// Set dimensions of structured grid dataset.
void vtkStructuredGrid::SetDimensions(int dim[3])
{
  int returnStatus=this->StructuredData.SetDimensions(dim,this->Dimensions);

  if ( returnStatus > -1 )
    {
    this->DataDescription = returnStatus;
    this->Modified();
    }
}

void vtkStructuredGrid::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPointSet::PrintSelf(os,indent);

  os << indent << "Dimensions: (" << this->Dimensions[0] << ", "
                                  << this->Dimensions[1] << ", "
                                  << this->Dimensions[2] << ")\n";

  os << indent << "Blanking: " << (this->Blanking ? "On\n" : "Off\n");
}

<|endoftext|>


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

#include <iostream>
#include <stdio.h>

// g++ webcam_recognise.cpp `pkg-config --cflags --libs opencv` -I/usr/include/opencv2/

using namespace std;
using namespace cv;

// Grab the next camera frame. Waits until the next frame is ready, and
// provides direct access to it, so do NOT modify or free the returned image!
// Will automatically initialize the camera on the first frame.
IplImage* getCameraFrame(CvCapture* &camera)
{
	IplImage *frame;
	int w, h;

	// If the camera hasn't been initialized, then open it.
	if (!camera) {
		printf("Acessing the camera ...\n");
		camera = cvCreateCameraCapture( 0 );
		if (!camera) {
			printf("Couldn't access the camera.\n");
			exit(1);
		}
		// Try to set the camera resolution to 320 x 240.
		cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_WIDTH, 320);
		cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_HEIGHT, 240);
		// Get the first frame, to make sure the camera is initialized.
		frame = cvQueryFrame( camera );
		if (frame) {
			w = frame->width;
			h = frame->height;
			printf("Got the camera at %dx%d resolution.\n", w, h);
		}
		// Wait a little, so that the camera can auto-adjust its brightness.
		sleep(1000);	// (in milliseconds)
	}

	// Wait until the next camera frame is ready, then grab it.
	frame = cvQueryFrame( camera );
	if (!frame) {
		printf("Couldn't grab a camera frame.\n");
		exit(1);
	}
	return frame;
}
<commit_msg>typo lint<commit_after>#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <stdio.h>

// g++ webcam_recognise.cpp `pkg-config --cflags --libs opencv` -I/usr/include/opencv2/

using namespace std;
using namespace cv;

// Grab the next camera frame. Waits until the next frame is ready, and
// provides direct access to it, so do NOT modify or free the returned image!
// Will automatically initialize the camera on the first frame.
IplImage* getCameraFrame(CvCapture* &camera) {
	IplImage *frame;
	int w, h;

	// If the camera hasn't been initialized, then open it.
	if (!camera) {
		printf("Acessing the camera ...\n");
		camera = cvCreateCameraCapture( 0 );
		if (!camera) {
			printf("Couldn't access the camera.\n");
			exit(1);
		}
		// Try to set the camera resolution to 320 x 240.
		cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_WIDTH, 320);
		cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_HEIGHT, 240);
		// Get the first frame, to make sure the camera is initialized.
		frame = cvQueryFrame( camera );
		if (frame) {
			w = frame->width;
			h = frame->height;
			printf("Got the camera at %dx%d resolution.\n", w, h);
		}
		// Wait a little, so that the camera can auto-adjust its brightness.
		sleep(1000);	// (in milliseconds)
	}

	// Wait until the next camera frame is ready, then grab it.
	frame = cvQueryFrame( camera );
	if (!frame) {
		printf("Couldn't grab a camera frame.\n");
		exit(1);
	}
	return frame;
}
<|endoftext|>


<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2014 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/ui/loop_win.h"

#include "xenia/base/assert.h"

namespace xe {
namespace ui {

std::unique_ptr<Loop> Loop::Create() { return std::make_unique<Win32Loop>(); }

Win32Loop::Win32Loop() : thread_id_(0) {
  timer_queue_ = CreateTimerQueue();

  xe::threading::Fence init_fence;
  thread_ = std::thread([&init_fence, this]() {
    xe::threading::set_name("Win32 Loop");
    thread_id_ = GetCurrentThreadId();

    // Make a Win32 call to enable the thread queue.
    MSG msg;
    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

    init_fence.Signal();

    ThreadMain();

    quit_fence_.Signal();
  });
  init_fence.Wait();
}

Win32Loop::~Win32Loop() {
  Quit();
  thread_.join();

  DeleteTimerQueueEx(timer_queue_, INVALID_HANDLE_VALUE);
  std::lock_guard<std::mutex> lock(pending_timers_mutex_);
  while (!pending_timers_.empty()) {
    auto timer = pending_timers_.back();
    pending_timers_.pop_back();
    delete timer;
  }
}

void Win32Loop::ThreadMain() {
  MSG msg;
  while (!should_exit_) {
    DWORD result =
        MsgWaitForMultipleObjectsEx(0, nullptr, INFINITE, QS_ALLINPUT, 0);

    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }

    // Process queued functions.
    std::lock_guard<std::mutex> lock(posted_functions_mutex_);
    for (auto it = posted_functions_.begin(); it != posted_functions_.end();) {
      (*it).Call();
      it = posted_functions_.erase(it);
    }
  }

  UIEvent e(nullptr);
  on_quit(&e);
}

bool Win32Loop::is_on_loop_thread() {
  return thread_id_ == GetCurrentThreadId();
}

void Win32Loop::Post(std::function<void()> fn) {
  assert_true(thread_id_ != 0);
  {
    std::lock_guard<std::mutex> lock(posted_functions_mutex_);
    PostedFn posted_fn(fn);
    posted_functions_.push_back(posted_fn);
  }

  while (!PostThreadMessage(thread_id_, WM_NULL, 0, 0)) {
    Sleep(1);
  }
}

void Win32Loop::TimerQueueCallback(void* context, uint8_t) {
  auto timer = reinterpret_cast<PendingTimer*>(context);
  auto loop = timer->loop;
  auto fn = std::move(timer->fn);
  DeleteTimerQueueTimer(timer->timer_queue, timer->timer_handle, NULL);
  {
    std::lock_guard<std::mutex> lock(loop->pending_timers_mutex_);
    loop->pending_timers_.remove(timer);
  }
  delete timer;
  loop->Post(std::move(fn));
}

void Win32Loop::PostDelayed(std::function<void()> fn, uint64_t delay_millis) {
  if (!delay_millis) {
    Post(std::move(fn));
    return;
  }
  auto timer = new PendingTimer();
  timer->loop = this;
  timer->timer_queue = timer_queue_;
  timer->fn = std::move(fn);
  {
    std::lock_guard<std::mutex> lock(pending_timers_mutex_);
    pending_timers_.push_back(timer);
  }
  CreateTimerQueueTimer(&timer->timer_handle, timer_queue_,
                        WAITORTIMERCALLBACK(TimerQueueCallback), timer,
                        DWORD(delay_millis), 0,
                        WT_EXECUTEINTIMERTHREAD | WT_EXECUTEONLYONCE);
}

void Win32Loop::Quit() {
  assert_true(thread_id_ != 0);
  should_exit_ = true;
  while (!PostThreadMessage(thread_id_, WM_NULL, 0, 0)) {
    Sleep(1);
  }
}

void Win32Loop::AwaitQuit() { quit_fence_.Wait(); }

}  // namespace ui
}  // namespace xe
<commit_msg>Fix UI thread not waking up from input<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2014 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/ui/loop_win.h"

#include "xenia/base/assert.h"

namespace xe {
namespace ui {

std::unique_ptr<Loop> Loop::Create() { return std::make_unique<Win32Loop>(); }

Win32Loop::Win32Loop() : thread_id_(0) {
  timer_queue_ = CreateTimerQueue();

  xe::threading::Fence init_fence;
  thread_ = std::thread([&init_fence, this]() {
    xe::threading::set_name("Win32 Loop");
    thread_id_ = GetCurrentThreadId();

    // Make a Win32 call to enable the thread queue.
    MSG msg;
    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

    init_fence.Signal();

    ThreadMain();

    quit_fence_.Signal();
  });
  init_fence.Wait();
}

Win32Loop::~Win32Loop() {
  Quit();
  thread_.join();

  DeleteTimerQueueEx(timer_queue_, INVALID_HANDLE_VALUE);
  std::lock_guard<std::mutex> lock(pending_timers_mutex_);
  while (!pending_timers_.empty()) {
    auto timer = pending_timers_.back();
    pending_timers_.pop_back();
    delete timer;
  }
}

void Win32Loop::ThreadMain() {
  MSG msg;
  while (!should_exit_ && GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);

    // Process queued functions.
    std::lock_guard<std::mutex> lock(posted_functions_mutex_);
    for (auto it = posted_functions_.begin(); it != posted_functions_.end();) {
      (*it).Call();
      it = posted_functions_.erase(it);
    }
  }

  UIEvent e(nullptr);
  on_quit(&e);
}

bool Win32Loop::is_on_loop_thread() {
  return thread_id_ == GetCurrentThreadId();
}

void Win32Loop::Post(std::function<void()> fn) {
  assert_true(thread_id_ != 0);
  {
    std::lock_guard<std::mutex> lock(posted_functions_mutex_);
    PostedFn posted_fn(fn);
    posted_functions_.push_back(posted_fn);
  }

  while (!PostThreadMessage(thread_id_, WM_NULL, 0, 0)) {
    Sleep(1);
  }
}

void Win32Loop::TimerQueueCallback(void* context, uint8_t) {
  auto timer = reinterpret_cast<PendingTimer*>(context);
  auto loop = timer->loop;
  auto fn = std::move(timer->fn);
  DeleteTimerQueueTimer(timer->timer_queue, timer->timer_handle, NULL);
  {
    std::lock_guard<std::mutex> lock(loop->pending_timers_mutex_);
    loop->pending_timers_.remove(timer);
  }
  delete timer;
  loop->Post(std::move(fn));
}

void Win32Loop::PostDelayed(std::function<void()> fn, uint64_t delay_millis) {
  if (!delay_millis) {
    Post(std::move(fn));
    return;
  }
  auto timer = new PendingTimer();
  timer->loop = this;
  timer->timer_queue = timer_queue_;
  timer->fn = std::move(fn);
  {
    std::lock_guard<std::mutex> lock(pending_timers_mutex_);
    pending_timers_.push_back(timer);
  }
  CreateTimerQueueTimer(&timer->timer_handle, timer_queue_,
                        WAITORTIMERCALLBACK(TimerQueueCallback), timer,
                        DWORD(delay_millis), 0,
                        WT_EXECUTEINTIMERTHREAD | WT_EXECUTEONLYONCE);
}

void Win32Loop::Quit() {
  assert_true(thread_id_ != 0);
  should_exit_ = true;
  while (!PostThreadMessage(thread_id_, WM_NULL, 0, 0)) {
    Sleep(1);
  }
}

void Win32Loop::AwaitQuit() { quit_fence_.Wait(); }

}  // namespace ui
}  // namespace xe
<|endoftext|>


<commit_before>// Experimental sample
// Sample using ORC JIT: Work in progress
#include <memory>

#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetSelect.h"

using namespace llvm;

class SimpleOrcJIT {
public:
  typedef orc::ObjectLinkingLayer<> ObjLayerT;
  typedef orc::IRCompileLayer<ObjLayerT> CompileLayerT;
  typedef CompileLayerT::ModuleSetHandleT ModuleHandleT;

  SimpleOrcJIT()
      : TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),
        CompileLayer(ObjectLayer, orc::SimpleCompiler(*TM)) {
  }

  TargetMachine &getTargetMachine() { return *TM; }

  struct NoLinkingResolver : public RuntimeDyld::SymbolResolver {
    RuntimeDyld::SymbolInfo findSymbol(const std::string &Name) {
      return nullptr;
    }
    RuntimeDyld::SymbolInfo findSymbolInLogicalDylib(const std::string &Name) {
      return nullptr;
    }
  };

  ModuleHandleT addModule(std::unique_ptr<Module> M) {
    std::vector<std::unique_ptr<Module>> MS;
    MS.push_back(std::move(M));
    auto H = CompileLayer.addModuleSet(std::move(MS),
                                       make_unique<SectionMemoryManager>(),
                                       make_unique<NoLinkingResolver>());

    ModuleHandles.push_back(H);
    return H;
  }

  void removeModule(ModuleHandleT H) {
    ModuleHandles.erase(
        std::find(ModuleHandles.begin(), ModuleHandles.end(), H));
    CompileLayer.removeModuleSet(H);
  }

  orc::JITSymbol findSymbol(const std::string Name) {
    std::string MangledName;
    {
      raw_string_ostream MangledNameStream(MangledName);
      Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
    }

    // Search modules in reverse order: from last added to first added.
    // This is the opposite of the usual search order for dlsym, but makes more
    // sense in a REPL where we want to bind to the newest available definition.
    for (auto H : make_range(ModuleHandles.rbegin(), ModuleHandles.rend()))
      if (auto Sym = CompileLayer.findSymbolIn(H, MangledName, true))
        return Sym;

    return nullptr;
  }

private:
  std::unique_ptr<TargetMachine> TM;
  const DataLayout DL;
  ObjLayerT ObjectLayer;
  CompileLayerT CompileLayer;
  std::vector<ModuleHandleT> ModuleHandles;
};

typedef double (*FooTy)(double, double);

int main(int argc, char **argv) {
  if (argc < 2) {
    errs() << "Usage: " << argv[0] << " <IR file>\n";
    return 1;
  }

  // Parse the input LLVM IR file into a module.
  SMDiagnostic Err;
  std::unique_ptr<Module> Mod(parseIRFile(argv[1], Err, getGlobalContext()));
  if (!Mod) {
    Err.print(argv[0], errs());
    return 1;
  }

  InitializeNativeTarget();
  InitializeNativeTargetAsmPrinter();
  InitializeNativeTargetAsmParser();

  SimpleOrcJIT JIT;
  JIT.addModule(std::move(Mod));

  orc::JITSymbol FooSym = JIT.findSymbol("foo");
  if (!FooSym) {
    errs() << "Unable to find symbol 'foo' in module";
    return 1;
  }

  FooTy FooPtr = reinterpret_cast<FooTy>(FooSym.getAddress());
  outs() << "foo(2.0, 3.0) = " << FooPtr(2.0, 3.0) << "\n";

  return 0;
}
<commit_msg>[experimental jit_orc_run sample] more cleanup<commit_after>// Experimental sample
// Sample using ORC JIT: Work in progress
#include <memory>

#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetSelect.h"

using namespace llvm;

class SimpleOrcJIT {
public:
  typedef orc::ObjectLinkingLayer<> ObjLayerT;
  typedef orc::IRCompileLayer<ObjLayerT> CompileLayerT;
  typedef CompileLayerT::ModuleSetHandleT ModuleHandleT;

  SimpleOrcJIT()
      : TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),
        CompileLayer(ObjectLayer, orc::SimpleCompiler(*TM)) {}

  // A simple SymbolResolver that doesn't support linking by always returning
  // nullptr.
  struct NoLinkingResolver : public RuntimeDyld::SymbolResolver {
    RuntimeDyld::SymbolInfo findSymbol(const std::string &Name) {
      return nullptr;
    }
    RuntimeDyld::SymbolInfo findSymbolInLogicalDylib(const std::string &Name) {
      return nullptr;
    }
  };

  ModuleHandleT addModule(std::unique_ptr<Module> M) {
    std::vector<std::unique_ptr<Module>> MS;
    MS.push_back(std::move(M));
    auto H = CompileLayer.addModuleSet(std::move(MS),
                                       make_unique<SectionMemoryManager>(),
                                       make_unique<NoLinkingResolver>());

    ModuleHandles.push_back(H);
    return H;
  }

  void removeModule(ModuleHandleT H) {
    ModuleHandles.erase(
        std::find(ModuleHandles.begin(), ModuleHandles.end(), H));
    CompileLayer.removeModuleSet(H);
  }

  orc::JITSymbol findSymbol(const std::string Name) {
    std::string MangledName;
    {
      raw_string_ostream MangledNameStream(MangledName);
      Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
    }

    for (auto H : make_range(ModuleHandles.rbegin(), ModuleHandles.rend())) {
      if (auto Sym = CompileLayer.findSymbolIn(H, MangledName, true)) {
        return Sym;
      }
    }

    return nullptr;
  }

private:
  std::unique_ptr<TargetMachine> TM;
  const DataLayout DL;
  ObjLayerT ObjectLayer;
  CompileLayerT CompileLayer;
  std::vector<ModuleHandleT> ModuleHandles;
};

typedef double (*FooTy)(double, double);

int main(int argc, char **argv) {
  if (argc < 2) {
    errs() << "Usage: " << argv[0] << " <IR file>\n";
    return 1;
  }

  // Parse the input LLVM IR file into a module.
  SMDiagnostic Err;
  std::unique_ptr<Module> Mod(parseIRFile(argv[1], Err, getGlobalContext()));
  if (!Mod) {
    Err.print(argv[0], errs());
    return 1;
  }

  InitializeNativeTarget();
  InitializeNativeTargetAsmPrinter();
  InitializeNativeTargetAsmParser();

  SimpleOrcJIT JIT;
  JIT.addModule(std::move(Mod));

  orc::JITSymbol FooSym = JIT.findSymbol("foo");
  if (!FooSym) {
    errs() << "Unable to find symbol 'foo' in module";
    return 1;
  }

  FooTy FooPtr = reinterpret_cast<FooTy>(FooSym.getAddress());
  outs() << "foo(2.0, 3.0) = " << FooPtr(2.0, 3.0) << "\n";

  return 0;
}
<|endoftext|>


<commit_before>#include "include/toml.h"

#include <cstring>
#include <cstdlib>
#include <vector>

void CToml::error(const char *format, ...) {
   char buffer[1024];

   va_list args; va_start(args, format);
   vsnprintf(buffer, 1024, format, args);
   va_end(args);

   errors_.push_back(CTomlError(buffer, cur_line));

   // Now we skip to the next line
   while (next_char() != '\n' && cur()) { }
   next_char();
}

bool CToml::is_whitespace(char c, bool new_line) {
   return c == '\t' || c == ' ' || (c == '\n' && new_line);
}

bool CToml::is_numeric(char c, bool dot) {
   return (c == dot && dot) || (c >= '0' && c <= '9');
}

bool CToml::is_integer(char *str) {
   // An integer must have only numeric digits. It may start with with a '-'.
   if (*str == '\0') return false;
   if (!is_numeric(str[0]) && str[0] != '-') return false;

   for (char *ch = str + 1; *ch; ch++) if (!is_numeric(*ch)) return false;
   return true;
}

bool CToml::is_float(char *str) {
   // A decimal may have a decimal point and a sign.
   if (*str == '\0') return false;
   if (!is_numeric(str[0]) && str[0] != '-') return false;

   bool decimal = false;
   for (char *ch = str + 1; *ch; ch++) {
      if (*ch == '.') {
         if (decimal) return false; // Double decimal point
         decimal = true;
      } else if(!is_numeric(*ch)) return false;
   }

   return true;
}

bool CToml::is_datetime(char *str) {
   // A datetime has the format YYYY-MM-DDThh:mm:ssZ
   // GCC still has an incomplete support for regex,
   // so it is not used here
   if (strlen(str) != 20) return false;
   return str[4] == '-' && str[7] == '-' && str[10] == 'T' &&
      str[13] == ':' && str[16] == ':' && str[19] == 'Z';
}

tm CToml::to_time(char *str) {
   int year, mon, mday, hour, min, sec;
   sscanf(str, "%d-%d-%dT%d:%d:%dZ", &year, &mon, &mday, &hour, &min, &sec);

   tm date;
   date.tm_year = year - 1900;
   date.tm_mon = mon - 1;
   date.tm_mday = mday;
   date.tm_hour = hour + 1;
   date.tm_min = min;
   date.tm_sec = sec;

   return date;
}

char CToml::next_char() {
   if (source_str_) cur() == '\0' ? '\0' : *(++cur_);
   else {
      char ch = getc(source_file_);
      *cur_ = (ch == EOF ? '\0' : ch);
   }

   if (cur() == '\n') cur_line++;
   return cur();
}

char CToml::next_skip_whitespace(bool new_lines) {
   while(next_char() && is_whitespace(cur(), new_lines)) { }
   return cur();
}

void CToml::expect(char c) {
   if (cur() != c) error("Expected '%c'", c);
   next_char();
}

void CToml::advance(char c, bool new_line) {
   skip_whitespace(new_line);
   expect(c);
}

void CToml::skip_whitespace(bool new_line) {
   if (is_whitespace(cur(), new_line)) next_skip_whitespace(new_line);
}

void CToml::skip_whitespace_and_comments() {
   while (cur() && (is_whitespace(cur(), true) || cur() == '#')) {
      if (cur() == '#') {
         while (cur() && cur() != '\n') next_char();
      }
      next_char();
   }
}

CTomlValue CToml::parse_string() {
   // A string is a double quoted string literal
   std::vector<char> str_buf;

   expect('"');
   while (cur()) {
      char c = cur(); next_char();

      // Handle special characters
      if (c == '\\' && cur()) {
         // TODO(evilncrazy): support null characters
         if (cur() == 't') c = '\t';
         else if (cur() == 'n') c = '\n';
         else if (cur() == 'r') c = '\r';
         else if (cur() == '"') c = '"';
         else if (cur() == '\\') c = '\\';
         else return error("Invalid escape character \\%c", cur()), CTomlValue();

         next_char();
      } else if (c == '"') {
         // String closed in a double quote
         break;
      }

      str_buf.push_back(c);
   }

   str_buf.push_back('\0');
   return CTomlValue(&str_buf[0]);
}

CTomlValue CToml::parse_number() {
   std::vector<char> str_buf;

   while (!is_whitespace(cur(), true) && cur() != ',' && cur() != ']') {
      str_buf.push_back(cur());
      next_char();
   }

   str_buf.push_back('\0');

   // Decide what data type it is
   if (is_integer(&str_buf[0])) return CTomlValue(atoll(&str_buf[0]));
   if (is_float(&str_buf[0])) return CTomlValue(atof(&str_buf[0]));
   if (is_datetime(&str_buf[0])) return CTomlValue(to_time(&str_buf[0]));
   else return error("\"%s\" is not a valid value",
      std::string(&str_buf[0]).c_str()), CTomlValue();
}

CTomlValue CToml::parse_boolean() {
   std::string str;
   while (!is_whitespace(cur(), true) && cur()) {
      str += cur();
      next_char();
   }

   if (str == "true") return CTomlValue(true);
   else if(str == "false") return CTomlValue(false);
   else return error("\"%s\" is not a valid value", str.c_str()), CTomlValue();
}

CTomlValue CToml::parse_array() {
   // TODO(evilncrazy): Currently, arrays can be heterogenous
   // that is, each element can be of any type. There is currently
   // a discussion on whether to switch to heterogenous arrays.
   // Shall wait and see.
   expect('[');

   std::vector<CTomlValue> array;
   while (cur() && cur() != ']') {
      skip_whitespace_and_comments();
      array.push_back(parse_value());

      skip_whitespace_and_comments();
      if (cur() == ']') break;
      advance(',');
      skip_whitespace_and_comments(); // Need this for trailing commas
   }

   advance(']');
   return CTomlValue(&array[0], array.size());
}

std::string CToml::parse_key_group() {
   expect('[');

   // Read until close bracket
   std::vector<char> str_buf;
   while (cur() && cur() != ']') {
      str_buf.push_back(cur());
      next_char();
   }

   expect(']');

   str_buf.push_back('\0');
   return std::string(&str_buf[0]);
}

CTomlValue CToml::parse_value() {
   if (cur() == '"') return parse_string();
   if (is_numeric(cur()) || cur() == '-') return parse_number();
   if (cur() == '[') return parse_array();
   return parse_boolean();
}

std::string CToml::parse_key() {
   std::vector<char> str_buf;
   while (!is_whitespace(cur()) && cur() && cur() != '=') {
      str_buf.push_back(cur());
      next_char();
   }

   str_buf.push_back('\0');
   return std::string(&str_buf[0]);
}

void CToml::parse() {
   std::string cur_group;

   // Find next non-whitespace character
   while (skip_whitespace_and_comments(), cur()) {
      if(cur() == '[') {
         // Key group (it's not an array as an array is always a value)
         cur_group = parse_key_group() + ".";
      } else {
         std::string key = cur_group + parse_key();
         advance('='); skip_whitespace();

         CTomlValue value = parse_value();
         if (value.type() != TOML_NULL) {
            // We check all the prefix key groups to ensure that they haven't
            // already been defined previously
            size_t dot_pos = 0;
            while (dot_pos = key.find(".", dot_pos + 1), dot_pos != std::string::npos) {
               std::string key_group(key, 0, dot_pos);
               if(get(key_group.c_str()).type() != TOML_NULL) {
                  error("The key '%s' has already been used", key_group.c_str());
                  break;
               }
            }

            // Now check the whole key
            if (get(key.c_str()).type() == TOML_NULL) {
               if (success())
                  values_.insert(std::make_pair(key, value));
            } else {
               error("The key '%s' has already been used", key.c_str());
            }
         }
      }
   }
}

CTomlValue CToml::get(const char *key) const {
   return get(const_cast<char *>(key));
}

CTomlValue CToml::get(char *key) const {
   auto it = values_.find(std::string(key));
   return it != values_.end() ? it->second : CTomlValue();
}

bool CToml::from(char *str) {
   if (str == NULL) return false;

   source_str_ = new char[strlen(str) + 2];
   strcpy(source_str_ + 1, str);

   // When the parser starts, it will call next_char(), which means that
   // the first character will be skipped. So we put a dummy character
   // in the front, so nothing gets skipped.
   source_str_[0] = ' ';
   cur_ = source_str_;

   return true;
}

bool CToml::open(const char *file) {
   source_file_ = fopen(file, "r");
   cur_ = new char(' '); // Dummy value

   return source_file_ != NULL;
}<commit_msg>Fix ambiguous call<commit_after>#include "include/toml.h"

#include <cstring>
#include <cstdlib>
#include <vector>

void CToml::error(const char *format, ...) {
   char buffer[1024];

   va_list args; va_start(args, format);
   vsnprintf(buffer, 1024, format, args);
   va_end(args);

   errors_.push_back(CTomlError(buffer, cur_line));

   // Now we skip to the next line
   while (next_char() != '\n' && cur()) { }
   next_char();
}

bool CToml::is_whitespace(char c, bool new_line) {
   return c == '\t' || c == ' ' || (c == '\n' && new_line);
}

bool CToml::is_numeric(char c, bool dot) {
   return (c == dot && dot) || (c >= '0' && c <= '9');
}

bool CToml::is_integer(char *str) {
   // An integer must have only numeric digits. It may start with with a '-'.
   if (*str == '\0') return false;
   if (!is_numeric(str[0]) && str[0] != '-') return false;

   for (char *ch = str + 1; *ch; ch++) if (!is_numeric(*ch)) return false;
   return true;
}

bool CToml::is_float(char *str) {
   // A decimal may have a decimal point and a sign.
   if (*str == '\0') return false;
   if (!is_numeric(str[0]) && str[0] != '-') return false;

   bool decimal = false;
   for (char *ch = str + 1; *ch; ch++) {
      if (*ch == '.') {
         if (decimal) return false; // Double decimal point
         decimal = true;
      } else if(!is_numeric(*ch)) return false;
   }

   return true;
}

bool CToml::is_datetime(char *str) {
   // A datetime has the format YYYY-MM-DDThh:mm:ssZ
   // GCC still has an incomplete support for regex,
   // so it is not used here
   if (strlen(str) != 20) return false;
   return str[4] == '-' && str[7] == '-' && str[10] == 'T' &&
      str[13] == ':' && str[16] == ':' && str[19] == 'Z';
}

tm CToml::to_time(char *str) {
   int year, mon, mday, hour, min, sec;
   sscanf(str, "%d-%d-%dT%d:%d:%dZ", &year, &mon, &mday, &hour, &min, &sec);

   tm date;
   date.tm_year = year - 1900;
   date.tm_mon = mon - 1;
   date.tm_mday = mday;
   date.tm_hour = hour + 1;
   date.tm_min = min;
   date.tm_sec = sec;

   return date;
}

char CToml::next_char() {
   if (source_str_) cur() == '\0' ? '\0' : *(++cur_);
   else {
      char ch = getc(source_file_);
      *cur_ = (ch == EOF ? '\0' : ch);
   }

   if (cur() == '\n') cur_line++;
   return cur();
}

char CToml::next_skip_whitespace(bool new_lines) {
   while(next_char() && is_whitespace(cur(), new_lines)) { }
   return cur();
}

void CToml::expect(char c) {
   if (cur() != c) error("Expected '%c'", c);
   next_char();
}

void CToml::advance(char c, bool new_line) {
   skip_whitespace(new_line);
   expect(c);
}

void CToml::skip_whitespace(bool new_line) {
   if (is_whitespace(cur(), new_line)) next_skip_whitespace(new_line);
}

void CToml::skip_whitespace_and_comments() {
   while (cur() && (is_whitespace(cur(), true) || cur() == '#')) {
      if (cur() == '#') {
         while (cur() && cur() != '\n') next_char();
      }
      next_char();
   }
}

CTomlValue CToml::parse_string() {
   // A string is a double quoted string literal
   std::vector<char> str_buf;

   expect('"');
   while (cur()) {
      char c = cur(); next_char();

      // Handle special characters
      if (c == '\\' && cur()) {
         // TODO(evilncrazy): support null characters
         if (cur() == 't') c = '\t';
         else if (cur() == 'n') c = '\n';
         else if (cur() == 'r') c = '\r';
         else if (cur() == '"') c = '"';
         else if (cur() == '\\') c = '\\';
         else return error("Invalid escape character \\%c", cur()), CTomlValue();

         next_char();
      } else if (c == '"') {
         // String closed in a double quote
         break;
      }

      str_buf.push_back(c);
   }

   str_buf.push_back('\0');
   return CTomlValue(&str_buf[0]);
}

CTomlValue CToml::parse_number() {
   std::vector<char> str_buf;

   while (!is_whitespace(cur(), true) && cur() != ',' && cur() != ']') {
      str_buf.push_back(cur());
      next_char();
   }

   str_buf.push_back('\0');

   // Decide what data type it is
   if (is_integer(&str_buf[0])) return CTomlValue(int64_t(atoll(&str_buf[0])));
   if (is_float(&str_buf[0])) return CTomlValue(atof(&str_buf[0]));
   if (is_datetime(&str_buf[0])) return CTomlValue(to_time(&str_buf[0]));
   else return error("\"%s\" is not a valid value",
      std::string(&str_buf[0]).c_str()), CTomlValue();
}

CTomlValue CToml::parse_boolean() {
   std::string str;
   while (!is_whitespace(cur(), true) && cur()) {
      str += cur();
      next_char();
   }

   if (str == "true") return CTomlValue(true);
   else if(str == "false") return CTomlValue(false);
   else return error("\"%s\" is not a valid value", str.c_str()), CTomlValue();
}

CTomlValue CToml::parse_array() {
   // TODO(evilncrazy): Currently, arrays can be heterogenous
   // that is, each element can be of any type. There is currently
   // a discussion on whether to switch to heterogenous arrays.
   // Shall wait and see.
   expect('[');

   std::vector<CTomlValue> array;
   while (cur() && cur() != ']') {
      skip_whitespace_and_comments();
      array.push_back(parse_value());

      skip_whitespace_and_comments();
      if (cur() == ']') break;
      advance(',');
      skip_whitespace_and_comments(); // Need this for trailing commas
   }

   advance(']');
   return CTomlValue(&array[0], array.size());
}

std::string CToml::parse_key_group() {
   expect('[');

   // Read until close bracket
   std::vector<char> str_buf;
   while (cur() && cur() != ']') {
      str_buf.push_back(cur());
      next_char();
   }

   expect(']');

   str_buf.push_back('\0');
   return std::string(&str_buf[0]);
}

CTomlValue CToml::parse_value() {
   if (cur() == '"') return parse_string();
   if (is_numeric(cur()) || cur() == '-') return parse_number();
   if (cur() == '[') return parse_array();
   return parse_boolean();
}

std::string CToml::parse_key() {
   std::vector<char> str_buf;
   while (!is_whitespace(cur()) && cur() && cur() != '=') {
      str_buf.push_back(cur());
      next_char();
   }

   str_buf.push_back('\0');
   return std::string(&str_buf[0]);
}

void CToml::parse() {
   std::string cur_group;

   // Find next non-whitespace character
   while (skip_whitespace_and_comments(), cur()) {
      if(cur() == '[') {
         // Key group (it's not an array as an array is always a value)
         cur_group = parse_key_group() + ".";
      } else {
         std::string key = cur_group + parse_key();
         advance('='); skip_whitespace();

         CTomlValue value = parse_value();
         if (value.type() != TOML_NULL) {
            // We check all the prefix key groups to ensure that they haven't
            // already been defined previously
            size_t dot_pos = 0;
            while (dot_pos = key.find(".", dot_pos + 1), dot_pos != std::string::npos) {
               std::string key_group(key, 0, dot_pos);
               if(get(key_group.c_str()).type() != TOML_NULL) {
                  error("The key '%s' has already been used", key_group.c_str());
                  break;
               }
            }

            // Now check the whole key
            if (get(key.c_str()).type() == TOML_NULL) {
               if (success())
                  values_.insert(std::make_pair(key, value));
            } else {
               error("The key '%s' has already been used", key.c_str());
            }
         }
      }
   }
}

CTomlValue CToml::get(const char *key) const {
   return get(const_cast<char *>(key));
}

CTomlValue CToml::get(char *key) const {
   auto it = values_.find(std::string(key));
   return it != values_.end() ? it->second : CTomlValue();
}

bool CToml::from(char *str) {
   if (str == NULL) return false;

   source_str_ = new char[strlen(str) + 2];
   strcpy(source_str_ + 1, str);

   // When the parser starts, it will call next_char(), which means that
   // the first character will be skipped. So we put a dummy character
   // in the front, so nothing gets skipped.
   source_str_[0] = ' ';
   cur_ = source_str_;

   return true;
}

bool CToml::open(const char *file) {
   source_file_ = fopen(file, "r");
   cur_ = new char(' '); // Dummy value

   return source_file_ != NULL;
}<|endoftext|>


<commit_before>/* Copyright (c) 2008, Avian Contributors

   Permission to use, copy, modify, and/or distribute this software
   for any purpose with or without fee is hereby granted, provided
   that the above copyright notice and this permission notice appear
   in all copies.

   There is NO WARRANTY for this software.  See license.txt for
   details. */

#include "assembler.h"
#include "vector.h"

using namespace vm;

namespace {

enum Register {
  rax = 0,
  rcx = 1,
  rdx = 2,
  rbx = 3,
  rsp = 4,
  rbp = 5,
  rsi = 6,
  rdi = 7,
  r8 = 8,
  r9 = 9,
  r10 = 10,
  r11 = 11,
  r12 = 12,
  r13 = 13,
  r14 = 14,
  r15 = 15,
};

class Task {
 public:
  Task(Task* next): next(next) { }

  virtual ~Task() { }

  virtual void run(uint8_t* code) = 0;

  Task* next;
};

class MyAssembler: public Assembler {
 public:
  MyAssembler(System* s, Allocator* a): s(s), code(s, a, 1024), tasks(0) { }

  virtual unsigned registerCount() {
    return BytesPerWord == 4 ? 8 : 16;
  }

  virtual int base() {
    return rbp;
  }

  virtual int stack() {
    return rsp;
  }

  virtual int thread() {
    return rbx;
  }

  virtual int returnLow() {
    return rax;
  }

  virtual int returnHigh() {
    return (BytesPerWord == 4 ? rdx : NoRegister);
  }

  virtual unsigned argumentRegisterCount() {
    return (BytesPerWord == 4 ? 0 : 6);
  }

  virtual int argumentRegister(unsigned index) {
    assert(s, BytesPerWord == 8);

    switch (index) {
    case 0:
      return rdi;
    case 1:
      return rsi;
    case 2:
      return rdx;
    case 3:
      return rcx;
    case 4:
      return r8;
    case 5:
      return r9;
    default:
      abort(s);
    }
  }

  virtual int stackSyncRegister(unsigned index) {
    switch (index) {
    case 0:
      return rax;
    case 1:
      return rcx;
    case 2:
      return rdx;
    case 3:
      return rsi;
    case 4:
      return rdi;
    default:
      abort(s);
    }
  }

  virtual void getTargets(UnaryOperation /*op*/, unsigned /*size*/,
                          Register* r)
  {
    // todo
    r->low = NoRegister;
    r->high = NoRegister;
  }

  virtual void getTargets(BinaryOperation /*op*/, unsigned /*size*/,
                          Register* a, Register* b)
  {
    // todo
    a->low = NoRegister;
    a->high = NoRegister;
    b->low = NoRegister;
    b->high = NoRegister;
  }

  virtual void apply(Operation /*op*/) {
    // todo
    abort(s);
  }

  virtual void apply(UnaryOperation /*op*/, unsigned /*size*/,
                     OperandType /*type*/, Operand* /*operand*/)
  {
    // todo
    abort(s);
  }

  virtual void apply(BinaryOperation /*op*/, unsigned /*size*/,
                     OperandType /*aType*/, Operand* /*a*/,
                     OperandType /*bType*/, Operand* /*b*/)
  {
    // todo
    abort(s);
  }

  virtual void writeTo(uint8_t* dst) {
    memcpy(dst, code.data, code.length());

    for (Task* t = tasks; t; t = t->next) {
      t->run(dst);
    }
  }

  virtual unsigned length() {
    return code.length();
  }

  virtual void updateCall(void* returnAddress, void* newTarget) {
    uint8_t* instruction = static_cast<uint8_t*>(returnAddress) - 5;
    assert(s, *instruction == 0xE8);
    assert(s, reinterpret_cast<uintptr_t>(instruction + 1) % 4 == 0);

    int32_t v = static_cast<uint8_t*>(newTarget)
      - static_cast<uint8_t*>(returnAddress);
    memcpy(instruction + 1, &v, 4);
  }

  System* s;
  Vector code;
  Task* tasks;
};

} // namespace

namespace vm {

Assembler*
makeAssembler(System* system, Allocator* allocator, Zone* zone)
{
  return new (zone->allocate(sizeof(MyAssembler)))
    MyAssembler(system, allocator);
}

} // namespace vm
<commit_msg>remove x86.cpp<commit_after><|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2010-2011, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "ToHoudiniStringAttribConverter.h"

using namespace IECore;

namespace IECoreHoudini
{

IE_CORE_DEFINERUNTIMETYPED( ToHoudiniStringVectorAttribConverter );

ToHoudiniAttribConverter::Description<ToHoudiniStringVectorAttribConverter> ToHoudiniStringVectorAttribConverter::m_description( StringVectorData::staticTypeId() );

ToHoudiniStringVectorAttribConverter::ToHoudiniStringVectorAttribConverter( const IECore::Data *data ) :
	ToHoudiniAttribConverter( data, "Converts IECore::StringVectorData to a GB_Attribute on the provided GU_Detail." )
{
	m_indicesParameter = new IntVectorParameter( "indices", "the indices into the source StringVectorData", new IntVectorData() );
	parameters()->addParameter( m_indicesParameter );
}

ToHoudiniStringVectorAttribConverter::~ToHoudiniStringVectorAttribConverter()
{
}

IntVectorParameterPtr ToHoudiniStringVectorAttribConverter::indicesParameter()
{
	return m_indicesParameter;
}

ConstIntVectorParameterPtr ToHoudiniStringVectorAttribConverter::indicesParameter() const
{
	return m_indicesParameter;
}

GA_RWAttributeRef ToHoudiniStringVectorAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo ) const
{
	/// \todo: this used to be supported. why?
	throw IECore::Exception( "ToHoudiniStringVectorAttribConverter does not support Detail attributes." );
}

GA_RWAttributeRef ToHoudiniStringVectorAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo, const GA_Range &range ) const
{
	assert( data );

	const IECore::StringVectorData *stringVectorData = IECore::runTimeCast<const IECore::StringVectorData>( data );
	if ( !stringVectorData )
	{
		throw IECore::Exception( ( boost::format( "ToHoudiniStringVectorAttribConverter::doConversion: PrimitiveVariable \"%s\" does not contain IECore::StringVectorData." ) % name ).str() );
	}

	GA_RWAttributeRef attrRef = geo->addStringTuple( range.getOwner(), name.c_str(), 1 );
	if ( attrRef.isInvalid() )
	{
		throw IECore::Exception( ( boost::format( "ToHoudiniStringVectorAttribConverter::doConversion: Invalid GA_RWAttributeRef returned for PrimitiveVariable \"%s\"." ) % name ).str() );
	}

	if ( !range.isValid() || range.empty() )
	{
		return attrRef;
	}

	GA_Attribute *attr = attrRef.getAttribute();

	const GA_AIFSharedStringTuple *tuple = attr->getAIFSharedStringTuple();

	UT_StringArray strings;
	const std::vector<std::string> &stringVector = stringVectorData->readable();

	const std::vector<int> &indices = ((const IECore::IntVectorData *)m_indicesParameter->getValidatedValue())->readable();
	if ( indices.empty() || stringVector.empty() )
	{
		return attrRef;
	}

	size_t i = 0;
	size_t numIndices = indices.size();
	for ( GA_Iterator it=range.begin(); !it.atEnd(), i < numIndices; ++it, ++i )
	{
		tuple->setString( attr, it.getOffset(), stringVector[ indices[i] ].c_str(), 0 );
	}

	return attrRef;
}

IE_CORE_DEFINERUNTIMETYPED( ToHoudiniStringDetailAttribConverter );

ToHoudiniAttribConverter::Description<ToHoudiniStringDetailAttribConverter> ToHoudiniStringDetailAttribConverter::m_description( StringData::staticTypeId() );

ToHoudiniStringDetailAttribConverter::ToHoudiniStringDetailAttribConverter( const IECore::Data *data ) :
	ToHoudiniAttribConverter( data, "Converts IECore::StringData to a GB_Attribute on the provided GU_Detail." )
{
}

ToHoudiniStringDetailAttribConverter::~ToHoudiniStringDetailAttribConverter()
{
}

GA_RWAttributeRef ToHoudiniStringDetailAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo ) const
{
	assert( data );

	const StringData *stringData = IECore::runTimeCast<const StringData>( data );
	if ( !stringData )
	{
		throw IECore::Exception( ( boost::format( "ToHoudiniStringDetailAttribConverter::doConversion: PrimitiveVariable \"%s\" does not contain IECore::StringData." ) % name ).str() );
	}

	GA_RWAttributeRef attrRef = geo->addStringTuple( GA_ATTRIB_DETAIL, name.c_str(), 1 );
	if ( attrRef.isInvalid() )
	{
		throw IECore::Exception( ( boost::format( "ToHoudiniStringDetailAttribConverter::doConversion: Invalid GA_RWAttributeRef returned for PrimitiveVariable \"%s\"." ) % name ).str() );
	}

	GA_Attribute *attr = attrRef.getAttribute();
	attr->getAIFSharedStringTuple()->setString( attr, 0, stringData->readable().c_str(), 0 );

	return attrRef;
}

GA_RWAttributeRef ToHoudiniStringDetailAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo, const GA_Range &range ) const
{
	throw IECore::Exception( "ToHoudiniStringDetailAttribConverter does not support Element attributes." );
}

} // namespace IECoreHoudini
<commit_msg>fixing todo. it was for backwards compatibility with old models, but didnt do the right thing anyways... just giving a warning rather than throwing<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2010-2011, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECore/MessageHandler.h"

#include "ToHoudiniStringAttribConverter.h"

using namespace IECore;

namespace IECoreHoudini
{

IE_CORE_DEFINERUNTIMETYPED( ToHoudiniStringVectorAttribConverter );

ToHoudiniAttribConverter::Description<ToHoudiniStringVectorAttribConverter> ToHoudiniStringVectorAttribConverter::m_description( StringVectorData::staticTypeId() );

ToHoudiniStringVectorAttribConverter::ToHoudiniStringVectorAttribConverter( const IECore::Data *data ) :
	ToHoudiniAttribConverter( data, "Converts IECore::StringVectorData to a GB_Attribute on the provided GU_Detail." )
{
	m_indicesParameter = new IntVectorParameter( "indices", "the indices into the source StringVectorData", new IntVectorData() );
	parameters()->addParameter( m_indicesParameter );
}

ToHoudiniStringVectorAttribConverter::~ToHoudiniStringVectorAttribConverter()
{
}

IntVectorParameterPtr ToHoudiniStringVectorAttribConverter::indicesParameter()
{
	return m_indicesParameter;
}

ConstIntVectorParameterPtr ToHoudiniStringVectorAttribConverter::indicesParameter() const
{
	return m_indicesParameter;
}

GA_RWAttributeRef ToHoudiniStringVectorAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo ) const
{
	IECore::msg( IECore::MessageHandler::Error, "ToHoudiniStringVectorAttribConverter", "Does not support Detail attributes." );
	return GA_RWAttributeRef();
}

GA_RWAttributeRef ToHoudiniStringVectorAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo, const GA_Range &range ) const
{
	assert( data );

	const IECore::StringVectorData *stringVectorData = IECore::runTimeCast<const IECore::StringVectorData>( data );
	if ( !stringVectorData )
	{
		throw IECore::Exception( ( boost::format( "ToHoudiniStringVectorAttribConverter::doConversion: PrimitiveVariable \"%s\" does not contain IECore::StringVectorData." ) % name ).str() );
	}

	GA_RWAttributeRef attrRef = geo->addStringTuple( range.getOwner(), name.c_str(), 1 );
	if ( attrRef.isInvalid() )
	{
		throw IECore::Exception( ( boost::format( "ToHoudiniStringVectorAttribConverter::doConversion: Invalid GA_RWAttributeRef returned for PrimitiveVariable \"%s\"." ) % name ).str() );
	}

	if ( !range.isValid() || range.empty() )
	{
		return attrRef;
	}

	GA_Attribute *attr = attrRef.getAttribute();

	const GA_AIFSharedStringTuple *tuple = attr->getAIFSharedStringTuple();

	UT_StringArray strings;
	const std::vector<std::string> &stringVector = stringVectorData->readable();

	const std::vector<int> &indices = ((const IECore::IntVectorData *)m_indicesParameter->getValidatedValue())->readable();
	if ( indices.empty() || stringVector.empty() )
	{
		return attrRef;
	}

	size_t i = 0;
	size_t numIndices = indices.size();
	for ( GA_Iterator it=range.begin(); !it.atEnd(), i < numIndices; ++it, ++i )
	{
		tuple->setString( attr, it.getOffset(), stringVector[ indices[i] ].c_str(), 0 );
	}

	return attrRef;
}

IE_CORE_DEFINERUNTIMETYPED( ToHoudiniStringDetailAttribConverter );

ToHoudiniAttribConverter::Description<ToHoudiniStringDetailAttribConverter> ToHoudiniStringDetailAttribConverter::m_description( StringData::staticTypeId() );

ToHoudiniStringDetailAttribConverter::ToHoudiniStringDetailAttribConverter( const IECore::Data *data ) :
	ToHoudiniAttribConverter( data, "Converts IECore::StringData to a GB_Attribute on the provided GU_Detail." )
{
}

ToHoudiniStringDetailAttribConverter::~ToHoudiniStringDetailAttribConverter()
{
}

GA_RWAttributeRef ToHoudiniStringDetailAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo ) const
{
	assert( data );

	const StringData *stringData = IECore::runTimeCast<const StringData>( data );
	if ( !stringData )
	{
		throw IECore::Exception( ( boost::format( "ToHoudiniStringDetailAttribConverter::doConversion: PrimitiveVariable \"%s\" does not contain IECore::StringData." ) % name ).str() );
	}

	GA_RWAttributeRef attrRef = geo->addStringTuple( GA_ATTRIB_DETAIL, name.c_str(), 1 );
	if ( attrRef.isInvalid() )
	{
		throw IECore::Exception( ( boost::format( "ToHoudiniStringDetailAttribConverter::doConversion: Invalid GA_RWAttributeRef returned for PrimitiveVariable \"%s\"." ) % name ).str() );
	}

	GA_Attribute *attr = attrRef.getAttribute();
	attr->getAIFSharedStringTuple()->setString( attr, 0, stringData->readable().c_str(), 0 );

	return attrRef;
}

GA_RWAttributeRef ToHoudiniStringDetailAttribConverter::doConversion( const IECore::Data *data, std::string name, GU_Detail *geo, const GA_Range &range ) const
{
	throw IECore::Exception( "ToHoudiniStringDetailAttribConverter does not support Element attributes." );
}

} // namespace IECoreHoudini
<|endoftext|>


<commit_before>/*
Copyright (c) 2011,2015 Jeff Donner

    Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

    The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <string>
#include "tree_parser.h"
#include "tree-kernel.h"
#include "sentence.h"

using namespace std;

// g++ -g .objs/node.o .objs/sentence.o .objs/tree-kernel.o .objs/test-tree-kernel.o -L../tree-parser -ltree_parser -o test-tree-kernel

string g_real =
   "(ROOT (S (VP (MD Must) (VP (VB have) (NP (NN java)))) (. .)))";

// oversimple parse
string g_dog_eat_dog =
"(S"
"  (NN dog)"
"  (VBP eat)"
"  (NN dog))";

// oversimple parse
string g_dog_eat_fish =
"(S"
"  (NN dog)"
"  (VBP eat)"
"  (NN fish))";

string g_brought_a_cat =
" (VP (V brought)"
"     (NP (D a)"
"         (N cat)))"
   ;

Tree const* make_tree(string const& tree_text)
{
   TreeLexer lexer(tree_text);
   TreeParser parser(lexer);
   Tree const* t = 0;
   try {
      t = parser.match_and_eat_tree();
   }
   catch (string& ex) {
      cout << "failed parse: " << ex << endl;
   }

//   t->pretty_print(cout, 0);

   return t;
}

double kernel_value(string one, string two, bool want_sst_not_st)
{
   Tree const* t1 = make_tree(one);
   Tree const* t2 = make_tree(two);

   cout << "s1" << endl;
   Sentence s1(t1);
   cout << "s2" << endl;
   Sentence s2(t2);

   // sigma == 1 is SSTs (fragments)
   // sigma == 0 is STs (whole sub-trees, down to leaves)
   int sigma = want_sst_not_st ? 1 : 0;
   double value = kernel_value(s1, s2, sigma);
   return value;
}

void test_sst(string test_name, string one, string two, double expected)
{
   cout << test_name << endl;
   double value = kernel_value(one, two, true);
   if (value != expected) {
      cout << "failed - got: " << value << " instead of: " << expected << endl;
   }
   else
      cout << " ok" << endl;
}

void test_st(string test_name, string one, string two, double expected)
{
   cout << test_name << endl;
   double value = kernel_value(one, two, false);
   if (value != expected) {
      cout << "failed - got: " << value << " instead of: " << expected << endl;
   }
   else
      cout << " ok" << endl;
}

int main()
{
   // SSTs are like STs, except that you can
   // 'break a single leg off of' a pre-terminal, and all off of
   // an ordinary non-terminal (because it's really just acting as
   // a child of its parent's rule). So if you include a production
   // you must include it all. Pre-terminals only /have/ one 'leg',
   // so they're included automatically.
   //
   // '17' is from the paper
   test_sst("brought a cat", g_brought_a_cat, g_brought_a_cat, 17);
   // hand-counted; number of non-terminal nodes
   test_st("brought a cat", g_brought_a_cat, g_brought_a_cat, 5);

   return 0;
}
<commit_msg>added pseudocode for the algorithm to generate all subtrees, use of which will allow more thorough testing<commit_after>/*
Copyright (c) 2011,2015 Jeff Donner

    Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

    The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <string>
#include "tree_parser.h"
#include "tree-kernel.h"
#include "sentence.h"

using namespace std;

// g++ -g .objs/node.o .objs/sentence.o .objs/tree-kernel.o .objs/test-tree-kernel.o -L../tree-parser -ltree_parser -o test-tree-kernel

string g_real =
   "(ROOT (S (VP (MD Must) (VP (VB have) (NP (NN java)))) (. .)))";

// oversimple parse
string g_dog_eat_dog =
"(S"
"  (NN dog)"
"  (VBP eat)"
"  (NN dog))";

// oversimple parse
string g_dog_eat_fish =
"(S"
"  (NN dog)"
"  (VBP eat)"
"  (NN fish))";

string g_brought_a_cat =
" (VP (V brought)"
"     (NP (D a)"
"         (N cat)))"
   ;

Tree const* make_tree(string const& tree_text)
{
   TreeLexer lexer(tree_text);
   TreeParser parser(lexer);
   Tree const* t = 0;
   try {
      t = parser.match_and_eat_tree();
   }
   catch (string& ex) {
      cout << "failed parse: " << ex << endl;
   }

//   t->pretty_print(cout, 0);

   return t;
}

double kernel_value(string one, string two, bool want_sst_not_st)
{
   Tree const* t1 = make_tree(one);
   Tree const* t2 = make_tree(two);

   cout << "s1" << endl;
   Sentence s1(t1);
   cout << "s2" << endl;
   Sentence s2(t2);

   // sigma == 1 is SSTs (fragments)
   // sigma == 0 is STs (whole sub-trees, down to leaves)
   int sigma = want_sst_not_st ? 1 : 0;
   double value = kernel_value(s1, s2, sigma);
   return value;
}

void test_sst(string test_name, string one, string two, double expected)
{
   cout << test_name << endl;
   double value = kernel_value(one, two, true);
   if (value != expected) {
      cout << "failed - got: " << value << " instead of: " << expected << endl;
   }
   else
      cout << " ok" << endl;
}

void test_st(string test_name, string one, string two, double expected)
{
   cout << test_name << endl;
   double value = kernel_value(one, two, false);
   if (value != expected) {
      cout << "failed - got: " << value << " instead of: " << expected << endl;
   }
   else
      cout << " ok" << endl;
}

/* Yo - to test better, we need more sub-tree'd sentences.

   def generate_all_connected_subtrees(node, path-so-far):
       generate powerset of all children of node
       with the empty subset, add path-so-far as a complete subtree

       generate_all_connected_subtrees(child, path-so-far + child)

   def generate all subtrees(root):
       for node in all root:
           generate_all)connected_subtrees(node, null)

 */

int main()
{
   // SSTs are like STs, except that you can
   // 'break a single leg off of' a pre-terminal, and all off of
   // an ordinary non-terminal (because it's really just acting as
   // a child of its parent's rule). So if you include a production
   // you must include it all. Pre-terminals only /have/ one 'leg',
   // so they're included automatically.
   //
   // '17' is from the paper
   test_sst("brought a cat", g_brought_a_cat, g_brought_a_cat, 17);
   // hand-counted; number of non-terminal nodes
   test_st("brought a cat", g_brought_a_cat, g_brought_a_cat, 5);

   return 0;
}
<|endoftext|>