<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>

#include "ast/Printer.hpp"

#include "variant.hpp"
#include "assert.hpp"
#include "VisitorUtils.hpp"
#include "Variable.hpp"

using namespace eddic;

namespace {

std::string toStringType(ast::Type type){
    if(auto* ptr = boost::get<ast::SimpleType>(&type)){
        return ptr->type;
    } else if(auto* ptr = boost::get<ast::ArrayType>(&type)){
        return ptr->type + "[]";
    } else {
        ASSERT_PATH_NOT_TAKEN("Unhandled type");
    }
}

struct DebugVisitor : public boost::static_visitor<> {
    mutable int level = 0;

    std::string indent() const {
        std::string acc = "";
        for(int i = 0; i < level; ++i){
            acc += "    ";
        }
        return acc;
    }

    template<typename Container>
    void print_each_sub(Container& container) const {
        level++;
        visit_each(*this, container);
        level--;
    }

    template<typename Container>
    void print_each_sub(Container& container, const std::string& title) const {
        std::cout << indent() << title << std::endl;
        print_each_sub(container);
    }

    template<typename Container>
    void print_each_sub_non_variant(Container& container) const {
        level++;
        visit_each_non_variant(*this, container);
        level--;
    }

    template<typename Container>
    void print_each_sub_non_variant(Container& container, const std::string& title) const {
        std::cout << indent() << title << std::endl;
        print_each_sub_non_variant(container);
    }

    template<typename Container>
    void print_sub(Container& container) const {
        level++;
        visit(*this, container);
        level--;
    }

    template<typename Container>
    void print_sub(Container& container, const std::string& title) const {
        std::cout << indent() << title << std::endl;
        print_sub(container);
    }

    void operator()(ast::SourceFile& program) const {
        print_each_sub(program.Content->blocks, "SourceFile");
    }

    void operator()(ast::Import& import) const {
        std::cout << indent() << "include \"" << import.file << "\"" << std::endl;
    }

    void operator()(ast::StandardImport& import) const {
        std::cout << indent() << "include <" << import.header << ">" << std::endl;
    }

    void operator()(ast::FunctionDeclaration& declaration) const {
        std::cout << indent() << "Function " << declaration.Content->functionName << std::endl;

        std::cout << indent() << "Parameters:" << std::endl;
        level++;
        for(auto param : declaration.Content->parameters){
            std::cout << indent() << param.parameterName << std::endl;
        }
        level--;

        print_each_sub(declaration.Content->instructions, "Instructions:");
    }

    void operator()(ast::Constructor& declaration) const {
        std::cout << indent() << "Constructor" << std::endl;

        std::cout << indent() << "Parameters:" << std::endl;
        level++;
        for(auto param : declaration.Content->parameters){
            std::cout << indent() << param.parameterName << std::endl;
        }
        level--;

        print_each_sub(declaration.Content->instructions, "Instructions:");
    }

    void operator()(ast::Destructor& declaration) const {
        std::cout << indent() << "Destructor" << std::endl;
        print_each_sub(declaration.Content->instructions, "Instructions:");
    }

    void operator()(ast::Struct& struct_) const {
        std::cout << indent() << "Structure declaration: " << struct_.Content->name << std::endl;
        level++;

        print_each_sub_non_variant(struct_.Content->members, "Members");
        print_each_sub_non_variant(struct_.Content->constructors, "Constructors");
        print_each_sub_non_variant(struct_.Content->destructors, "Destructors");
        print_each_sub_non_variant(struct_.Content->functions, "Functions");

        level--;
    }

    void operator()(ast::MemberDeclaration& declaration) const {
        std::cout << indent() << toStringType(declaration.Content->type)  << " " << declaration.Content->name << std::endl;
    }

    void operator()(ast::GlobalVariableDeclaration&) const {
        std::cout << indent() << "Global Variable" << std::endl;
    }

    void operator()(ast::GlobalArrayDeclaration&) const {
        std::cout << indent() << "Global Array" << std::endl;
    }

    void operator()(ast::New& new_) const {
        std::cout << indent() << "New " << toStringType(new_.Content->type) << std::endl;
    }

    void operator()(ast::Delete& delete_) const {
        std::cout << indent() << "Delete " << delete_.Content->variable_name << std::endl;
    }

    void operator()(ast::For& for_) const {
        print_each_sub(for_.Content->instructions, "For");
    }

    void operator()(ast::Foreach& for_) const {
        print_each_sub(for_.Content->instructions, "Foreach");
    }

    void operator()(ast::ForeachIn& for_) const {
        print_each_sub(for_.Content->instructions, "Foreach In");
    }

    void operator()(ast::Switch& switch_) const {
        std::cout << indent() << "Switch " << std::endl;

        ++level;

        print_sub(switch_.Content->value, "Value");

        for(auto& case_ : switch_.Content->cases){
            visit_non_variant(*this, case_);
        }

        if(switch_.Content->default_case){
            visit_non_variant(*this, *switch_.Content->default_case);
        }

        --level;
    }

    void operator()(ast::SwitchCase& switch_case) const {
        std::cout << indent() << "Case" << std::endl;

        ++level;

        print_sub(switch_case.value, "Value");
        print_each_sub(switch_case.instructions, "Instructions");

        --level;
    }

    void operator()(ast::DefaultCase& default_case) const {
        print_each_sub(default_case.instructions, "Default Case");
    }

    void operator()(ast::While& while_) const {
        std::cout << indent() << "While" << std::endl;
        print_sub(while_.Content->condition, "Condition:");
        print_each_sub(while_.Content->instructions, "Instructions:");
    }

    void operator()(ast::DoWhile& while_) const {
        std::cout << indent() << "Do while" << std::endl;
        print_sub(while_.Content->condition, "Condition:");
        print_each_sub(while_.Content->instructions, "Instructions:");
    }

    void operator()(ast::Swap&) const {
        std::cout << indent() << "Swap" << std::endl;
    }

    void operator()(ast::If& if_) const {
        std::cout << indent() << "If" << std::endl;

        print_sub(if_.Content->condition, "Condition");
        print_each_sub(if_.Content->instructions, "Instructions");

        for(auto& else_if : if_.Content->elseIfs){
            std::cout << indent() << "ElseIf" << std::endl;

            print_sub(else_if.condition, "Condition");
            print_each_sub(else_if.instructions, "Instructions");
        }

        if(if_.Content->else_){
            std::cout << indent() << "Else" << std::endl;

            print_each_sub((*if_.Content->else_).instructions, "Instructions");
        }
    }

    void operator()(ast::FunctionCall& call) const {
        std::cout << indent() << "FunctionCall " << call.Content->functionName << std::endl;
        print_each_sub(call.Content->values);
    }

    void operator()(ast::MemberFunctionCall& call) const {
        std::cout << indent() << "Member FunctionCall " << call.Content->object_name << "." << call.Content->function_name << std::endl;
        print_each_sub(call.Content->values);
    }

    void operator()(ast::BuiltinOperator& builtin) const {
        std::cout << indent() << "Builtin Operator " << (int) builtin.Content->type << std::endl;
        print_each_sub(builtin.Content->values);
    }

    void operator()(ast::VariableDeclaration& declaration) const {
        std::cout << indent() << "Variable declaration [" << declaration.Content->variableName << "]" << std::endl;

        if(declaration.Content->value){
            print_sub(*declaration.Content->value);
        }
    }

    void operator()(ast::ArrayDeclaration&) const {
        std::cout << indent() << "Array declaration" << std::endl;
    }

    void operator()(ast::SuffixOperation& op) const {
        std::cout << indent() << op.Content->variableName << "(suffix)" << (int)op.Content->op << std::endl;
    }

    void operator()(ast::PrefixOperation& op) const {
        std::cout << indent() << (int)op.Content->op << "(prefix)" << op.Content->variableName << std::endl;
    }

    void operator()(ast::Assignment& assign) const {
        std::cout << indent() << "Assignment [operator = " << static_cast<int>(assign.Content->op) << " ] " << std::endl;

        print_sub(assign.Content->left_value, "Left Value");
        print_sub(assign.Content->value, "Right Value");
    }

    void operator()(ast::Ternary& ternary) const {
        std::cout << indent() << "Ternary" << std::endl;

        print_sub(ternary.Content->condition, "Condition");
        print_sub(ternary.Content->true_value, "True Value");
        print_sub(ternary.Content->false_value, "False Value");
    }

    void operator()(ast::Return& return_) const {
        print_sub(return_.Content->value, "Function Return");
    }

    void operator()(ast::Litteral& litteral) const {
        std::cout << indent() << "Litteral [" << litteral.value << "]" << std::endl;
    }

    void operator()(ast::Integer& integer) const {
        std::cout << indent() << "Integer [" << integer.value << "]" << std::endl;
    }

    void operator()(ast::IntegerSuffix& integer) const {
        std::cout << indent() << "Float (suffix) [" << integer.value << "f]" << std::endl;
    }

    void operator()(ast::Float& float_) const {
        std::cout << indent() << "Float [" << float_.value << "]" << std::endl;
    }

    void operator()(ast::True&) const {
        std::cout << indent() << "true" << std::endl;
    }

    void operator()(ast::Null&) const {
        std::cout << indent() << "null" << std::endl;
    }

    void operator()(ast::False&) const {
        std::cout << indent() << "false" << std::endl;
    }

    void operator()(ast::VariableValue& value) const {
        std::cout << indent() << "Variable " << value.Content->var->name();

        for(auto& member : value.Content->memberNames){
            std::cout << "." << member;
        }

        std::cout << std::endl;
    }

    void operator()(ast::DereferenceValue& value) const {
        std::cout << indent() << "Dereference Variable Value" << std::endl;;

        print_sub(value.Content->ref, "Left Value");
    }

    void operator()(ast::ArrayValue& value) const {
        std::cout << indent() << "Array value [" << value.Content->arrayName << "]" << std::endl;
        print_sub(value.Content->indexValue);
    }

    void operator()(ast::Expression& value) const {
        std::cout << indent() << "Expression [" << value.Content->operations.size() << "]" << std::endl;
        ++level;
        visit(*this, value.Content->first);
        for(auto& operation : value.Content->operations){
            std::cout << indent() << (int) operation.get<0>() << std::endl;
            visit(*this, operation.get<1>());
        }
        --level;
    }

    void operator()(ast::Unary& value) const {
        std::cout << indent() << "Unary " << static_cast<int>(value.Content->op) << std::endl;
        print_sub(value.Content->value);
    }

    void operator()(ast::Cast& cast) const {
        std::cout << indent() << "Cast " << std::endl;
        std::cout << indent() << "\tType: " << toStringType(cast.Content->type) << std::endl;
        print_sub(cast.Content->value);
    }
};

} //end of anonymous namespace

void ast::Printer::print(SourceFile& program){
    DebugVisitor visitor;
    visit_non_variant(visitor, program);
}
<commit_msg>Enhance printer to handle passing values to new<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>

#include "ast/Printer.hpp"

#include "variant.hpp"
#include "assert.hpp"
#include "VisitorUtils.hpp"
#include "Variable.hpp"

using namespace eddic;

namespace {

std::string toStringType(ast::Type type){
    if(auto* ptr = boost::get<ast::SimpleType>(&type)){
        return ptr->type;
    } else if(auto* ptr = boost::get<ast::ArrayType>(&type)){
        return ptr->type + "[]";
    } else {
        ASSERT_PATH_NOT_TAKEN("Unhandled type");
    }
}

struct DebugVisitor : public boost::static_visitor<> {
    mutable int level = 0;

    std::string indent() const {
        std::string acc = "";
        for(int i = 0; i < level; ++i){
            acc += "    ";
        }
        return acc;
    }

    template<typename Container>
    void print_each_sub(Container& container) const {
        level++;
        visit_each(*this, container);
        level--;
    }

    template<typename Container>
    void print_each_sub(Container& container, const std::string& title) const {
        std::cout << indent() << title << std::endl;
        print_each_sub(container);
    }

    template<typename Container>
    void print_each_sub_non_variant(Container& container) const {
        level++;
        visit_each_non_variant(*this, container);
        level--;
    }

    template<typename Container>
    void print_each_sub_non_variant(Container& container, const std::string& title) const {
        std::cout << indent() << title << std::endl;
        print_each_sub_non_variant(container);
    }

    template<typename Container>
    void print_sub(Container& container) const {
        level++;
        visit(*this, container);
        level--;
    }

    template<typename Container>
    void print_sub(Container& container, const std::string& title) const {
        std::cout << indent() << title << std::endl;
        print_sub(container);
    }

    void operator()(ast::SourceFile& program) const {
        print_each_sub(program.Content->blocks, "SourceFile");
    }

    void operator()(ast::Import& import) const {
        std::cout << indent() << "include \"" << import.file << "\"" << std::endl;
    }

    void operator()(ast::StandardImport& import) const {
        std::cout << indent() << "include <" << import.header << ">" << std::endl;
    }

    void operator()(ast::FunctionDeclaration& declaration) const {
        std::cout << indent() << "Function " << declaration.Content->functionName << std::endl;

        std::cout << indent() << "Parameters:" << std::endl;
        level++;
        for(auto param : declaration.Content->parameters){
            std::cout << indent() << param.parameterName << std::endl;
        }
        level--;

        print_each_sub(declaration.Content->instructions, "Instructions:");
    }

    void operator()(ast::Constructor& declaration) const {
        std::cout << indent() << "Constructor" << std::endl;

        std::cout << indent() << "Parameters:" << std::endl;
        level++;
        for(auto param : declaration.Content->parameters){
            std::cout << indent() << param.parameterName << std::endl;
        }
        level--;

        print_each_sub(declaration.Content->instructions, "Instructions:");
    }

    void operator()(ast::Destructor& declaration) const {
        std::cout << indent() << "Destructor" << std::endl;
        print_each_sub(declaration.Content->instructions, "Instructions:");
    }

    void operator()(ast::Struct& struct_) const {
        std::cout << indent() << "Structure declaration: " << struct_.Content->name << std::endl;
        level++;

        print_each_sub_non_variant(struct_.Content->members, "Members");
        print_each_sub_non_variant(struct_.Content->constructors, "Constructors");
        print_each_sub_non_variant(struct_.Content->destructors, "Destructors");
        print_each_sub_non_variant(struct_.Content->functions, "Functions");

        level--;
    }

    void operator()(ast::MemberDeclaration& declaration) const {
        std::cout << indent() << toStringType(declaration.Content->type)  << " " << declaration.Content->name << std::endl;
    }

    void operator()(ast::GlobalVariableDeclaration&) const {
        std::cout << indent() << "Global Variable" << std::endl;
    }

    void operator()(ast::GlobalArrayDeclaration&) const {
        std::cout << indent() << "Global Array" << std::endl;
    }

    void operator()(ast::New& new_) const {
        std::cout << indent() << "New " << toStringType(new_.Content->type) << std::endl;
        print_each_sub(new_.Content->values, "Value");
    }

    void operator()(ast::Delete& delete_) const {
        std::cout << indent() << "Delete " << delete_.Content->variable_name << std::endl;
    }

    void operator()(ast::For& for_) const {
        print_each_sub(for_.Content->instructions, "For");
    }

    void operator()(ast::Foreach& for_) const {
        print_each_sub(for_.Content->instructions, "Foreach");
    }

    void operator()(ast::ForeachIn& for_) const {
        print_each_sub(for_.Content->instructions, "Foreach In");
    }

    void operator()(ast::Switch& switch_) const {
        std::cout << indent() << "Switch " << std::endl;

        ++level;

        print_sub(switch_.Content->value, "Value");

        for(auto& case_ : switch_.Content->cases){
            visit_non_variant(*this, case_);
        }

        if(switch_.Content->default_case){
            visit_non_variant(*this, *switch_.Content->default_case);
        }

        --level;
    }

    void operator()(ast::SwitchCase& switch_case) const {
        std::cout << indent() << "Case" << std::endl;

        ++level;

        print_sub(switch_case.value, "Value");
        print_each_sub(switch_case.instructions, "Instructions");

        --level;
    }

    void operator()(ast::DefaultCase& default_case) const {
        print_each_sub(default_case.instructions, "Default Case");
    }

    void operator()(ast::While& while_) const {
        std::cout << indent() << "While" << std::endl;
        print_sub(while_.Content->condition, "Condition:");
        print_each_sub(while_.Content->instructions, "Instructions:");
    }

    void operator()(ast::DoWhile& while_) const {
        std::cout << indent() << "Do while" << std::endl;
        print_sub(while_.Content->condition, "Condition:");
        print_each_sub(while_.Content->instructions, "Instructions:");
    }

    void operator()(ast::Swap&) const {
        std::cout << indent() << "Swap" << std::endl;
    }

    void operator()(ast::If& if_) const {
        std::cout << indent() << "If" << std::endl;

        print_sub(if_.Content->condition, "Condition");
        print_each_sub(if_.Content->instructions, "Instructions");

        for(auto& else_if : if_.Content->elseIfs){
            std::cout << indent() << "ElseIf" << std::endl;

            print_sub(else_if.condition, "Condition");
            print_each_sub(else_if.instructions, "Instructions");
        }

        if(if_.Content->else_){
            std::cout << indent() << "Else" << std::endl;

            print_each_sub((*if_.Content->else_).instructions, "Instructions");
        }
    }

    void operator()(ast::FunctionCall& call) const {
        std::cout << indent() << "FunctionCall " << call.Content->functionName << std::endl;
        print_each_sub(call.Content->values);
    }

    void operator()(ast::MemberFunctionCall& call) const {
        std::cout << indent() << "Member FunctionCall " << call.Content->object_name << "." << call.Content->function_name << std::endl;
        print_each_sub(call.Content->values);
    }

    void operator()(ast::BuiltinOperator& builtin) const {
        std::cout << indent() << "Builtin Operator " << (int) builtin.Content->type << std::endl;
        print_each_sub(builtin.Content->values);
    }

    void operator()(ast::VariableDeclaration& declaration) const {
        std::cout << indent() << "Variable declaration [" << declaration.Content->variableName << "]" << std::endl;

        if(declaration.Content->value){
            print_sub(*declaration.Content->value);
        }
    }

    void operator()(ast::ArrayDeclaration&) const {
        std::cout << indent() << "Array declaration" << std::endl;
    }

    void operator()(ast::SuffixOperation& op) const {
        std::cout << indent() << op.Content->variableName << "(suffix)" << (int)op.Content->op << std::endl;
    }

    void operator()(ast::PrefixOperation& op) const {
        std::cout << indent() << (int)op.Content->op << "(prefix)" << op.Content->variableName << std::endl;
    }

    void operator()(ast::Assignment& assign) const {
        std::cout << indent() << "Assignment [operator = " << static_cast<int>(assign.Content->op) << " ] " << std::endl;

        print_sub(assign.Content->left_value, "Left Value");
        print_sub(assign.Content->value, "Right Value");
    }

    void operator()(ast::Ternary& ternary) const {
        std::cout << indent() << "Ternary" << std::endl;

        print_sub(ternary.Content->condition, "Condition");
        print_sub(ternary.Content->true_value, "True Value");
        print_sub(ternary.Content->false_value, "False Value");
    }

    void operator()(ast::Return& return_) const {
        print_sub(return_.Content->value, "Function Return");
    }

    void operator()(ast::Litteral& litteral) const {
        std::cout << indent() << "Litteral [" << litteral.value << "]" << std::endl;
    }

    void operator()(ast::Integer& integer) const {
        std::cout << indent() << "Integer [" << integer.value << "]" << std::endl;
    }

    void operator()(ast::IntegerSuffix& integer) const {
        std::cout << indent() << "Float (suffix) [" << integer.value << "f]" << std::endl;
    }

    void operator()(ast::Float& float_) const {
        std::cout << indent() << "Float [" << float_.value << "]" << std::endl;
    }

    void operator()(ast::True&) const {
        std::cout << indent() << "true" << std::endl;
    }

    void operator()(ast::Null&) const {
        std::cout << indent() << "null" << std::endl;
    }

    void operator()(ast::False&) const {
        std::cout << indent() << "false" << std::endl;
    }

    void operator()(ast::VariableValue& value) const {
        std::cout << indent() << "Variable " << value.Content->var->name();

        for(auto& member : value.Content->memberNames){
            std::cout << "." << member;
        }

        std::cout << std::endl;
    }

    void operator()(ast::DereferenceValue& value) const {
        std::cout << indent() << "Dereference Variable Value" << std::endl;;

        print_sub(value.Content->ref, "Left Value");
    }

    void operator()(ast::ArrayValue& value) const {
        std::cout << indent() << "Array value [" << value.Content->arrayName << "]" << std::endl;
        print_sub(value.Content->indexValue);
    }

    void operator()(ast::Expression& value) const {
        std::cout << indent() << "Expression [" << value.Content->operations.size() << "]" << std::endl;
        ++level;
        visit(*this, value.Content->first);
        for(auto& operation : value.Content->operations){
            std::cout << indent() << (int) operation.get<0>() << std::endl;
            visit(*this, operation.get<1>());
        }
        --level;
    }

    void operator()(ast::Unary& value) const {
        std::cout << indent() << "Unary " << static_cast<int>(value.Content->op) << std::endl;
        print_sub(value.Content->value);
    }

    void operator()(ast::Cast& cast) const {
        std::cout << indent() << "Cast " << std::endl;
        std::cout << indent() << "\tType: " << toStringType(cast.Content->type) << std::endl;
        print_sub(cast.Content->value);
    }
};

} //end of anonymous namespace

void ast::Printer::print(SourceFile& program){
    DebugVisitor visitor;
    visit_non_variant(visitor, program);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003-2005 The Regents of The University of Michigan
 * 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 the copyright holders nor the names of its
 * contributors 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.
 *
 * Authors: Nathan Binkert
 */

#ifndef __HASHMAP_HH__
#define __HASHMAP_HH__

#if defined(__GNUC__) && __GNUC__ >= 3
#include <ext/hash_map>
#else
#include <hash_map>
#endif

#include <string>

#include "sim/host.hh"

#if defined(__GNUC__) && __GNUC__ >= 3
    #define __hash_namespace __gnu_cxx
#else
    #define __hash_namespace std
#endif

namespace m5 {
    using ::__hash_namespace::hash_multimap;
    using ::__hash_namespace::hash_map;
    using ::__hash_namespace::hash;
}

///////////////////////////////////
// Some default Hashing Functions
//

namespace __hash_namespace {
#if (__APPLE__) || !defined(__LP64__) && !defined(__alpha__) && !defined(__SUNPRO_CC)
    template<>
    struct hash<uint64_t> {
        size_t operator()(uint64_t r) const {
            return r;
        }
    };

    template<>
    struct hash<int64_t> {
        size_t operator()(int64_t r) const {
            return r;
        };
    };
#endif

    template<>
    struct hash<std::string> {
        size_t operator()(const std::string &s) const {
            return(__stl_hash_string(s.c_str()));
        }
    };
}

#endif // __HASHMAP_HH__
<commit_msg>Make non Apple compilation work again. Ali may have to refix this.<commit_after>/*
 * Copyright (c) 2003-2005 The Regents of The University of Michigan
 * 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 the copyright holders nor the names of its
 * contributors 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.
 *
 * Authors: Nathan Binkert
 */

#ifndef __HASHMAP_HH__
#define __HASHMAP_HH__

#if defined(__GNUC__) && __GNUC__ >= 3
#include <ext/hash_map>
#else
#include <hash_map>
#endif

#include <string>

#include "sim/host.hh"

#if defined(__GNUC__) && __GNUC__ >= 3
    #define __hash_namespace __gnu_cxx
#else
    #define __hash_namespace std
#endif

namespace m5 {
    using ::__hash_namespace::hash_multimap;
    using ::__hash_namespace::hash_map;
    using ::__hash_namespace::hash;
}

///////////////////////////////////
// Some default Hashing Functions
//

namespace __hash_namespace {
#if defined(__APPLE__) || !defined(__LP64__) && !defined(__alpha__) && !defined(__SUNPRO_CC)
    template<>
    struct hash<uint64_t> {
        size_t operator()(uint64_t r) const {
            return r;
        }
    };

    template<>
    struct hash<int64_t> {
        size_t operator()(int64_t r) const {
            return r;
        };
    };
#endif

    template<>
    struct hash<std::string> {
        size_t operator()(const std::string &s) const {
            return(__stl_hash_string(s.c_str()));
        }
    };
}

#endif // __HASHMAP_HH__
<|endoftext|>


<commit_before>/*
 Copyright (c) 2016,
 Dan Bethell, Johannes Saam, Vahan Sosoyan, Brian Scherbinski.
 All rights reserved. See Copyright.txt for more details.
 */

#include "FrameBuffer.h"

using namespace aton;

// Lightweight colour pixel class
RenderColour::RenderColour() { _val[0] = _val[1] = _val[2] = 0.f; }

float& RenderColour::operator[](int i){ return _val[i]; }
const float& RenderColour::operator[](int i) const { return _val[i]; }

// Lightweight alpha pixel class
RenderAlpha::RenderAlpha() { _val = 1.f; }

float& RenderAlpha::operator[](int i){ return _val; }
const float& RenderAlpha::operator[](int i) const { return _val; }

// Our image buffer class
RenderBuffer::RenderBuffer(): _width(0), _height(0) {}

void RenderBuffer::initBuffer(const unsigned int width,
                              const unsigned int height,
                              const bool empty,
                              const bool alpha)
{
    _width = width;
    _height = height;
    if (!empty)
    {
        _colour_data.resize(_width * _height);
        if (alpha)
            _alpha_data.resize(_width * _height);
    }
}

RenderColour& RenderBuffer::getColour(unsigned int x, unsigned int y)
{
    unsigned int index = (_width * y) + x;
    return _colour_data[index];
}

const RenderColour& RenderBuffer::getColour(unsigned int x, unsigned int y) const
{
    unsigned int index = (_width * y) + x;
    return _colour_data[index];
}

RenderAlpha& RenderBuffer::getAlpha(unsigned int x, unsigned int y)
{
    unsigned int index = (_width * y) + x;
    return _alpha_data[index];
}

const RenderAlpha& RenderBuffer::getAlpha(unsigned int x, unsigned int y) const
{
    unsigned int index = (_width * y) + x;
    return _alpha_data[index];
}

unsigned int RenderBuffer::width() { return _width; }
unsigned int RenderBuffer::height() { return _height; }

bool RenderBuffer::empty()
{
    return _colour_data.empty();
}

// Framebuffer main class
FrameBuffer::FrameBuffer(double currentFrame,
                         int w,
                         int h): _frame(0),
                                 _bucket(0,0,1,1),
                                 _progress(0),
                                 _time(0),
                                 _ram(0),
                                 _pram(0),
                                _ready(false)
{
    _frame = currentFrame;
    _width = w;
    _height = h;
}

// Add new buffer
void FrameBuffer::addBuffer(const char * aov, int spp)
{
    RenderBuffer buffer;

    if (spp < 4)
        buffer.initBuffer(_width, _height);
    else
        buffer.initBuffer(_width, _height, false, true);

    _buffers.push_back(buffer);
    _aovs.push_back(aov);
}

// Get buffer object
RenderBuffer& FrameBuffer::getBuffer(int index)
{
    return _buffers[index];
}

// Get buffer object
const RenderBuffer& FrameBuffer::getBuffer(int index) const
{
    return _buffers[index];
}

// Get the current buffer index
int FrameBuffer::getBufferIndex(Channel z)
{
    int b_index = 0;

    if (!_aovs.empty())
    {
        std::string layer = getLayerName(z);
        if (layer.compare(ChannelStr::rgb) != 0)
        {
            for(std::vector<std::string>::iterator it = _aovs.begin(); it != _aovs.end(); ++it)
            {
                if (it->compare(layer) == 0)
                {
                    b_index = static_cast<int>(it - _aovs.begin());
                    break;
                }
                else if ( it->compare(ChannelStr::Z) == 0 && layer.compare(ChannelStr::depth) == 0 )
                {
                    b_index = static_cast<int>(it - _aovs.begin());
                    break;
                }
            }
        }
    }
    return b_index;
}

// Get the current buffer index
int FrameBuffer::getBufferIndex(const char * aovName)
{
    int b_index = 0;

    if (!_aovs.empty())
        for(std::vector<std::string>::iterator it = _aovs.begin(); it != _aovs.end(); ++it)
        {
            if (it->compare(aovName) == 0)
            {
                b_index = static_cast<int>(it - _aovs.begin());
                break;
            }
        }

    return b_index;
}

// Get N buffer/aov name name
std::string FrameBuffer::getBufferName(size_t index)
{
    std::string bufferName = "";
    if (!_aovs.empty())
        bufferName = _aovs[index];
    return bufferName;
}

// Get last buffer/aov name
std::string FrameBuffer::getFirstBufferName()
{
    std::string bufferName = "";
    if (!_aovs.empty())
        bufferName = _aovs.front();
    return bufferName;
}

// Compare buffers with given buffer/aov names and dimensoions
int FrameBuffer::compareAll(int width, int height, std::vector<std::string> aovs)
{
    if (!_buffers.empty() && !_aovs.empty())
    {
        if (aovs == _aovs &&
            width ==_buffers[0].width() &&
            height ==_buffers[0].height())
            return 0;
        else if (width == _buffers[0].width() &&
                 height == _buffers[0].height())
            return 1;
        else
            return 2;
    }
    else
        return -1;
}

// Clear buffers and aovs
void FrameBuffer::clearAll()
{
    _buffers.resize(0);
    _aovs.resize(0);
}

// Check if the given buffer/aov name name is exist
bool FrameBuffer::bufferNameExists(const char * aovName)
{
    return std::find(_aovs.begin(),
                     _aovs.end(),
                     aovName) != _aovs.end();
}

// Get width of the buffer
int FrameBuffer::getWidth() { return _width; }

// Get height of the buffer
int FrameBuffer::getHeight() { return _height; }

// Get size of the buffers aka AOVs count
size_t FrameBuffer::size() { return _aovs.size(); }

// Resize the buffers
void FrameBuffer::resize(size_t s)
{
    _buffers.resize(s);
    _aovs.resize(s);
}

// Set current bucket BBox for asapUpdate()
void FrameBuffer::setBucketBBox(int x, int y, int r, int t)
{
    _bucket.set(x, y, r, t);
}

// Get current bucket BBox for asapUpdate()
Box FrameBuffer::getBucketBBox() { return _bucket; }

// Set status parameters
void FrameBuffer::setProgress(int progress) { _progress = progress; }
void FrameBuffer::setRAM(long long ram)
{
    _pram = _ram < ram ? ram : _ram;
    _ram = ram;
}
void FrameBuffer::setTime(int time) { _time = time; }

// Get status parameters
int FrameBuffer::getProgress() { return _progress; }
long long FrameBuffer::getRAM() { return _ram; }
long long FrameBuffer::getPRAM() { return _pram; }
int FrameBuffer::getTime() { return _time; }

// Set Arnold core version
void FrameBuffer::setArnoldVersion(int version)
{
    // Construct a string from the version number passed
    int archV = (version%10000000)/1000000;
    int majorV = (version%1000000)/10000;
    int minorV = (version%10000)/100;
    int fixV = version%100;
    _version = (boost::format("%s.%s.%s.%s")%archV%majorV%minorV%fixV).str();
}

// Get Arnold core version
std::string FrameBuffer::getArnoldVersion() { return _version; }

// Get the frame number of this framebuffer
double FrameBuffer::getFrame() { return _frame; }

// Check if this framebuffer is empty
bool FrameBuffer::empty() { return (_buffers.empty() && _aovs.empty()) ; }

// To keep False while writing the buffer
void FrameBuffer::ready(bool ready) { _ready = ready; }
bool FrameBuffer::isReady() { return _ready; }
<commit_msg>Update FrameBuffer.cpp<commit_after>/*
 Copyright (c) 2016,
 Dan Bethell, Johannes Saam, Vahan Sosoyan, Brian Scherbinski.
 All rights reserved. See Copyright.txt for more details.
 */

#include "FrameBuffer.h"

using namespace aton;

// Lightweight colour pixel class
RenderColour::RenderColour() { _val[0] = _val[1] = _val[2] = 0.f; }

float& RenderColour::operator[](int i){ return _val[i]; }
const float& RenderColour::operator[](int i) const { return _val[i]; }

// Lightweight alpha pixel class
RenderAlpha::RenderAlpha() { _val = 1.f; }

float& RenderAlpha::operator[](int i){ return _val; }
const float& RenderAlpha::operator[](int i) const { return _val; }

// Our image buffer class
RenderBuffer::RenderBuffer(): _width(0), _height(0) {}

void RenderBuffer::initBuffer(const unsigned int width,
                              const unsigned int height,
                              const bool alpha)
{
    _width = width;
    _height = height;

    _colour_data.resize(_width * _height);
    if (alpha)
        _alpha_data.resize(_width * _height);
}

RenderColour& RenderBuffer::getColour(unsigned int x, unsigned int y)
{
    unsigned int index = (_width * y) + x;
    return _colour_data[index];
}

const RenderColour& RenderBuffer::getColour(unsigned int x, unsigned int y) const
{
    unsigned int index = (_width * y) + x;
    return _colour_data[index];
}

RenderAlpha& RenderBuffer::getAlpha(unsigned int x, unsigned int y)
{
    unsigned int index = (_width * y) + x;
    return _alpha_data[index];
}

const RenderAlpha& RenderBuffer::getAlpha(unsigned int x, unsigned int y) const
{
    unsigned int index = (_width * y) + x;
    return _alpha_data[index];
}

unsigned int RenderBuffer::width() { return _width; }
unsigned int RenderBuffer::height() { return _height; }

bool RenderBuffer::empty()
{
    return _colour_data.empty();
}

// Framebuffer main class
FrameBuffer::FrameBuffer(double currentFrame,
                         int w,
                         int h): _frame(0),
                                 _bucket(0,0,1,1),
                                 _progress(0),
                                 _time(0),
                                 _ram(0),
                                 _pram(0),
                                 _ready(false)
{
    _frame = currentFrame;
    _width = w;
    _height = h;
}

// Add new buffer
void FrameBuffer::addBuffer(const char * aov, int spp)
{
    RenderBuffer buffer;

    if (spp < 4)
        buffer.initBuffer(_width, _height);
    else
        buffer.initBuffer(_width, _height, true);

    _buffers.push_back(buffer);
    _aovs.push_back(aov);
}

// Get buffer object
RenderBuffer& FrameBuffer::getBuffer(int index)
{
    return _buffers[index];
}

// Get buffer object
const RenderBuffer& FrameBuffer::getBuffer(int index) const
{
    return _buffers[index];
}

// Get the current buffer index
int FrameBuffer::getBufferIndex(Channel z)
{
    int b_index = 0;

    if (!_aovs.empty())
    {
        std::string layer = getLayerName(z);
        if (layer.compare(ChannelStr::rgb) != 0)
        {
            for(std::vector<std::string>::iterator it = _aovs.begin(); it != _aovs.end(); ++it)
            {
                if (it->compare(layer) == 0)
                {
                    b_index = static_cast<int>(it - _aovs.begin());
                    break;
                }
                else if ( it->compare(ChannelStr::Z) == 0 && layer.compare(ChannelStr::depth) == 0 )
                {
                    b_index = static_cast<int>(it - _aovs.begin());
                    break;
                }
            }
        }
    }
    return b_index;
}

// Get the current buffer index
int FrameBuffer::getBufferIndex(const char * aovName)
{
    int b_index = 0;

    if (!_aovs.empty())
        for(std::vector<std::string>::iterator it = _aovs.begin(); it != _aovs.end(); ++it)
        {
            if (it->compare(aovName) == 0)
            {
                b_index = static_cast<int>(it - _aovs.begin());
                break;
            }
        }
    return b_index;
}

// Get N buffer/aov name name
std::string FrameBuffer::getBufferName(size_t index)
{
    std::string bufferName = "";
    if (!_aovs.empty())
        bufferName = _aovs[index];
    return bufferName;
}

// Get last buffer/aov name
std::string FrameBuffer::getFirstBufferName()
{
    std::string bufferName = "";
    if (!_aovs.empty())
        bufferName = _aovs.front();
    return bufferName;
}

// Compare buffers with given buffer/aov names and dimensoions
int FrameBuffer::compareAll(int width, int height, std::vector<std::string> aovs)
{
    if (!_buffers.empty() && !_aovs.empty())
    {
        if (aovs == _aovs &&
            width ==_buffers[0].width() &&
            height ==_buffers[0].height())
            return 0;
        else if (width == _buffers[0].width() &&
                 height == _buffers[0].height())
            return 1;
        else
            return 2;
    }
    else
        return -1;
}

// Clear buffers and aovs
void FrameBuffer::clearAll()
{
    _buffers.resize(0);
    _aovs.resize(0);
}

// Check if the given buffer/aov name name is exist
bool FrameBuffer::bufferNameExists(const char * aovName)
{
    return std::find(_aovs.begin(),
                     _aovs.end(),
                     aovName) != _aovs.end();
}

// Get width of the buffer
int FrameBuffer::getWidth() { return _width; }

// Get height of the buffer
int FrameBuffer::getHeight() { return _height; }

// Get size of the buffers aka AOVs count
size_t FrameBuffer::size() { return _aovs.size(); }

// Resize the buffers
void FrameBuffer::resize(size_t s)
{
    _buffers.resize(s);
    _aovs.resize(s);
}

// Set current bucket BBox for asapUpdate()
void FrameBuffer::setBucketBBox(int x, int y, int r, int t)
{
    _bucket.set(x, y, r, t);
}

// Get current bucket BBox for asapUpdate()
Box FrameBuffer::getBucketBBox() { return _bucket; }

// Set status parameters
void FrameBuffer::setProgress(int progress) { _progress = progress; }
void FrameBuffer::setRAM(long long ram)
{
    _pram = _ram < ram ? ram : _ram;
    _ram = ram;
}
void FrameBuffer::setTime(int time) { _time = time; }

// Get status parameters
int FrameBuffer::getProgress() { return _progress; }
long long FrameBuffer::getRAM() { return _ram; }
long long FrameBuffer::getPRAM() { return _pram; }
int FrameBuffer::getTime() { return _time; }

// Set Arnold core version
void FrameBuffer::setArnoldVersion(int version)
{
    // Construct a string from the version number passed
    int archV = (version%10000000)/1000000;
    int majorV = (version%1000000)/10000;
    int minorV = (version%10000)/100;
    int fixV = version%100;
    _version = (boost::format("%s.%s.%s.%s")%archV%majorV%minorV%fixV).str();
}

// Get Arnold core version
std::string FrameBuffer::getArnoldVersion() { return _version; }

// Get the frame number of this framebuffer
double FrameBuffer::getFrame() { return _frame; }

// Check if this framebuffer is empty
bool FrameBuffer::empty() { return (_buffers.empty() && _aovs.empty()) ; }

// To keep False while writing the buffer
void FrameBuffer::ready(bool ready) { _ready = ready; }
bool FrameBuffer::isReady() { return _ready; }
<|endoftext|>


<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa)
*
* 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 "Core.h"
#include "GetUserMedia.h"
#include "GetSources.h"
#include "MediaStream.h"
#include "Observers.h"
#include "MediaConstraints.h"

using namespace v8;
using namespace WebRTC;

void GetUserMedia::Init(Handle<Object> exports) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  NanScope();

  exports->Set(NanNew("getUserMedia"), NanNew<FunctionTemplate>(GetUserMedia::GetMediaStream)->GetFunction());
}

NAN_METHOD(GetSources::GetDevices) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  NanScope();

  rtc::scoped_refptr<webrtc::MediaStreamInterface> stream;
  rtc::scoped_refptr<MediaConstraints> constraints = MediaConstraints::New(args[0]);
  const char *error = 0;

  std::string audioId = constraints->AudioId();
  std::string videoId = constraints->VideoId();

  if (constraints->UseAudio() || constraints->UseVideo()) {
    webrtc::PeerConnectionFactoryInterface *factory = Core::GetFactory();

    if (factory) {
      stream = factory->CreateLocalMediaStream("stream");

      if (stream.get()) {
        if (constraints->UseAudio()) {
          rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track;

          if (audioId.empty()) {
            audio_track = GetSources::GetAudioSource(constraints);
          } else {
            audio_track = GetSources::GetAudioSource(audioId, constraints);
          }

          if (audio_track.get()) {
            stream->AddTrack(audio_track);
          } else {
            if (!audioId.empty()) {
              error = "Invalid Audio Input";
            }
          }
        }

        if (constraints->UseVideo()) {
          rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track;

          if (videoId.empty()) {
            video_track = GetSources::GetVideoSource(constraints);
          }
          else {
            video_track = GetSources::GetVideoSource(videoId, constraints);
          }

          if (video_track.get()) {
            stream->AddTrack(video_track);
          } else {
            if (!videoId.empty()) {
              error = "Invalid Video Input";
            }
          }
        }
      }
    }
  } else {
    error = "No Stream Inputs";
  }

  Handle<Value> argv[1];

  if (!error) {
    if (stream.get()) {
      argv[0] = MediaStream::New(stream);
    } else {
      error = "Invalid MediaStream";
    }
  }

  if (error) {
    if (!args[2].IsEmpty() && args[2]->IsFunction()) {
      Local<Function> onerror = Local<Function>::Cast(args[2]);
      argv[0] = NanError(error);

      onerror->Call(args.This(), 1, argv);
    } else {
      NanThrowError(error);
    }
  } else {
    if (!args[1].IsEmpty() && args[1]->IsFunction()) {
      Local<Function> onsuccess = Local<Function>::Cast(args[1]);
      onsuccess->Call(args.This(), 1, argv);
    }
  }
}
<commit_msg>Update GetUserMedia<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa)
*
* 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 "Core.h"
#include "GetUserMedia.h"
#include "GetSources.h"
#include "MediaStream.h"
#include "Observers.h"
#include "MediaConstraints.h"

using namespace v8;
using namespace WebRTC;

void GetUserMedia::Init(Handle<Object> exports) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  NanScope();

  exports->Set(NanNew("getUserMedia"), NanNew<FunctionTemplate>(GetUserMedia::GetMediaStream)->GetFunction());
}

NAN_METHOD(GetUserMedia::GetMediaStream) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  NanScope();

  rtc::scoped_refptr<webrtc::MediaStreamInterface> stream;
  rtc::scoped_refptr<MediaConstraints> constraints = MediaConstraints::New(args[0]);
  const char *error = 0;

  std::string audioId = constraints->AudioId();
  std::string videoId = constraints->VideoId();

  if (constraints->UseAudio() || constraints->UseVideo()) {
    webrtc::PeerConnectionFactoryInterface *factory = Core::GetFactory();

    if (factory) {
      stream = factory->CreateLocalMediaStream("stream");

      if (stream.get()) {
        if (constraints->UseAudio()) {
          rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track;

          if (audioId.empty()) {
            audio_track = GetSources::GetAudioSource(constraints);
          } else {
            audio_track = GetSources::GetAudioSource(audioId, constraints);
          }

          if (audio_track.get()) {
            stream->AddTrack(audio_track);
          } else {
            if (!audioId.empty()) {
              error = "Invalid Audio Input";
            }
          }
        }

        if (constraints->UseVideo()) {
          rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track;

          if (videoId.empty()) {
            video_track = GetSources::GetVideoSource(constraints);
          }
          else {
            video_track = GetSources::GetVideoSource(videoId, constraints);
          }

          if (video_track.get()) {
            stream->AddTrack(video_track);
          } else {
            if (!videoId.empty()) {
              error = "Invalid Video Input";
            }
          }
        }
      }
    }
  } else {
    error = "No Stream Inputs";
  }

  Handle<Value> argv[1];

  if (!error) {
    if (stream.get()) {
      argv[0] = MediaStream::New(stream);
    } else {
      error = "Invalid MediaStream";
    }
  }

  if (error) {
    if (!args[2].IsEmpty() && args[2]->IsFunction()) {
      Local<Function> onerror = Local<Function>::Cast(args[2]);
      argv[0] = NanError(error);

      onerror->Call(args.This(), 1, argv);
    } else {
      NanThrowError(error);
    }
  } else {
    if (!args[1].IsEmpty() && args[1]->IsFunction()) {
      Local<Function> onsuccess = Local<Function>::Cast(args[1]);
      onsuccess->Call(args.This(), 1, argv);
    }
  }
}
<|endoftext|>


<commit_before>//#include <ros/ros.h>
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <sstream>
#include <list>
#include <Eigen/Dense>
#include <sys/time.h>
#include <cmath>
#include <random>

using namespace std;

typedef Eigen::Vector2d V2d;

//function declarations
double computeAccuracy(vector<int> labels1, vector<int> labels2, map<int, int> matchings);
void birthDeathMotionProcesses(vector<V2d>& clusterCenters, vector<bool>& aliveClusters, double birthProbability, double deathProbability, double motionStdDev);
void generateData(vector<V2d> clusterCenters, vector<bool> aliveClusters, int nDataPerClusterPerStep, double likelihoodstd, vector<V2d>& clusterData, vector<int>& trueLabels);

//random number generator
mt19937 rng;//uses the same seed every time, 5489u

#include "vectorgraph.hpp"
#include "expgraph.hpp"

#include <dynmeans/kerndynmeans.hpp>
#include "maxmatching.hpp"

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

	//generates clusters that jump around on the domain R^2
	//they move stochastically with a normal distribution w/ std deviation 0.05
	//they die stochastically with probability 0.05 at each step
	//a cluster is created stochastically with probability 0.10 at each step in the area [0,1]x[0,1]

	//note: when computing accuracy, ***proper tracking is taken into account***
	//i.e. if true label 1 is matched to learned label 3, then that matching is fixed from that point forward
	//later pairings that attempt to match true label 1 to something else
	//or learned label 3 to something else are discarded

	//constants
	//play with these to change the data generation process
	double birthProbability = 0.10;
	double deathProbability = 0.05;
	double motionStdDev = 0.05;
	double clusterStdDev = 0.05;
	int nDataPerClusterPerStep = 15; // datapoints generated for each cluster per timestep
	int nSteps = 100;//run the experiment for nSteps steps
	int initialClusters = 4; //the number of clusters to start with

	//data structures for the cluster centers
	vector<V2d> clusterCenters;
	vector<bool> aliveClusters;

	//start with some number of initial clusters
	uniform_real_distribution<double> uniformDist01(0, 1);
	for (int i = 0; i < initialClusters; i++){
			V2d newCenter;
			newCenter(0) = uniformDist01(rng);
			newCenter(1) = uniformDist01(rng);
			clusterCenters.push_back(newCenter);
			aliveClusters.push_back(true);
	}

	//the Dynamic Means object
	//play with lambda/Q/tau to change Dynamic Means' performance
	double lambda = 0.05;
	double T_Q = 6.8;
	double K_tau = 1.01;
	double Q = lambda/T_Q;
	double tau = (T_Q*(K_tau-1.0)+1.0)/(T_Q-1.0);
	int nRestarts = 10;
	int nCoarsest = 20;
	KernDynMeans<VectorGraph> kdm(lambda, Q, tau, false);
	VectorGraph vgr;

	//run the experiment
	double cumulativeAccuracy = 0;//stores the accuracy accumulated for each step
	map<int, int> matchings;//stores the saved matchings from previous timesteps
							//enables proper label tracking (see note at line 27)
	for (int i = 0; i < nSteps; i++){
		//----------------------------
		//birth/death/motion processes
		//----------------------------
		cout << "Step " << i << ": Clusters undergoing birth/death/motion..." << endl;
		birthDeathMotionProcesses(clusterCenters, aliveClusters, birthProbability, deathProbability, motionStdDev);
		//------------------------------------------
		//generate the data for the current timestep
		//------------------------------------------
		cout << "Step " << i << ": Generating data from the clusters..." << endl;
		vector<V2d> clusterData;
		vector<int> trueLabels;
		generateData(clusterCenters, aliveClusters, nDataPerClusterPerStep, clusterStdDev, clusterData, trueLabels);

		//------------------------------------------
		//Take the vectors that we just created, and package them in the KD class defined above
		//------------------------------------------
		vgr.updateData(clusterData);

		//----------------------------
		//cluster using Dynamic Means
		//---------------------------
		vector<int> learnedLabels;
		vector<double> gammas;
		vector<int> prmlbls;
		double tTaken, obj;
		cout << "Step " << i << ": Clustering..." << endl;
		kdm.cluster(vgr, nRestarts, nCoarsest, learnedLabels, obj, gammas, prmlbls, tTaken);
		vgr.updateOldParameters(clusterData, learnedLabels, gammas, prmlbls);
		//----------------------------------------------------
		//calculate the accuracy via linear programming
		//including proper cluster label tracking (see above)
		//----------------------------------------------------
		matchings = getMaxMatchingConsistentWithOldMatching(learnedLabels, trueLabels, matchings);
		double acc = computeAccuracy(learnedLabels, trueLabels, matchings);
		cout << "Step " << i << ": Accuracy = " << acc <<  "\%" << endl;
		cumulativeAccuracy += acc;
	}
	cout << "Average Accuracy: " << cumulativeAccuracy/(double)nSteps << "\%" << endl;
	cout << "Done!" << endl;

	return 0;
}

//this function takes two label sets and a matching and outputs
//the accuracy of the labelling (assuming labels1 = learned, labels2 = true)
double computeAccuracy(vector<int> labels1, vector<int> labels2, map<int, int> matchings){
	if (labels1.size() != labels2.size()){
		cout << "Error: computeAccuracy requires labels1/labels2 to have the same size" << endl;
		return -1;
	}

	double acc = 0;
	for (int i = 0; i < labels1.size(); i++){
		if (matchings[labels1[i]] == labels2[i]){
			acc += 1.0;
		}
	}
	//compute the accuracy
	return 100.0*acc/(double)labels1.size();
}

//this function takes a set of cluster centers and runs them through a birth/death/motion model
void birthDeathMotionProcesses(vector<V2d>& clusterCenters, vector<bool>& aliveClusters, double birthProbability, double deathProbability, double motionStdDev){

	//distributions
	uniform_real_distribution<double> uniformDistAng(0, 2*M_PI);
	uniform_real_distribution<double> uniformDist01(0, 1);
	normal_distribution<double> transitionDistRadial(0, motionStdDev);

	for (int j = 0; j < clusterCenters.size(); j++){
		//for each cluster center, decide whether it dies
		if (aliveClusters[j] && uniformDist01(rng) < deathProbability){
			cout << "Cluster " << j << " died." << endl;
			aliveClusters[j] = false;
		} else if (aliveClusters[j]) {
			//if it survived, move it stochastically
			//radius sampled from normal
			double steplen = transitionDistRadial(rng);
			//angle sampled from uniform
			double stepang = uniformDistAng(rng);
			clusterCenters[j](0) += steplen*cos(stepang);
			clusterCenters[j](1) += steplen*sin(stepang);
			cout << "Cluster " << j << " moved to " << clusterCenters[j].transpose() << endl;
		}
	}
	//decide whether to create a new cluster
	if (uniformDist01(rng) < birthProbability || all_of(aliveClusters.begin(), aliveClusters.end(), [](bool b){return !b;}) ) {
		V2d newCenter;
		newCenter(0) = uniformDist01(rng);
		newCenter(1) = uniformDist01(rng);
		clusterCenters.push_back(newCenter);
		aliveClusters.push_back(true);
		cout << "Cluster " << clusterCenters.size()-1 << " was created at " << clusterCenters.back().transpose() << endl;
	}
}

//this function takes a set of cluster centers and generates data from them
void generateData(vector<V2d> clusterCenters, vector<bool> aliveClusters, int nDataPerClusterPerStep, double clusterStdDev, vector<V2d>& clusterData, vector<int>& trueLabels){

	//distributions
	uniform_real_distribution<double> uniformDistAng(0, 2*M_PI);
	normal_distribution<double> likelihoodDistRadial(0, clusterStdDev);
	//loop through alive centers, generate nDataPerClusterPerStep datapoints for each
	for (int j = 0; j < clusterCenters.size(); j++){
		if (aliveClusters[j]){
			for (int k = 0; k < nDataPerClusterPerStep; k++){
				V2d newData = clusterCenters[j];
				double len = likelihoodDistRadial(rng);
				double ang = uniformDistAng(rng);
				newData(0) += len*cos(ang);
				newData(1) += len*sin(ang);
				clusterData.push_back(newData);
				trueLabels.push_back(j);
			}
		}
	}
}

<commit_msg>minoredits to mainkdm<commit_after>//#include <ros/ros.h>
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <sstream>
#include <list>
#include <Eigen/Dense>
#include <sys/time.h>
#include <cmath>
#include <random>

using namespace std;

typedef Eigen::Vector2d V2d;

//function declarations
double computeAccuracy(vector<int> labels1, vector<int> labels2, map<int, int> matchings);
void birthDeathMotionProcesses(vector<V2d>& clusterCenters, vector<bool>& aliveClusters, double birthProbability, double deathProbability, double motionStdDev);
void generateData(vector<V2d> clusterCenters, vector<bool> aliveClusters, int nDataPerClusterPerStep, double likelihoodstd, vector<V2d>& clusterData, vector<int>& trueLabels);

//random number generator
mt19937 rng;//uses the same seed every time, 5489u

#include "vectorgraph.hpp"
#include "expgraph.hpp"

#include <dynmeans/kerndynmeans.hpp>
#include "maxmatching.hpp"

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

	//generates clusters that jump around on the domain R^2
	//they move stochastically with a normal distribution w/ std deviation 0.05
	//they die stochastically with probability 0.05 at each step
	//a cluster is created stochastically with probability 0.10 at each step in the area [0,1]x[0,1]

	//note: when computing accuracy, ***proper tracking is taken into account***
	//i.e. if true label 1 is matched to learned label 3, then that matching is fixed from that point forward
	//later pairings that attempt to match true label 1 to something else
	//or learned label 3 to something else are discarded

	//constants
	//play with these to change the data generation process
	double birthProbability = 0.10;
	double deathProbability = 0.05;
	double motionStdDev = 0.05;
	double clusterStdDev = 0.05;
	int nDataPerClusterPerStep = 15; // datapoints generated for each cluster per timestep
	int nSteps = 100;//run the experiment for nSteps steps
	int initialClusters = 4; //the number of clusters to start with

	//data structures for the cluster centers
	vector<V2d> clusterCenters;
	vector<bool> aliveClusters;

	//start with some number of initial clusters
	uniform_real_distribution<double> uniformDist01(0, 1);
	for (int i = 0; i < initialClusters; i++){
			V2d newCenter;
			newCenter(0) = uniformDist01(rng);
			newCenter(1) = uniformDist01(rng);
			clusterCenters.push_back(newCenter);
			aliveClusters.push_back(true);
	}

	//the Dynamic Means object
	//play with lambda/Q/tau to change Dynamic Means' performance
	double lambda = 0.05;
	double T_Q = 6.8;
	double K_tau = 1.01;
	double Q = lambda/T_Q;
	double tau = (T_Q*(K_tau-1.0)+1.0)/(T_Q-1.0);
	int nRestarts = 10;
	int nCoarsest = 20;
	KernDynMeans<VectorGraph> kdm(lambda, Q, tau, true);
	VectorGraph vgr;

	//run the experiment
	double cumulativeAccuracy = 0;//stores the accuracy accumulated for each step
	map<int, int> matchings;//stores the saved matchings from previous timesteps
							//enables proper label tracking (see note at line 27)
	for (int i = 0; i < nSteps; i++){
		//----------------------------
		//birth/death/motion processes
		//----------------------------
		cout << "Step " << i << ": Clusters undergoing birth/death/motion..." << endl;
		birthDeathMotionProcesses(clusterCenters, aliveClusters, birthProbability, deathProbability, motionStdDev);
		//------------------------------------------
		//generate the data for the current timestep
		//------------------------------------------
		cout << "Step " << i << ": Generating data from the clusters..." << endl;
		vector<V2d> clusterData;
		vector<int> trueLabels;
		generateData(clusterCenters, aliveClusters, nDataPerClusterPerStep, clusterStdDev, clusterData, trueLabels);

		//------------------------------------------
		//Take the vectors that we just created, and package them in the KD class defined above
		//------------------------------------------
		vgr.updateData(clusterData);

		//----------------------------
		//cluster using Dynamic Means
		//---------------------------
		vector<int> learnedLabels;
		vector<double> gammas;
		vector<int> prmlbls;
		double tTaken, obj;
		cout << "Step " << i << ": Clustering..." << endl;
		kdm.cluster(vgr, nRestarts, nCoarsest, learnedLabels, obj, gammas, prmlbls, tTaken);
		vgr.updateOldParameters(clusterData, learnedLabels, gammas, prmlbls);
		//----------------------------------------------------
		//calculate the accuracy via linear programming
		//including proper cluster label tracking (see above)
		//----------------------------------------------------
		matchings = getMaxMatchingConsistentWithOldMatching(learnedLabels, trueLabels, matchings);
		double acc = computeAccuracy(learnedLabels, trueLabels, matchings);
		cout << "Step " << i << ": Accuracy = " << acc <<  "\%" << endl;
		cumulativeAccuracy += acc;
	}
	cout << "Average Accuracy: " << cumulativeAccuracy/(double)nSteps << "\%" << endl;
	cout << "Done!" << endl;

	return 0;
}

//this function takes two label sets and a matching and outputs
//the accuracy of the labelling (assuming labels1 = learned, labels2 = true)
double computeAccuracy(vector<int> labels1, vector<int> labels2, map<int, int> matchings){
	if (labels1.size() != labels2.size()){
		cout << "Error: computeAccuracy requires labels1/labels2 to have the same size" << endl;
		return -1;
	}

	double acc = 0;
	for (int i = 0; i < labels1.size(); i++){
		if (matchings[labels1[i]] == labels2[i]){
			acc += 1.0;
		}
	}
	//compute the accuracy
	return 100.0*acc/(double)labels1.size();
}

//this function takes a set of cluster centers and runs them through a birth/death/motion model
void birthDeathMotionProcesses(vector<V2d>& clusterCenters, vector<bool>& aliveClusters, double birthProbability, double deathProbability, double motionStdDev){

	//distributions
	uniform_real_distribution<double> uniformDistAng(0, 2*M_PI);
	uniform_real_distribution<double> uniformDist01(0, 1);
	normal_distribution<double> transitionDistRadial(0, motionStdDev);

	for (int j = 0; j < clusterCenters.size(); j++){
		//for each cluster center, decide whether it dies
		if (aliveClusters[j] && uniformDist01(rng) < deathProbability){
			cout << "Cluster " << j << " died." << endl;
			aliveClusters[j] = false;
		} else if (aliveClusters[j]) {
			//if it survived, move it stochastically
			//radius sampled from normal
			double steplen = transitionDistRadial(rng);
			//angle sampled from uniform
			double stepang = uniformDistAng(rng);
			clusterCenters[j](0) += steplen*cos(stepang);
			clusterCenters[j](1) += steplen*sin(stepang);
			cout << "Cluster " << j << " moved to " << clusterCenters[j].transpose() << endl;
		}
	}
	//decide whether to create a new cluster
	if (uniformDist01(rng) < birthProbability || all_of(aliveClusters.begin(), aliveClusters.end(), [](bool b){return !b;}) ) {
		V2d newCenter;
		newCenter(0) = uniformDist01(rng);
		newCenter(1) = uniformDist01(rng);
		clusterCenters.push_back(newCenter);
		aliveClusters.push_back(true);
		cout << "Cluster " << clusterCenters.size()-1 << " was created at " << clusterCenters.back().transpose() << endl;
	}
}

//this function takes a set of cluster centers and generates data from them
void generateData(vector<V2d> clusterCenters, vector<bool> aliveClusters, int nDataPerClusterPerStep, double clusterStdDev, vector<V2d>& clusterData, vector<int>& trueLabels){

	//distributions
	uniform_real_distribution<double> uniformDistAng(0, 2*M_PI);
	normal_distribution<double> likelihoodDistRadial(0, clusterStdDev);
	//loop through alive centers, generate nDataPerClusterPerStep datapoints for each
	for (int j = 0; j < clusterCenters.size(); j++){
		if (aliveClusters[j]){
			for (int k = 0; k < nDataPerClusterPerStep; k++){
				V2d newData = clusterCenters[j];
				double len = likelihoodDistRadial(rng);
				double ang = uniformDistAng(rng);
				newData(0) += len*cos(ang);
				newData(1) += len*sin(ang);
				clusterData.push_back(newData);
				trueLabels.push_back(j);
			}
		}
	}
}

<|endoftext|>


<commit_before>#include "Hearthstone.h"

#include <QFile>
#include <QDesktopServices>
#include <QSettings>

#ifdef Q_WS_MAC
#include "OSXWindowCapture.h"
#elif defined Q_WS_WIN
#include "WinWindowCapture.h"
#include "Shlobj.h"
#endif

DEFINE_SINGLETON_SCOPE( Hearthstone )

Hearthstone::Hearthstone() {
#ifdef Q_WS_MAC
  mCapture = new OSXWindowCapture( "Hearthstone" );
#elif defined Q_WS_WIN
  mCapture = new WinWindowCapture( "Hearthstone" );
#endif
}

Hearthstone::~Hearthstone() {
  if( mCapture != NULL )
    delete mCapture;
}

bool Hearthstone::Running() {
  return mCapture->WindowFound();
}

#ifdef Q_WS_WIN
inline float roundf( float x ) {
   return x >= 0.0f ? floorf( x + 0.5f ) : ceilf( x - 0.5f );
}
#endif

QPixmap Hearthstone::Capture( int vx, int vy, int vw, int vh ) {
  int x, y, w, h;

  int realCanvasWidth = mCapture->Width();
  int realCanvasHeight = mCapture->Height();

  int virtualCanvasWidth = VIRTUAL_CANVAS_WIDTH;
  int virtualCanvasHeight = VIRTUAL_CANVAS_HEIGHT;

  float dx = ( vx - virtualCanvasWidth/2 );
  float dy = ( vy - virtualCanvasHeight/2 );
  float scale = ( float )realCanvasHeight / virtualCanvasHeight;

  // Rounding here is important for dhash calc
  x = roundf( realCanvasWidth/2 + dx * scale );
  y = roundf( realCanvasHeight/2 + dy * scale );
  w = roundf( vw * scale );
  h = roundf( vh * scale );

  return mCapture->Capture( x, y, w, h );
}

void Hearthstone::SetWindowCapture( WindowCapture *windowCapture ) {
  if( mCapture != NULL )
    delete mCapture;

  mCapture = windowCapture;
}

void Hearthstone::EnableLogging() {
  const int   NUM_LOG_SYSTEMS = 3;
  const char  LOG_SYSTEMS[ NUM_LOG_SYSTEMS ][ 32 ] = { "Zone", "Asset", "Bob" };

  string path = LogConfigPath();
  QFile file( path.c_str() );

  // Read file contents
  QString contents;
  if( file.exists() ) {
    file.open( QIODevice::ReadOnly | QIODevice::Text );
    QTextStream in( &file );
    contents = in.readAll();
    file.close();
  }

  if( !file.open( QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text ) ) {
    LOG( "Couldn't create file %s", path.c_str() );
  } else {
    QTextStream out( &file );
    for( int i = 0; i < NUM_LOG_SYSTEMS; i++ ) {
      const char *logSysName = LOG_SYSTEMS[ i ];
      if( !contents.contains( QString( "[%1]" ).arg( logSysName ) ) ) {
        out << "\n";
        out << "[" << LOG_SYSTEMS[i] << "]\n";
        out << "LogLevel=1\n";
        out << "ConsolePrinting=true\n";
        LOG( "Enable Log System %s", logSysName );
      }
    }
    file.close();
  }
}

void Hearthstone::DisableLogging() {
  QFile file( LogConfigPath().c_str() );
  if( file.exists() ) {
    file.remove();
    LOG( "Ingame log deactivated." );
  }
}

string Hearthstone::LogConfigPath() {
#ifdef Q_WS_MAC
  QString homeLocation = QDesktopServices::storageLocation( QDesktopServices::HomeLocation );
  QString configPath = homeLocation + "/Library/Preferences/Blizzard/Hearthstone/log.config";
#elif defined Q_WS_WIN
  char buffer[ MAX_PATH ];
  SHGetSpecialFolderPathA( NULL, buffer, CSIDL_LOCAL_APPDATA, FALSE );
  QString localAppData( buffer );
  QString configPath = localAppData + "\\Blizzard\\Hearthstone\\log.config";
#endif
  return configPath.toStdString();
}

string Hearthstone::LogPath() {
#ifdef Q_WS_MAC
  QString homeLocation = QDesktopServices::storageLocation( QDesktopServices::HomeLocation );
  QString logPath = homeLocation + "/Library/Logs/Unity/Player.log";
#elif defined Q_WS_WIN
  QSettings hsKey( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Hearthstone", QSettings::NativeFormat );
  QString hsPath = hsKey.value( "InstallLocation" ).toString();
  if( hsPath.isEmpty() ) {
    LOG( "LogPath Fallback" );
    QString programFiles( getenv( "PROGRAMFILES(X86)" ) );
    if( programFiles.isEmpty() ) {
      programFiles = getenv( "PROGRAMFILES" );
    }
    hsPath = programFiles + "\\Hearthstone";
  }
  QString logPath = hsPath + "\\Hearthstone_Data\\output_log.txt";
#endif
  return logPath.toStdString();
}

int Hearthstone::Width() {
  return mCapture->Width();
}

int Hearthstone::Height() {
  return mCapture->Height();
}
<commit_msg>clarify<commit_after>#include "Hearthstone.h"

#include <QFile>
#include <QDesktopServices>
#include <QSettings>

#ifdef Q_WS_MAC
#include "OSXWindowCapture.h"
#elif defined Q_WS_WIN
#include "WinWindowCapture.h"
#include "Shlobj.h"
#endif

DEFINE_SINGLETON_SCOPE( Hearthstone )

Hearthstone::Hearthstone() {
#ifdef Q_WS_MAC
  mCapture = new OSXWindowCapture( "Hearthstone" );
#elif defined Q_WS_WIN
  mCapture = new WinWindowCapture( "Hearthstone" );
#endif
}

Hearthstone::~Hearthstone() {
  if( mCapture != NULL )
    delete mCapture;
}

bool Hearthstone::Running() {
  return mCapture->WindowFound();
}

#ifdef Q_WS_WIN
inline float roundf( float x ) {
   return x >= 0.0f ? floorf( x + 0.5f ) : ceilf( x - 0.5f );
}
#endif

QPixmap Hearthstone::Capture( int vx, int vy, int vw, int vh ) {
  int x, y, w, h;

  int realCanvasWidth = mCapture->Width();
  int realCanvasHeight = mCapture->Height();

  int virtualCanvasWidth = VIRTUAL_CANVAS_WIDTH;
  int virtualCanvasHeight = VIRTUAL_CANVAS_HEIGHT;

  float dx = ( vx - virtualCanvasWidth/2 );
  float dy = ( vy - virtualCanvasHeight/2 );
  float scale = ( float )realCanvasHeight / virtualCanvasHeight;

  // Rounding here is important for dhash calc
  x = roundf( realCanvasWidth/2 + dx * scale );
  y = roundf( realCanvasHeight/2 + dy * scale );
  w = roundf( vw * scale );
  h = roundf( vh * scale );

  return mCapture->Capture( x, y, w, h );
}

void Hearthstone::SetWindowCapture( WindowCapture *windowCapture ) {
  if( mCapture != NULL )
    delete mCapture;

  mCapture = windowCapture;
}

void Hearthstone::EnableLogging() {
  const int   NUM_LOG_MODULES = 4;
  const char  LOG_MODULES[ NUM_LOG_MODULES ][ 32 ] = { "Zone", "Asset", "Bob", "Power" };

  string path = LogConfigPath();
  QFile file( path.c_str() );

  // Read file contents
  QString contents;
  if( file.exists() ) {
    file.open( QIODevice::ReadOnly | QIODevice::Text );
    QTextStream in( &file );
    contents = in.readAll();
    file.close();
  }

  if( !file.open( QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text ) ) {
    LOG( "Couldn't create file %s", path.c_str() );
  } else {
    QTextStream out( &file );
    for( int i = 0; i < NUM_LOG_MODULES; i++ ) {
      const char *logModuleName = LOG_MODULES[ i ];
      if( !contents.contains( QString( "[%1]" ).arg( logModuleName ) ) ) {
        out << "\n";
        out << "[" << LOG_MODULES[i] << "]\n";
        out << "LogLevel=1\n";
        out << "ConsolePrinting=true\n";
        LOG( "Enable Log Module %s", logModuleName );
      }
    }
    file.close();
  }
}

void Hearthstone::DisableLogging() {
  QFile file( LogConfigPath().c_str() );
  if( file.exists() ) {
    file.remove();
    LOG( "Ingame log deactivated." );
  }
}

string Hearthstone::LogConfigPath() {
#ifdef Q_WS_MAC
  QString homeLocation = QDesktopServices::storageLocation( QDesktopServices::HomeLocation );
  QString configPath = homeLocation + "/Library/Preferences/Blizzard/Hearthstone/log.config";
#elif defined Q_WS_WIN
  char buffer[ MAX_PATH ];
  SHGetSpecialFolderPathA( NULL, buffer, CSIDL_LOCAL_APPDATA, FALSE );
  QString localAppData( buffer );
  QString configPath = localAppData + "\\Blizzard\\Hearthstone\\log.config";
#endif
  return configPath.toStdString();
}

string Hearthstone::LogPath() {
#ifdef Q_WS_MAC
  QString homeLocation = QDesktopServices::storageLocation( QDesktopServices::HomeLocation );
  QString logPath = homeLocation + "/Library/Logs/Unity/Player.log";
#elif defined Q_WS_WIN
  QSettings hsKey( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Hearthstone", QSettings::NativeFormat );
  QString hsPath = hsKey.value( "InstallLocation" ).toString();
  if( hsPath.isEmpty() ) {
    LOG( "LogPath Fallback" );
    QString programFiles( getenv( "PROGRAMFILES(X86)" ) );
    if( programFiles.isEmpty() ) {
      programFiles = getenv( "PROGRAMFILES" );
    }
    hsPath = programFiles + "\\Hearthstone";
  }
  QString logPath = hsPath + "\\Hearthstone_Data\\output_log.txt";
#endif
  return logPath.toStdString();
}

int Hearthstone::Width() {
  return mCapture->Width();
}

int Hearthstone::Height() {
  return mCapture->Height();
}
<|endoftext|>


<commit_before>#include "IObservable.hpp"
#include "IObserver.hpp"

#include <set>

void IObservable::attach(IObserver &observer)
{
	observers.insert(&observer);
}

void IObservable::detach(IObserver &observer)
{
	observers.erase(&observer);
}

void IObservable::notifyAll()
{
	for(IObserver *observer : observers)
		observer->notify();
}
<commit_msg>Usunięcie niepotrzebnego includa<commit_after>#include "IObservable.hpp"
#include "IObserver.hpp"

void IObservable::attach(IObserver &observer)
{
	observers.insert(&observer);
}

void IObservable::detach(IObserver &observer)
{
	observers.erase(&observer);
}

void IObservable::notifyAll()
{
	for(IObserver *observer : observers)
		observer->notify();
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <ga/GASimpleGA.h>
#include <ga/GA2DBinStrGenome.h>
#include <ga/std_stream.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "imagedetect.hpp"
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
using namespace cv;
BaseCascadeDetect *detectCascade;
struct binImage {Mat image; Rect binLoc;};
vector <binImage> allBinImages;
int centerArea = 4000;
int rectArea = 100;
Mat drawCopy;

vector<string> &split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
       if (!item.empty())
        elems.push_back(item);
    }
    return elems;
}

bool rectangleCompare(Rect rect1, Rect rect2) {

Point center1 = Point(rect1.width/2,rect1.height/2);
Point center2 = Point(rect2.width/2,rect2.height/2);
Rect centerRect = Rect(center1,center2);
bool matched = ((abs((rect1.width * rect1.height) - (rect2.width * rect2.height)) < rectArea) && ((centerRect.width * centerRect.height) < centerArea));
if(matched)
cout << "rectangles matched" << endl;
return matched;
}

vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

// this function returns an int from a binary string
unsigned int getIntFrom2DBinaryString(const GA2DBinaryStringGenome &genome,unsigned int row)
{
     unsigned int intval = 0;
     for(int i=0; i<genome.width(); i++){
        intval <<= 1;
        intval  |= genome.gene(i, row) & 1;
     }
     return intval;
}
//this should return a value depending on how close the GA is to
//the objective

float Objective(GAGenome& g) {
GA2DBinaryStringGenome & genome = (GA2DBinaryStringGenome &)g;
  unsigned int intval[genome.height()];
  for(int i=0; i<genome.height(); i++){
     intval[i] = getIntFrom2DBinaryString(genome, i);
  }

vector <Rect> binsThreshold;
vector <Rect> binsClassifier;
vector <Rect> filteredBins;
Mat threshHoldImage;
float foundRect = 0.0;
int totalRect = 0;
cout << "trying values: ";
for(int i = 0; i < genome.height(); i++)
cout << intval[i] << ",";
scale = intval[0];
neighbors = intval[1];
for(int i = 0; i < allBinImages.size(); i++) { //run for each image
	detectCascade->cascadeDetect(allBinImages[i].image,binsClassifier); //detect stuff
	foundRect = 0;
	for( int j = 0; binsClassifier.size() < j; j++) { //run for each detected bin
		if (rectangleCompare(binsClassifier[j],allBinImages[i].binLoc)) //if the detection was real
		foundRect++;
		else
		foundRect = foundRect - 0.2;
		totalRect++;
	}
}
drawCopy = allBinImages[allBinImages.size() - 1].image.clone();
/*rectangle(drawCopy,allBinImages[allBinImages.size() - 1].binLoc,Scalar(0,255,0),4);
for (int j = 0; j < binsClassifier.size(); j++)
rectangle(drawCopy,binsClassifier[j],Scalar(0,0,255),4);
imshow("Image",drawCopy);
waitKey(5); */
float successRate = 0;
if (totalRect != 0)
   successRate = foundRect / (float)totalRect;
if (successRate < 0)
   float successRate = 0;
cout << "Returning: " << successRate << endl;
return successRate;
}

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

   const char *cascadeName = "../cascade_training/classifier_bin_5/cascade_27.xml";
   if (gpu::getCudaEnabledDeviceCount() > 0)
      detectCascade = new GPU_CascadeDetect(cascadeName);
   else
      detectCascade = new CPU_CascadeDetect(cascadeName);

   //-- 1. Load the cascades
   if( !detectCascade->loaded() )
   {
      cerr << "--(!)Error loading " << cascadeName << endl;
      return -1;
   }
for(int ii=1; ii<argc; ii++) {
  if(strcmp(argv[ii++],"seed") == 0) {
    GARandomSeed((unsigned int)atoi(argv[ii]));
  }
}
int imageNum = 0;
int position;
vector<string> image_names;
vector<string> parameters;
DIR *dirp = opendir("./gaSource/");
struct dirent *dp;
if (!dirp)
return -1;
while ((dp = readdir(dirp)) != NULL) {
   if (strstr(dp->d_name, ".png") && !strstr(dp->d_name, "_r.png"))
	 image_names.push_back(dp->d_name);
   }
   closedir(dirp);
   cout << "Read " << image_names.size() << " image names" << endl;
   for (vector<string>::iterator it = image_names.begin(); it != image_names.end(); ++it)
   {
	allBinImages.push_back(binImage());
	string imagePath = "./gaSource/" + *it;
	allBinImages[imageNum].image = imread(imagePath);
	*it = it->substr(0, it->rfind('.'));
	parameters = split(*it,'_');
	if(parameters.size() != 7) {
		cout << "file parameters error" << endl;
		return -1;
		}
	cout << "Image " << it - image_names.begin() << " parameters: ";
	for(int i = 1; i < parameters.size(); i++)
	cout << parameters[i] << " ";
	cout << endl;
	Point rectPoint1 = Point(atoi(parameters[3].c_str()),atoi(parameters[4].c_str())); //top left
	Point rectPoint2 = Point((atoi(parameters[3].c_str()) + atoi(parameters[5].c_str())),(atoi(parameters[4].c_str()) + atoi(parameters[6].c_str())));
	allBinImages[imageNum].binLoc = Rect(rectPoint1,rectPoint2);
	if(allBinImages[imageNum].image.empty()) {
		cout << "image loading error" << endl;
		return -1;
		}
	imageNum++;
    }
int width    = 6; //number of bits per number
int height   = 2; //number of values to change
int popsize  = 30; //how many pairs of numbers it creates per gen
int ngen     = 400; //number of generations to run
float pmut   = 0.001; //chance of mutation
float pcross = 0.9; //chance of crossover

//create the genome
GA2DBinaryStringGenome genome(width, height, Objective);
GASimpleGA ga(genome); //create the algorithm
ga.populationSize(popsize); //set parameters that we defined
ga.nGenerations(ngen);
ga.pMutation(pmut);
ga.pCrossover(pcross);
ga.scoreFilename("iteration_data.dat"); //write stuff to this file
ga.flushFrequency(20); //frequency of writing to data
cout << "created GA, starting now..." << endl;
ga.evolve(); //RUN!
//now we print out the best values that it found
genome = ga.statistics().bestIndividual();
cout << "The GA found:" << endl;
double accum = 0;
  for (int i = 0; i < genome.height(); i++) //for each value
  {
     unsigned int intval = getIntFrom2DBinaryString(genome, i);
     cout << "value " << i << " : " << intval << endl;
  }
}
<commit_msg>Got code ready for running on GPU.<commit_after>#include <fstream>
#include <iostream>
#include <ga/GASimpleGA.h>
#include <ga/GA2DBinStrGenome.h>
#include <ga/std_stream.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "imagedetect.hpp"
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
using namespace cv;
BaseCascadeDetect *detectCascade;
struct binImage {Mat image; Rect binLoc;};
struct binImageGPU {gpu::GpuMat image; Rect binLoc;}
vector <binImage> allBinImages;
vector <binImageGPU> allBinImagesGPU;
int centerArea = 4000;
int rectArea = 100;
Mat drawCopy;

vector<string> &split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
       if (!item.empty())
        elems.push_back(item);
    }
    return elems;
}

bool rectangleCompare(Rect rect1, Rect rect2) {

Point center1 = Point(rect1.width/2,rect1.height/2);
Point center2 = Point(rect2.width/2,rect2.height/2);
Rect centerRect = Rect(center1,center2);
bool matched = ((abs((rect1.width * rect1.height) - (rect2.width * rect2.height)) < rectArea) && ((centerRect.width * centerRect.height) < centerArea));
if(matched)
cout << "rectangles matched" << endl;
return matched;
}

vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

// this function returns an int from a binary string
unsigned int getIntFrom2DBinaryString(const GA2DBinaryStringGenome &genome,unsigned int row)
{
     unsigned int intval = 0;
     for(int i=0; i<genome.width(); i++){
        intval <<= 1;
        intval  |= genome.gene(i, row) & 1;
     }
     return intval;
}
//this should return a value depending on how close the GA is to
//the objective

float Objective(GAGenome& g) {
GA2DBinaryStringGenome & genome = (GA2DBinaryStringGenome &)g;
  unsigned int intval[genome.height()];
  for(int i=0; i<genome.height(); i++){
     intval[i] = getIntFrom2DBinaryString(genome, i);
  }

vector <Rect> binsThreshold;
vector <Rect> binsClassifier;
vector <Rect> filteredBins;
Mat threshHoldImage;
float foundRect = 0.0;
int totalRect = 0;
cout << "trying values: ";
for(int i = 0; i < genome.height(); i++)
cout << intval[i] << ",";
scale = intval[0];
neighbors = intval[1];
for(int i = 0; i < allBinImages.size(); i++) { //run for each image
	if (gpu::getCudaEnabledDeviceCount() > 0)
	   detectCascade->cascadeDetect(allBinImagesGPU[i].image,binsClassifier); //detect stuff using gpu
	else
	   detectCascade->cascadeDetect(allBinImages[i].image,binsClassifier); //detect stuff
	foundRect = 0;
	for( int j = 0; binsClassifier.size() < j; j++) { //run for each detected bin
		if (rectangleCompare(binsClassifier[j],allBinImages[i].binLoc)) //if the detection was real
		foundRect++;
		else
		foundRect = foundRect - 0.2;
		totalRect++;
	}
}
drawCopy = allBinImages[allBinImages.size() - 1].image.clone();
/*rectangle(drawCopy,allBinImages[allBinImages.size() - 1].binLoc,Scalar(0,255,0),4);
for (int j = 0; j < binsClassifier.size(); j++)
rectangle(drawCopy,binsClassifier[j],Scalar(0,0,255),4);
imshow("Image",drawCopy);
waitKey(5); */
float successRate = 0;
if (totalRect != 0)
   successRate = foundRect / (float)totalRect;
if (successRate < 0)
   float successRate = 0;
cout << "Returning: " << successRate << endl;
return successRate;
}

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

   const char *cascadeName = "../cascade_training/classifier_bin_5/cascade_27.xml";
   if (gpu::getCudaEnabledDeviceCount() > 0)
      detectCascade = new GPU_CascadeDetect(cascadeName);
   else
      detectCascade = new CPU_CascadeDetect(cascadeName);

   //-- 1. Load the cascades
   if( !detectCascade->loaded() )
   {
      cerr << "--(!)Error loading " << cascadeName << endl;
      return -1;
   }
for(int ii=1; ii<argc; ii++) {
  if(strcmp(argv[ii++],"seed") == 0) {
    GARandomSeed((unsigned int)atoi(argv[ii]));
  }
}
int imageNum = 0;
int position;
vector<string> image_names;
vector<string> parameters;
DIR *dirp = opendir("./gaSource/");
struct dirent *dp;
if (!dirp)
return -1;
while ((dp = readdir(dirp)) != NULL) {
   if (strstr(dp->d_name, ".png") && !strstr(dp->d_name, "_r.png"))
	 image_names.push_back(dp->d_name);
   }
   closedir(dirp);
   cout << "Read " << image_names.size() << " image names" << endl;
   for (vector<string>::iterator it = image_names.begin(); it != image_names.end(); ++it) //run for each image
   {
	allBinImages.push_back(binImage());
	if (gpu::getCudaEnabledDeviceCount() > 0) //run if gpu
	   allBinImagesGPU.push_back(binImage()) //allocate memory for GpuMats
	string imagePath = "./gaSource/" + *it;
	allBinImages[imageNum].image = imread(imagePath);
	if (gpu::getCudaEnabledDeviceCount() > 0) //run if gpu
	   allBinImagesGPU[imageNum].image.upload(allBinImage[imageNum].image); //upload image
	*it = it->substr(0, it->rfind('.'));
	parameters = split(*it,'_');
	if(parameters.size() != 7) {
		cout << "file parameters error" << endl;
		return -1;
		}
	cout << "Image " << it - image_names.begin() << " parameters: ";
	for(int i = 1; i < parameters.size(); i++)
	cout << parameters[i] << " ";
	cout << endl;
	Point rectPoint1 = Point(atoi(parameters[3].c_str()),atoi(parameters[4].c_str())); //top left
	Point rectPoint2 = Point((atoi(parameters[3].c_str()) + atoi(parameters[5].c_str())),(atoi(parameters[4].c_str()) + atoi(parameters[6].c_str())));
	allBinImages[imageNum].binLoc = Rect(rectPoint1,rectPoint2);
	if (gpu::getCudaEnabledDeviceCount() > 0) //run if gpu
	   allBinImagesGPU[imageNum].binLoc = Rect(rectPoint1,rectPoint2); //copy bin locations
	if(allBinImages[imageNum].image.empty()) {
		cout << "image loading error" << endl;
		return -1;
		}
	imageNum++;
    }
int width    = 6; //number of bits per number
int height   = 2; //number of values to change
int popsize  = 30; //how many pairs of numbers it creates per gen
int ngen     = 400; //number of generations to run
float pmut   = 0.001; //chance of mutation
float pcross = 0.9; //chance of crossover

//create the genome
GA2DBinaryStringGenome genome(width, height, Objective);
GASimpleGA ga(genome); //create the algorithm
ga.populationSize(popsize); //set parameters that we defined
ga.nGenerations(ngen);
ga.pMutation(pmut);
ga.pCrossover(pcross);
ga.scoreFilename("iteration_data.dat"); //write stuff to this file
ga.flushFrequency(20); //frequency of writing to data
cout << "created GA, starting now..." << endl;
ga.evolve(); //RUN!
//now we print out the best values that it found
genome = ga.statistics().bestIndividual();
cout << "The GA found:" << endl;
double accum = 0;
  for (int i = 0; i < genome.height(); i++) //for each value
  {
     unsigned int intval = getIntFrom2DBinaryString(genome, i);
     cout << "value " << i << " : " << intval << endl;
  }
}
<|endoftext|>