<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "server_util.hpp"
#include <glog/logging.h>

#include <iostream>
#include <iomanip>
#include <pficommon/text/json.h>

#include "../common/util.hpp"
#include "../common/network.hpp"
#include "../common/cmdline.h"
#include "../common/exception.hpp"
#include "../common/membership.hpp"

namespace jubatus { namespace framework {

  static const std::string VERSION(JUBATUS_VERSION);

  void print_version(const std::string& progname){
    std::cout << "jubatus-" << VERSION << " (" << progname << ")" << std::endl;
  }

  server_argv::server_argv(int args, char** argv, const std::string& type)
    : type(type)
  {
    google::InitGoogleLogging(argv[0]);

    cmdline::parser p;
    p.add<int>("rpc-port", 'p', "port number", false, 9199);
    p.add<int>("thread", 'c', "concurrency = thread number", false, 2);
    p.add<int>("timeout", 't', "time out (sec)", false, 10);
    p.add<std::string>("tmpdir", 'd', "directory to save and load models", false, "/tmp");
    p.add<std::string>("logdir", 'l', "directory to output logs (instead of stderr)", false);

#ifdef HAVE_ZOOKEEPER_H
    p.add<std::string>("zookeeper", 'z', "zookeeper location", false);
    p.add<std::string>("name", 'n', "learning machine instance name", false);
    p.add("join", 'j', "join to the existing cluster");
    p.add<int>("interval_sec", 's', "mix interval by seconds", false, 16);
    p.add<int>("interval_count", 'i', "mix interval by update count", false, 512);
#endif

    // APPLY CHANGES TO JUBAVISOR WHEN ARGUMENTS MODIFIED

    p.add("version", 'v', "version");

    p.parse_check(args, argv);

    if( p.exist("version") ){
      print_version(jubatus::util::get_program_name());
      exit(0);
    }

    port = p.get<int>("rpc-port");
    threadnum = p.get<int>("thread");
    timeout = p.get<int>("timeout");
    program_name = jubatus::util::get_program_name();
    tmpdir = p.get<std::string>("tmpdir");
    logdir = p.get<std::string>("logdir");

    //    eth = "localhost";
    eth = jubatus::common::get_default_v4_address();

#ifdef HAVE_ZOOKEEPER_H
    z = p.get<std::string>("zookeeper");
    name = p.get<std::string>("name");
    join = p.exist("join");
    interval_sec = p.get<int>("interval_sec");
    interval_count = p.get<int>("interval_count");
#else
    z = "";
    name = "";
    join = false;
    interval_sec = 16;
    interval_count = 512;
#endif

    if(z != "" and name == ""){
      std::cerr << "can't start multinode mode without name specified" << std::endl;
      std::cerr << p.usage() << std::endl;
      exit(1);
    }

    if(p.exist("logdir")){
      set_log_destination(jubatus::util::get_program_name());
    } else {
      google::LogToStderr();
    }

    boot_message(jubatus::util::get_program_name());
  };

  server_argv::server_argv():
    join(false), port(9199), timeout(10), threadnum(2), z(""), name(""),
    tmpdir("/tmp"), logdir(""), eth("localhost"), interval_sec(5), interval_count(1024)
  {
  };

  void server_argv::boot_message(const std::string& progname) const {
    std::stringstream ss;
    ss << "starting " << progname << " " << VERSION << " RPC server at " << eth << ":" << port << '\n';
    ss << "    pid            : " << getpid() << '\n';
    ss << "    user           : " << getenv("USER") << '\n';
    ss << "    mode           : ";
    if(is_standalone()) {
      ss << "standalone mode\n";
    } else {
      ss << "multinode mode\n";
    }
    ss << "    timeout        : " << timeout << '\n';
    ss << "    thread         : " << threadnum << '\n';
    ss << "    tmpdir         : " << tmpdir << '\n';
    ss << "    logdir         : " << logdir << '\n';
#ifdef HAVE_ZOOKEEPER_H
    ss << "    zookeeper      : " << z << '\n';
    ss << "    name           : " << name << '\n';
    ss << "    join           : " << std::boolalpha << join << '\n';
    ss << "    interval sec   : " << interval_sec << '\n';
    ss << "    interval count : " << interval_count << '\n';
#endif
    LOG(INFO) << ss.str();
  };

  void server_argv::set_log_destination(const std::string& progname) const {
    std::ostringstream basename;
    basename <<  progname << '.' << eth << '_' << port;
    for(int severity = 0; severity < google::NUM_SEVERITIES; severity++) {
      std::string log = logdir + '/';
      log += basename.str() + '.';
      log += name + '.';
      log += google::GetLogSeverityName(severity);
      log += ".log.";
      std::string link = basename.str() + '.';
      link += pfi::lang::lexical_cast<std::string>(getpid());
      google::SetLogDestination(severity, log.c_str());
      google::SetLogSymlink(severity, link.c_str());
    }
  }

  std::string get_server_identifier(const server_argv& a) {
    std::stringstream ss;
    ss << a.eth;
    ss << "_";
    ss << a.port;
    return ss.str();
  }

  keeper_argv::keeper_argv(int args, char** argv, const std::string& t)
    : type(t)
  {
    google::InitGoogleLogging(argv[0]);

    cmdline::parser p;
    p.add<int>("rpc-port", 'p', "port number", false, 9199);
    p.add<int>("thread", 'c', "concurrency = thread number", false, 16);
    p.add<int>("timeout", 't', "time out (sec)", false, 10);

    p.add<std::string>("zookeeper", 'z', "zookeeper location", false, "localhost:2181");
    p.add<std::string>("logdir", 'l', "directory to output logs (instead of stderr)", false);
    p.add("version", 'v', "version");

    p.parse_check(args, argv);

    if( p.exist("version") ){
      print_version(jubatus::util::get_program_name());
      exit(0);
    }

    port = p.get<int>("rpc-port");
    threadnum = p.get<int>("thread");
    timeout = p.get<int>("timeout");
    program_name = jubatus::util::get_program_name();
    z = p.get<std::string>("zookeeper");
    logdir = p.get<std::string>("logdir");
    eth = jubatus::common::get_default_v4_address();

    if(p.exist("logdir")){
      set_log_destination(jubatus::util::get_program_name());
    } else {
      google::LogToStderr();
    }

    boot_message(jubatus::util::get_program_name());
  };

  keeper_argv::keeper_argv():
    port(9199), timeout(10), threadnum(16), z("localhost:2181"), logdir(""), eth("")
  {
  };

  void keeper_argv::boot_message(const std::string& progname) const {
    std::stringstream ss;
    ss << "starting " << progname << " " << VERSION << " RPC server at " << eth << ":" << port << '\n';
    ss << "    pid            : " << getpid() << '\n';
    ss << "    user           : " << getenv("USER") << '\n';
    ss << "    timeout        : " << timeout << '\n';
    ss << "    thread         : " << threadnum << '\n';
    ss << "    logdir         : " << logdir << '\n';
    ss << "    zookeeper      : " << z << '\n';
    LOG(INFO) << ss.str();
  };

  void keeper_argv::set_log_destination(const std::string& progname) const {
    std::ostringstream basename;
    basename <<  progname << '.' << eth << '_' << port;
    for(int severity = 0; severity < google::NUM_SEVERITIES; severity++) {
      std::string log = logdir + '/';
      log += basename.str() + '.';
      log += google::GetLogSeverityName(severity);
      log += ".log.";
      std::string link = basename.str() + '.';
      link += pfi::lang::lexical_cast<std::string>(getpid());
      google::SetLogDestination(severity, log.c_str());
      google::SetLogSymlink(severity, link.c_str());
    }
  }

  common::cshared_ptr<jubatus::common::lock_service> ls;

  void atexit(void){
#ifdef HAVE_ZOOKEEPER_H
    if(ls)
      ls->force_close();
#endif
  }

}
}
<commit_msg>Changed logfile name<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "server_util.hpp"
#include <glog/logging.h>

#include <iostream>
#include <iomanip>
#include <pficommon/text/json.h>

#include "../common/util.hpp"
#include "../common/network.hpp"
#include "../common/cmdline.h"
#include "../common/exception.hpp"
#include "../common/membership.hpp"

namespace jubatus { namespace framework {

  static const std::string VERSION(JUBATUS_VERSION);

  void print_version(const std::string& progname){
    std::cout << "jubatus-" << VERSION << " (" << progname << ")" << std::endl;
  }

  server_argv::server_argv(int args, char** argv, const std::string& type)
    : type(type)
  {
    google::InitGoogleLogging(argv[0]);

    cmdline::parser p;
    p.add<int>("rpc-port", 'p', "port number", false, 9199);
    p.add<int>("thread", 'c', "concurrency = thread number", false, 2);
    p.add<int>("timeout", 't', "time out (sec)", false, 10);
    p.add<std::string>("tmpdir", 'd', "directory to save and load models", false, "/tmp");
    p.add<std::string>("logdir", 'l', "directory to output logs (instead of stderr)", false);

#ifdef HAVE_ZOOKEEPER_H
    p.add<std::string>("zookeeper", 'z', "zookeeper location", false);
    p.add<std::string>("name", 'n', "learning machine instance name", false);
    p.add("join", 'j', "join to the existing cluster");
    p.add<int>("interval_sec", 's', "mix interval by seconds", false, 16);
    p.add<int>("interval_count", 'i', "mix interval by update count", false, 512);
#endif

    // APPLY CHANGES TO JUBAVISOR WHEN ARGUMENTS MODIFIED

    p.add("version", 'v', "version");

    p.parse_check(args, argv);

    if( p.exist("version") ){
      print_version(jubatus::util::get_program_name());
      exit(0);
    }

    port = p.get<int>("rpc-port");
    threadnum = p.get<int>("thread");
    timeout = p.get<int>("timeout");
    program_name = jubatus::util::get_program_name();
    tmpdir = p.get<std::string>("tmpdir");
    logdir = p.get<std::string>("logdir");

    //    eth = "localhost";
    eth = jubatus::common::get_default_v4_address();

#ifdef HAVE_ZOOKEEPER_H
    z = p.get<std::string>("zookeeper");
    name = p.get<std::string>("name");
    join = p.exist("join");
    interval_sec = p.get<int>("interval_sec");
    interval_count = p.get<int>("interval_count");
#else
    z = "";
    name = "";
    join = false;
    interval_sec = 16;
    interval_count = 512;
#endif

    if(z != "" and name == ""){
      std::cerr << "can't start multinode mode without name specified" << std::endl;
      std::cerr << p.usage() << std::endl;
      exit(1);
    }

    if(p.exist("logdir")){
      set_log_destination(jubatus::util::get_program_name());
    } else {
      google::LogToStderr();
    }

    boot_message(jubatus::util::get_program_name());
  };

  server_argv::server_argv():
    join(false), port(9199), timeout(10), threadnum(2), z(""), name(""),
    tmpdir("/tmp"), logdir(""), eth("localhost"), interval_sec(5), interval_count(1024)
  {
  };

  void server_argv::boot_message(const std::string& progname) const {
    std::stringstream ss;
    ss << "starting " << progname << " " << VERSION << " RPC server at " << eth << ":" << port << '\n';
    ss << "    pid            : " << getpid() << '\n';
    ss << "    user           : " << getenv("USER") << '\n';
    ss << "    mode           : ";
    if(is_standalone()) {
      ss << "standalone mode\n";
    } else {
      ss << "multinode mode\n";
    }
    ss << "    timeout        : " << timeout << '\n';
    ss << "    thread         : " << threadnum << '\n';
    ss << "    tmpdir         : " << tmpdir << '\n';
    ss << "    logdir         : " << logdir << '\n';
#ifdef HAVE_ZOOKEEPER_H
    ss << "    zookeeper      : " << z << '\n';
    ss << "    name           : " << name << '\n';
    ss << "    join           : " << std::boolalpha << join << '\n';
    ss << "    interval sec   : " << interval_sec << '\n';
    ss << "    interval count : " << interval_count << '\n';
#endif
    LOG(INFO) << ss.str();
  };

  void server_argv::set_log_destination(const std::string& progname) const {
    std::ostringstream basename;
    basename <<  progname << '.' << eth << '_' << port;
    for(int severity = 0; severity < google::NUM_SEVERITIES; severity++) {
      std::string log = logdir + '/';
      log += basename.str() + '.';
      if (!name.empty()) {
        log += name + '.';
      }
      log += google::GetLogSeverityName(severity);
      log += ".log.";
      std::string link = basename.str() + '.';
      link += pfi::lang::lexical_cast<std::string>(getpid());
      google::SetLogDestination(severity, log.c_str());
      google::SetLogSymlink(severity, link.c_str());
    }
  }

  std::string get_server_identifier(const server_argv& a) {
    std::stringstream ss;
    ss << a.eth;
    ss << "_";
    ss << a.port;
    return ss.str();
  }

  keeper_argv::keeper_argv(int args, char** argv, const std::string& t)
    : type(t)
  {
    google::InitGoogleLogging(argv[0]);

    cmdline::parser p;
    p.add<int>("rpc-port", 'p', "port number", false, 9199);
    p.add<int>("thread", 'c', "concurrency = thread number", false, 16);
    p.add<int>("timeout", 't', "time out (sec)", false, 10);

    p.add<std::string>("zookeeper", 'z', "zookeeper location", false, "localhost:2181");
    p.add<std::string>("logdir", 'l', "directory to output logs (instead of stderr)", false);
    p.add("version", 'v', "version");

    p.parse_check(args, argv);

    if( p.exist("version") ){
      print_version(jubatus::util::get_program_name());
      exit(0);
    }

    port = p.get<int>("rpc-port");
    threadnum = p.get<int>("thread");
    timeout = p.get<int>("timeout");
    program_name = jubatus::util::get_program_name();
    z = p.get<std::string>("zookeeper");
    logdir = p.get<std::string>("logdir");
    eth = jubatus::common::get_default_v4_address();

    if(p.exist("logdir")){
      set_log_destination(jubatus::util::get_program_name());
    } else {
      google::LogToStderr();
    }

    boot_message(jubatus::util::get_program_name());
  };

  keeper_argv::keeper_argv():
    port(9199), timeout(10), threadnum(16), z("localhost:2181"), logdir(""), eth("")
  {
  };

  void keeper_argv::boot_message(const std::string& progname) const {
    std::stringstream ss;
    ss << "starting " << progname << " " << VERSION << " RPC server at " << eth << ":" << port << '\n';
    ss << "    pid            : " << getpid() << '\n';
    ss << "    user           : " << getenv("USER") << '\n';
    ss << "    timeout        : " << timeout << '\n';
    ss << "    thread         : " << threadnum << '\n';
    ss << "    logdir         : " << logdir << '\n';
    ss << "    zookeeper      : " << z << '\n';
    LOG(INFO) << ss.str();
  };

  void keeper_argv::set_log_destination(const std::string& progname) const {
    std::ostringstream basename;
    basename <<  progname << '.' << eth << '_' << port;
    for(int severity = 0; severity < google::NUM_SEVERITIES; severity++) {
      std::string log = logdir + '/';
      log += basename.str() + '.';
      log += google::GetLogSeverityName(severity);
      log += ".log.";
      std::string link = basename.str() + '.';
      link += pfi::lang::lexical_cast<std::string>(getpid());
      google::SetLogDestination(severity, log.c_str());
      google::SetLogSymlink(severity, link.c_str());
    }
  }

  common::cshared_ptr<jubatus::common::lock_service> ls;

  void atexit(void){
#ifdef HAVE_ZOOKEEPER_H
    if(ls)
      ls->force_close();
#endif
  }

}
}
<|endoftext|>


<commit_before>#include "ScriptManager.hpp"

#include <angelscript.h>
#include <scriptstdstring/scriptstdstring.h>
#include "../Util/Log.hpp"

void MessageCallback(const asSMessageInfo* message, void* param) {
    Log() << message->section << " (" << message->row << ", " << message->col << " : ";

    switch (message->type) {
    case asMSGTYPE_ERROR:
        Log() << "Error";
        break;
    case asMSGTYPE_INFORMATION:
        Log() << "Information";
        break;
    case asMSGTYPE_WARNING:
        Log() << "Warning";
        break;
    }

    Log() << " : " << message->message << "\n";
}

void print(const std::string& message) {
    Log() << message;
}

ScriptManager::ScriptManager() {

}

ScriptManager::~ScriptManager() {

}

void ScriptManager::TestScripting() {
    // Create the script engine
    asIScriptEngine* engine = asCreateScriptEngine();

    // Set the message callback to receive information on errors in human readable form.
    int r = engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); assert(r >= 0);

    // Register add-ons.
    RegisterStdString(engine);

    // Register functions.
    r = engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(print), asCALL_CDECL); assert(r >= 0);

    // Clean up.
    engine->ShutDownAndRelease();
}
<commit_msg>Build script<commit_after>#include "ScriptManager.hpp"

#include <angelscript.h>
#include <scriptstdstring/scriptstdstring.h>
#include "../Util/Log.hpp"

void MessageCallback(const asSMessageInfo* message, void* param) {
    Log() << message->section << " (" << message->row << ", " << message->col << " : ";

    switch (message->type) {
    case asMSGTYPE_ERROR:
        Log() << "Error";
        break;
    case asMSGTYPE_INFORMATION:
        Log() << "Information";
        break;
    case asMSGTYPE_WARNING:
        Log() << "Warning";
        break;
    }

    Log() << " : " << message->message << "\n";
}

void print(const std::string& message) {
    Log() << message;
}

ScriptManager::ScriptManager() {

}

ScriptManager::~ScriptManager() {

}

void ScriptManager::TestScripting() {
    // Create the script engine
    asIScriptEngine* engine = asCreateScriptEngine();

    // Set the message callback to receive information on errors in human readable form.
    int r = engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); assert(r >= 0);

    // Register add-ons.
    RegisterStdString(engine);

    // Register functions.
    r = engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(print), asCALL_CDECL); assert(r >= 0);

    // Define the test script.
    std::string script = "void main() { print(\"Hello world\\n\"); }";

    // Create, load and build script module.
    asIScriptModule* module = engine->GetModule("module", asGM_ALWAYS_CREATE);
    module->AddScriptSection("script.as", script.c_str());
    r = module->Build();
    if (r < 0)
        Log() << "Couldn't build script module.\n";

    // Clean up.
    engine->ShutDownAndRelease();
}
<|endoftext|>


<commit_before>/*
 * Copyright © 2010 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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 "ir_print_visitor.h"
#include "glsl_types.h"
#include "glsl_parser_extras.h"

static void print_type(const glsl_type *t);

void
ir_instruction::print(void) const
{
   ir_instruction *deconsted = const_cast<ir_instruction *>(this);

   ir_print_visitor v;
   deconsted->accept(&v);
}

void
_mesa_print_ir(exec_list *instructions,
	       struct _mesa_glsl_parse_state *state)
{
   for (unsigned i = 0; i < state->num_user_structures; i++) {
      const glsl_type *const s = state->user_structures[i];

      printf("(structure (%s) (%s@%p) (%u) (\n",
	     s->name, s->name, s, s->length);

      for (unsigned j = 0; j < s->length; j++) {
	 printf("\t((");
	 print_type(s->fields.structure[j].type);
	 printf(")(%s))\n", s->fields.structure[j].name);
      }

      printf(")\n");
   }

   printf("(\n");
   foreach_iter(exec_list_iterator, iter, *instructions) {
      ((ir_instruction *)iter.get())->print();
      printf("\n");
   }
   printf("\n)");
}

static void
print_type(const glsl_type *t)
{
   if (t->base_type == GLSL_TYPE_ARRAY) {
      printf("(array ");
      print_type(t->fields.array);
      printf(" %u)", t->length);
   } else if ((t->base_type == GLSL_TYPE_STRUCT)
	      && (strncmp("gl_", t->name, 3) != 0)) {
      printf("%s@%p", t->name, t);
   } else {
      printf("%s", t->name);
   }
}

void ir_print_visitor::visit(ir_variable *ir)
{
   printf("(declare ");

   const char *const cent = (ir->centroid) ? "centroid " : "";
   const char *const inv = (ir->invariant) ? "invariant " : "";
   const char *const mode[] = { "", "uniform ", "in ", "out ", "inout " };
   const char *const interp[] = { "", "flat", "noperspective" };

   printf("(%s%s%s%s) ",
	  cent, inv, mode[ir->mode], interp[ir->interpolation]);

   print_type(ir->type);
   printf(" %s@%p)", ir->name, ir);
}

void ir_print_visitor::visit(ir_function_signature *ir)
{
   printf("(signature ");
   print_type(ir->return_type);
   printf("\n  (parameters\n");
   foreach_iter(exec_list_iterator, iter, ir->parameters) {
      ir_variable *const inst = (ir_variable *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf("  )\n(");

   foreach_iter(exec_list_iterator, iter, ir->body) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf("))\n");
}

void ir_print_visitor::visit(ir_function *ir)
{
   printf("(function %s\n", ir->name);
   foreach_iter(exec_list_iterator, iter, *ir) {
      ir_function_signature *const sig = (ir_function_signature *) iter.get();

      sig->accept(this);
      printf("\n");
   }

   printf(")\n");
}

void ir_print_visitor::visit(ir_expression *ir)
{
   printf("(expression ");

   print_type(ir->type);

   printf(" %s ", ir->operator_string());

   if (ir->operands[0])
      ir->operands[0]->accept(this);

   if (ir->operands[1])
      ir->operands[1]->accept(this);
   printf(") ");
}

void ir_print_visitor::visit(ir_texture *ir)
{
   printf("(%s ", ir->opcode_string());

   ir->sampler->accept(this);
   printf(" ");

   ir->coordinate->accept(this);

   printf(" (%d %d %d) ", ir->offsets[0], ir->offsets[1], ir->offsets[2]);

   if (ir->op != ir_txf) {
      if (ir->projector)
	 ir->projector->accept(this);
      else
	 printf("1");

      if (ir->shadow_comparitor) {
	 printf(" ");
	 ir->shadow_comparitor->accept(this);
      } else {
	 printf(" ()");
      }
   }

   printf(" ");
   switch (ir->op)
   {
   case ir_tex:
      break;
   case ir_txb:
      ir->lod_info.bias->accept(this);
      break;
   case ir_txl:
   case ir_txf:
      ir->lod_info.lod->accept(this);
      break;
   case ir_txd:
      printf("(");
      ir->lod_info.grad.dPdx->accept(this);
      printf(" ");
      ir->lod_info.grad.dPdy->accept(this);
      printf(")");
      break;
   };
   printf(")");
}

void ir_print_visitor::visit(ir_swizzle *ir)
{
   const unsigned swiz[4] = {
      ir->mask.x,
      ir->mask.y,
      ir->mask.z,
      ir->mask.w,
   };

   printf("(swiz ");
   for (unsigned i = 0; i < ir->mask.num_components; i++) {
      printf("%c", "xyzw"[swiz[i]]);
   }
   printf(" ");
   ir->val->accept(this);
   printf(")");
}

void ir_print_visitor::visit(ir_dereference_variable *ir)
{
   ir_variable *var = ir->variable_referenced();
   printf("(var_ref %s@%p) ", var->name, var);
}

void ir_print_visitor::visit(ir_dereference_array *ir)
{
   printf("(array_ref ");
   ir->array->accept(this);
   ir->array_index->accept(this);
   printf(") ");
}

void ir_print_visitor::visit(ir_dereference_record *ir)
{
   printf("(record_ref ");
   ir->record->accept(this);
   printf(" %s) ", ir->field);
}

void ir_print_visitor::visit(ir_assignment *ir)
{
   printf("(assign ");

   if (ir->condition)
      ir->condition->accept(this);
   else
      printf("(constant bool (1))");

   printf(" ");

   ir->lhs->accept(this);

   printf(" ");

   ir->rhs->accept(this);
   printf(") ");
}

void ir_print_visitor::visit(ir_constant *ir)
{
   const glsl_type *const base_type = ir->type->get_base_type();

   printf("(constant ");
   print_type(ir->type);
   printf(" (");

   if (ir->type->is_array()) {
      for (unsigned i = 0; i < ir->type->length; i++)
	 ir->get_array_element(i)->accept(this);
   } else {
      for (unsigned i = 0; i < ir->type->components(); i++) {
	 if (i != 0)
	    printf(" ");
	 switch (base_type->base_type) {
	 case GLSL_TYPE_UINT:  printf("%u", ir->value.u[i]); break;
	 case GLSL_TYPE_INT:   printf("%d", ir->value.i[i]); break;
	 case GLSL_TYPE_FLOAT: printf("%f", ir->value.f[i]); break;
	 case GLSL_TYPE_BOOL:  printf("%d", ir->value.b[i]); break;
	 default: assert(0);
	 }
      }
   }
   printf(")) ");
}

void
ir_print_visitor::visit(ir_call *ir)
{
   printf("(call %s (", ir->callee_name());
   foreach_iter(exec_list_iterator, iter, *ir) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
   }
   printf("))\n");
}

void
ir_print_visitor::visit(ir_return *ir)
{
   printf("(return");

   ir_rvalue *const value = ir->get_value();
   if (value) {
      printf(" ");
      value->accept(this);
   }

   printf(")");
}

void
ir_print_visitor::visit(ir_discard *ir)
{
   printf("(discard ");

   if (ir->condition != NULL) {
      printf(" ");
      ir->condition->accept(this);
   }

   printf(")");
}

void
ir_print_visitor::visit(ir_if *ir)
{
   printf("(if ");
   ir->condition->accept(this);

   printf("(\n");
   foreach_iter(exec_list_iterator, iter, ir->then_instructions) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf(")\n");

   printf("(\n");
   foreach_iter(exec_list_iterator, iter, ir->else_instructions) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf("))\n");
}

void
ir_print_visitor::visit(ir_loop *ir)
{
   printf("(loop (");
   if (ir->counter != NULL)
      ir->counter->accept(this);
   printf(") (");
   if (ir->from != NULL)
      ir->from->accept(this);
   printf(") (");
   if (ir->to != NULL)
      ir->to->accept(this);
   printf(") (");
   if (ir->increment != NULL)
      ir->increment->accept(this);
   printf(") (\n");
   foreach_iter(exec_list_iterator, iter, ir->body_instructions) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf("))\n");
}

void
ir_print_visitor::visit(ir_loop_jump *ir)
{
   printf("%s", ir->is_break() ? "break" : "continue");
}
<commit_msg>ir_print_visitor: Add "temporary" to mode string printing.<commit_after>/*
 * Copyright © 2010 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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 "ir_print_visitor.h"
#include "glsl_types.h"
#include "glsl_parser_extras.h"

static void print_type(const glsl_type *t);

void
ir_instruction::print(void) const
{
   ir_instruction *deconsted = const_cast<ir_instruction *>(this);

   ir_print_visitor v;
   deconsted->accept(&v);
}

void
_mesa_print_ir(exec_list *instructions,
	       struct _mesa_glsl_parse_state *state)
{
   for (unsigned i = 0; i < state->num_user_structures; i++) {
      const glsl_type *const s = state->user_structures[i];

      printf("(structure (%s) (%s@%p) (%u) (\n",
	     s->name, s->name, s, s->length);

      for (unsigned j = 0; j < s->length; j++) {
	 printf("\t((");
	 print_type(s->fields.structure[j].type);
	 printf(")(%s))\n", s->fields.structure[j].name);
      }

      printf(")\n");
   }

   printf("(\n");
   foreach_iter(exec_list_iterator, iter, *instructions) {
      ((ir_instruction *)iter.get())->print();
      printf("\n");
   }
   printf("\n)");
}

static void
print_type(const glsl_type *t)
{
   if (t->base_type == GLSL_TYPE_ARRAY) {
      printf("(array ");
      print_type(t->fields.array);
      printf(" %u)", t->length);
   } else if ((t->base_type == GLSL_TYPE_STRUCT)
	      && (strncmp("gl_", t->name, 3) != 0)) {
      printf("%s@%p", t->name, t);
   } else {
      printf("%s", t->name);
   }
}

void ir_print_visitor::visit(ir_variable *ir)
{
   printf("(declare ");

   const char *const cent = (ir->centroid) ? "centroid " : "";
   const char *const inv = (ir->invariant) ? "invariant " : "";
   const char *const mode[] = { "", "uniform ", "in ", "out ", "inout ",
			        "temporary " };
   const char *const interp[] = { "", "flat", "noperspective" };

   printf("(%s%s%s%s) ",
	  cent, inv, mode[ir->mode], interp[ir->interpolation]);

   print_type(ir->type);
   printf(" %s@%p)", ir->name, ir);
}

void ir_print_visitor::visit(ir_function_signature *ir)
{
   printf("(signature ");
   print_type(ir->return_type);
   printf("\n  (parameters\n");
   foreach_iter(exec_list_iterator, iter, ir->parameters) {
      ir_variable *const inst = (ir_variable *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf("  )\n(");

   foreach_iter(exec_list_iterator, iter, ir->body) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf("))\n");
}

void ir_print_visitor::visit(ir_function *ir)
{
   printf("(function %s\n", ir->name);
   foreach_iter(exec_list_iterator, iter, *ir) {
      ir_function_signature *const sig = (ir_function_signature *) iter.get();

      sig->accept(this);
      printf("\n");
   }

   printf(")\n");
}

void ir_print_visitor::visit(ir_expression *ir)
{
   printf("(expression ");

   print_type(ir->type);

   printf(" %s ", ir->operator_string());

   if (ir->operands[0])
      ir->operands[0]->accept(this);

   if (ir->operands[1])
      ir->operands[1]->accept(this);
   printf(") ");
}

void ir_print_visitor::visit(ir_texture *ir)
{
   printf("(%s ", ir->opcode_string());

   ir->sampler->accept(this);
   printf(" ");

   ir->coordinate->accept(this);

   printf(" (%d %d %d) ", ir->offsets[0], ir->offsets[1], ir->offsets[2]);

   if (ir->op != ir_txf) {
      if (ir->projector)
	 ir->projector->accept(this);
      else
	 printf("1");

      if (ir->shadow_comparitor) {
	 printf(" ");
	 ir->shadow_comparitor->accept(this);
      } else {
	 printf(" ()");
      }
   }

   printf(" ");
   switch (ir->op)
   {
   case ir_tex:
      break;
   case ir_txb:
      ir->lod_info.bias->accept(this);
      break;
   case ir_txl:
   case ir_txf:
      ir->lod_info.lod->accept(this);
      break;
   case ir_txd:
      printf("(");
      ir->lod_info.grad.dPdx->accept(this);
      printf(" ");
      ir->lod_info.grad.dPdy->accept(this);
      printf(")");
      break;
   };
   printf(")");
}

void ir_print_visitor::visit(ir_swizzle *ir)
{
   const unsigned swiz[4] = {
      ir->mask.x,
      ir->mask.y,
      ir->mask.z,
      ir->mask.w,
   };

   printf("(swiz ");
   for (unsigned i = 0; i < ir->mask.num_components; i++) {
      printf("%c", "xyzw"[swiz[i]]);
   }
   printf(" ");
   ir->val->accept(this);
   printf(")");
}

void ir_print_visitor::visit(ir_dereference_variable *ir)
{
   ir_variable *var = ir->variable_referenced();
   printf("(var_ref %s@%p) ", var->name, var);
}

void ir_print_visitor::visit(ir_dereference_array *ir)
{
   printf("(array_ref ");
   ir->array->accept(this);
   ir->array_index->accept(this);
   printf(") ");
}

void ir_print_visitor::visit(ir_dereference_record *ir)
{
   printf("(record_ref ");
   ir->record->accept(this);
   printf(" %s) ", ir->field);
}

void ir_print_visitor::visit(ir_assignment *ir)
{
   printf("(assign ");

   if (ir->condition)
      ir->condition->accept(this);
   else
      printf("(constant bool (1))");

   printf(" ");

   ir->lhs->accept(this);

   printf(" ");

   ir->rhs->accept(this);
   printf(") ");
}

void ir_print_visitor::visit(ir_constant *ir)
{
   const glsl_type *const base_type = ir->type->get_base_type();

   printf("(constant ");
   print_type(ir->type);
   printf(" (");

   if (ir->type->is_array()) {
      for (unsigned i = 0; i < ir->type->length; i++)
	 ir->get_array_element(i)->accept(this);
   } else {
      for (unsigned i = 0; i < ir->type->components(); i++) {
	 if (i != 0)
	    printf(" ");
	 switch (base_type->base_type) {
	 case GLSL_TYPE_UINT:  printf("%u", ir->value.u[i]); break;
	 case GLSL_TYPE_INT:   printf("%d", ir->value.i[i]); break;
	 case GLSL_TYPE_FLOAT: printf("%f", ir->value.f[i]); break;
	 case GLSL_TYPE_BOOL:  printf("%d", ir->value.b[i]); break;
	 default: assert(0);
	 }
      }
   }
   printf(")) ");
}

void
ir_print_visitor::visit(ir_call *ir)
{
   printf("(call %s (", ir->callee_name());
   foreach_iter(exec_list_iterator, iter, *ir) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
   }
   printf("))\n");
}

void
ir_print_visitor::visit(ir_return *ir)
{
   printf("(return");

   ir_rvalue *const value = ir->get_value();
   if (value) {
      printf(" ");
      value->accept(this);
   }

   printf(")");
}

void
ir_print_visitor::visit(ir_discard *ir)
{
   printf("(discard ");

   if (ir->condition != NULL) {
      printf(" ");
      ir->condition->accept(this);
   }

   printf(")");
}

void
ir_print_visitor::visit(ir_if *ir)
{
   printf("(if ");
   ir->condition->accept(this);

   printf("(\n");
   foreach_iter(exec_list_iterator, iter, ir->then_instructions) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf(")\n");

   printf("(\n");
   foreach_iter(exec_list_iterator, iter, ir->else_instructions) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf("))\n");
}

void
ir_print_visitor::visit(ir_loop *ir)
{
   printf("(loop (");
   if (ir->counter != NULL)
      ir->counter->accept(this);
   printf(") (");
   if (ir->from != NULL)
      ir->from->accept(this);
   printf(") (");
   if (ir->to != NULL)
      ir->to->accept(this);
   printf(") (");
   if (ir->increment != NULL)
      ir->increment->accept(this);
   printf(") (\n");
   foreach_iter(exec_list_iterator, iter, ir->body_instructions) {
      ir_instruction *const inst = (ir_instruction *) iter.get();

      inst->accept(this);
      printf("\n");
   }
   printf("))\n");
}

void
ir_print_visitor::visit(ir_loop_jump *ir)
{
   printf("%s", ir->is_break() ? "break" : "continue");
}
<|endoftext|>


<commit_before>#include <SCD/File_Parsing/SimplestParsing.h>
#include <iostream>
#include <fstream>

using namespace FileParsing;

SimplestParsing::SimplestParsing()
{

}

SimplestParsing::~SimplestParsing()
{
}

void SimplestParsing::load(const char* filename)
{
  std::ifstream tmp_is(filename);

  if(!tmp_is.is_open())
  {
	  std::cout << "EXCEPTION : Unable to open File " << filename << std::endl;
		throw std::exception();
  }

  std::string strbuf;
  const unsigned BUF_SIZE = 500000;
  char buf[BUF_SIZE];

  do
  {
    tmp_is.read(buf, BUF_SIZE);
    strbuf += std::string(buf, BUF_SIZE);
  }
  while(!tmp_is.eof());

  stream_.str(strbuf);
}

std::stringstream& SimplestParsing::operator()()
{
	return stream_;
}

bool SimplestParsing::find(const std::string& s)
{
	bool b=false,ef= false;//b signifie que la chaine a t trouve, ef signifie que la fin de fichier est atteinte
	int i;
	while (!(b)&&!(ef))
	{
		i=0;
		b=true;
		while ((b)&&(static_cast<unsigned int>(i)<s.size()))
		{
			char a;
			stream_.get(a);
			if (stream_.eof())
			{
				b=false;
				ef=true;
			}
			if (a!=s[i++])
				b=false;

		}
		if (b) return true;//chaine trouve
		else
		{
			stream_.seekg(-i+1,std::ios_base::cur);//retour  la position qu'on avait avant de trouver les caractres semblables
		}
	}
	return b;

}

bool SimplestParsing::jumpSeparators()
{
	char c;
	do
	{
		stream_.get(c);
		if (stream_.eof())
			return false;//fin de fichier

	}while ((c==' ')||(c=='\t')||(c=='\n')||(c==13));//les caractres blances
	stream_.seekg(-1,std::ios_base::cur);//on revient car le dernier caractre n'est pas blanc
	return true;
}

bool SimplestParsing::checkIfNextString(const std::string & s)
{
	bool b=true;
	int i=0;
	while ((b)&&(static_cast<unsigned int>(i)<s.size()))//tant que la chaine correspond temporairement  celle en cours de lecture
	{
		char a;
		stream_.get(a);
		if (stream_.eof())
		{
			b=false;
			i--;
		}
		if (a!=s[i++])
			b=false;

	}
	if (b)
		return true; //chaine trouve
	else //chaine non trouve
	{
		stream_.seekg(-i,std::ios_base::cur);//retour  la case dpart
		return false;
	}

}

<commit_msg>Fix file reading.<commit_after>#include <SCD/File_Parsing/SimplestParsing.h>
#include <iostream>
#include <fstream>

using namespace FileParsing;

SimplestParsing::SimplestParsing()
{

}

SimplestParsing::~SimplestParsing()
{
}

void SimplestParsing::load(const char* filename)
{
  std::ifstream tmp_is(filename);

  if(!tmp_is.is_open())
  {
	  std::cout << "EXCEPTION : Unable to open File " << filename << std::endl;
		throw std::exception();
  }

  std::string strbuf;
  const unsigned BUF_SIZE = 500000;
  char buf[BUF_SIZE];

  do
  {
    tmp_is.read(buf, BUF_SIZE);
    strbuf += std::string(buf, tmp_is.gcount());
  }
  while(!tmp_is.eof());

  stream_.str(strbuf);
}

std::stringstream& SimplestParsing::operator()()
{
	return stream_;
}

bool SimplestParsing::find(const std::string& s)
{
	bool b=false,ef= false;//b signifie que la chaine a t trouve, ef signifie que la fin de fichier est atteinte
	int i;
	while (!(b)&&!(ef))
	{
		i=0;
		b=true;
		while ((b)&&(static_cast<unsigned int>(i)<s.size()))
		{
			char a;
			stream_.get(a);
			if (stream_.eof())
			{
				b=false;
				ef=true;
			}
			if (a!=s[i++])
				b=false;

		}
		if (b) return true;//chaine trouve
		else
		{
			stream_.seekg(-i+1,std::ios_base::cur);//retour  la position qu'on avait avant de trouver les caractres semblables
		}
	}
	return b;

}

bool SimplestParsing::jumpSeparators()
{
	char c;
	do
	{
		stream_.get(c);
		if (stream_.eof())
			return false;//fin de fichier

	}while ((c==' ')||(c=='\t')||(c=='\n')||(c==13));//les caractres blances
	stream_.seekg(-1,std::ios_base::cur);//on revient car le dernier caractre n'est pas blanc
	return true;
}

bool SimplestParsing::checkIfNextString(const std::string & s)
{
	bool b=true;
	int i=0;
	while ((b)&&(static_cast<unsigned int>(i)<s.size()))//tant que la chaine correspond temporairement  celle en cours de lecture
	{
		char a;
		stream_.get(a);
		if (stream_.eof())
		{
			b=false;
			i--;
		}
		if (a!=s[i++])
			b=false;

	}
	if (b)
		return true; //chaine trouve
	else //chaine non trouve
	{
		stream_.seekg(-i,std::ios_base::cur);//retour  la case dpart
		return false;
	}

}

<|endoftext|>


<commit_before>//
//  IgniteScene.cpp
//  show
//
//  Created by Chris Mullany on 02/09/2015.
//
//

#include "IgniteScene.h"

IgniteScene::IgniteScene() {
    name = "Ignite";
    averageVolume = 0;
}

void IgniteScene::setup() {
    radiusMin.set("radius min", 10, 0, 500);
    radiusMax.set("radius max", 200, 0, 500);
    noiseScale.set("noise scale", 80, 0, 500);
    threshold.set("threshold", 0.5, 0.0, 1.0);
    debugDraw.set("debug draw", false);
    // subscenes
    subsceneStart = 3;
    subsceneEnd = 9;
    // master needs to listen out for window volumes
    ofAddListener(this->osc->volumeEvent, this, &IgniteScene::onWindowVolume);
    ofAddListener(this->osc->volumeTriggerEvent, this, &IgniteScene::onWindowVolumeTrigger);
    SceneBase::setup();
}

void IgniteScene::update() {

    if (isWindow() && getWindowActive()) {
        mic->fftLive.setThreshold(threshold);
        mic->update();
        averageVolume = ofLerp(averageVolume, mic->fftLive.getAveragePeak(), 0.3);
        osc->sendVolume(averageVolume, appModel->windowId);
    }

    if (isMaster()) minTime.update();
    // In Subscene 8, each window is active
    // master listens to volumes sent over OSC
    // and triggers next scene when all have reached max
    if (subsceneI == 8 && isMaster()) {
        // Every window is active, need to get overall average/max
        bool allActive = true;
        for (int i = 0; i<WINDOW_COUNT; i++) {
            if (!windowTriggers[i]) allActive = false;
        }
        if (allActive) {
            ofLogNotice() << "IgniteScene::update target volume reached FOR ALL";
            nextSubscene();
        }
    }

    SceneBase::update();
}

void IgniteScene::draw() {
    /*
    if (isWindow() && getWindowActive()) {
        // draw a blob based on the average volume of the mic input
        float x = ofGetWidth()/2;
        float y = ofGetHeight()/2;
        int pointCount = 30;
        float outerRadius = ofMap(averageVolume, 0, 0.8, radiusMin, radiusMax);
        ofPath path;
        path.newSubPath();
        auto angleChangePerPt = ((pi) * 2) / pointCount;
        auto angle = pi * 0.5;
        path.moveTo(x + (outerRadius * cos(angle)), y + (outerRadius * sin(angle)));
        float time = ofGetElapsedTimef();
        ofPoint firstPoint;
        for (int i = 0; i < pointCount; i++) {
            auto rad = outerRadius + ofNoise(cos(angle)*time, sin(angle)*time) * noiseScale * averageVolume;
            auto vertX = x + (rad * cos(angle));
            auto vertY = y + (rad * sin(angle));
            if (i==0) firstPoint.set(vertX, vertY);
            path.curveTo(vertX, vertY);
            //path.circle(vertX, vertY, 10);
            angle += angleChangePerPt;
        };
        path.curveTo(firstPoint);
        path.setColor(ofColor(255));
        path.close();
        path.draw();
    }
     */

    if (isMaster()) {
        for (int i = 0; i<WINDOW_COUNT; i++) {
            if (windowTriggers[i]) ofSetColor(255);
            else ofSetColor(150);
            float h = windowVolumes[i] * (ofGetHeight()/2);
            ofRect(i*40, ofGetHeight(), 40, -h);
        }
        //int remaining = targetFrames - targetHitCount;
        ofDrawBitmapStringHighlight("Min time remaining: " + ofToString(minTime.progress), 10, ofGetHeight() - 220, ofColor(200, 0, 0));
        ofDrawBitmapStringHighlight("Audio peak count: " + ofToString(targetHitCount)+"/"+ofToString(targetFrames), 10, ofGetHeight() - 200, ofColor(200, 0, 0));
        ofSetColor(255);
    }

    SceneBase::draw();

    if (debugDraw) {
        mic->draw();
    }
}

//////////////////////////////////////////////////////////////////////////////////
// public
//////////////////////////////////////////////////////////////////////////////////
void IgniteScene::play(int i){

    // Initial subscene is blank
    if (i == 3) {
        if (isSlave()) led->show(title1.get());
        if (isMaster()) {
            countdown->start(0);//timeIntro.get());
        }
    }
    if(i == 4) {
        //osc->sendSoundCue(3); //Another Horrible Hack I'M SORRY CHRIS!
        if (isMaster()) {
            osc->sendLightSoundCue(intro);
            //osc->sendSoundCue(intro.soundCue);
        }
    }
    if(i == 5) {
        if (isMaster()) {
//            osc->sendLightingCue(FourToFive.lightCue, FourToFive.lightList);
//            osc->sendSoundCue(FourToFive.soundCue);
            osc->sendLightSoundCue(FourToFive);
        }
    }
    if(i == 6) {
        if (isMaster()) {
//            osc->sendLightingCue(FiveToSix.lightCue, FiveToSix.lightList);
//            osc->sendSoundCue(FiveToSix.soundCue);
            osc->sendLightSoundCue(FiveToSix);

        }
    }
    if(i == 7) {
        if (isMaster()) {
//            osc->sendLightingCue(SixToSeven.lightCue, SixToSeven.lightList);
//            osc->sendSoundCue(SixToSeven.soundCue);
            osc->sendLightSoundCue(SixToSeven);

        }
    }
    if(i == 8) {
        if (isMaster()) {
            osc->sendLightSoundCue(SevenToEight);
            osc->sendSoundCue(6.5);
//            osc->sendLightingCue(SevenToEight.lightCue, SevenToEight.lightList);
//            osc->sendSoundCue(SevenToEight.soundCue);
        }
    }

    // Active mic scenes, 1 to 4, then all 4
    if (i >= 4 && i <= 8) {
        if (isSlave()) {
            led->show(title1.get());
        }
        if (isMaster()) {
            int cueI = i - 4;
            countdown->stop();
            minTime.start(minMicTime.get());
            // reset values
            for (int i = 0; i<WINDOW_COUNT; i++) {
                windowTriggers[i] = false;
                windowVolumes[i] = 0;
                //osc->sendLightSoundCue(outCues[i]);
            }
        }
        // start audio input if this is the active window
        if (isWindow() && getWindowActive()) {
            targetHitCount = 0;
            mic->start();
        }
    }

    // countdown outro
    else if (i == 9) {
        if (isSlave()) {
            led->hide();
            led->queue(LedDisplay::Params(title1.get(), 0, 1, 15, false, 0));
            led->queue(LedDisplay::Params("", 0, 14, 0, false, 0));
            led->queue(LedDisplay::Params(title2, 0, 2, 0, false, 0));
            led->queue(LedDisplay::Params(title2, 0, 5, 0, false, 5));
            led->playQueue();
            //led->show(title2, countdownDuration);
        }
        if (isMaster()) {
            countdown->start(countdownDuration);
            cout<<"sent lighting cue 2 and sound cue 7"<<endl;
            osc->sendLightingCue(2);
            osc->sendSoundCue(7);
        }
    }

    SceneBase::play(i);
}

void IgniteScene::stop(){
    mic->stop();
    SceneBase::stop();
}

void IgniteScene::setupGui() {
    guiName = "Ignite";
    panel.setup(guiName, "settings/ignite.xml");

    // titles, times
    panel.add(title1.set("title 1", "VERY LOUD I CONE"));
    panel.add(title2.set("title 2", "Next Level"));
    panel.add(minMicTime.set("min mic time", 20, 1, 60));
    panel.add(timeIntro.set("intro time", 30, 1, 60));
    panel.add(countdownDuration.set("countdown", 37, 0, 20));

    // audio
    panel.add(targetVolume.set("target volume", 0.5, 0, 1));
    panel.add(targetFrames.set("target frames", 60, 1, 180));
    panel.add(threshold);
    panel.add(debugDraw);

    // cues
    for (int i=0; i<CUE_COUNT; i++) {
        panel.add(inCues[i].setup("Cue in" + ofToString(i), (i+1)*2));
        panel.add(outCues[i].setup("Cue out" + ofToString(i), ((i+1)*2)+1));
    }
    panel.add(intro.setup("Wall 1 Open", 1));
    panel.add(FourToFive.setup("Wall 2 Open", 1));
    panel.add(FiveToSix.setup("Wall 3 Open", 1));
    panel.add(SixToSeven.setup("Wall 4 Open", 1));
    panel.add(SevenToEight.setup("All Walls Open", 1));
    panel.add(nextCue.setup("Cue Next", 2));
    panel.loadFromFile("settings/ignite.xml");
}

void IgniteScene::drawGui() {
    GuiableBase::drawGui();
}

//////////////////////////////////////////////////////////////////////////////////
// protected
//////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////
// private
//////////////////////////////////////////////////////////////////////////////////
bool IgniteScene::getWindowActive() {
    bool active = false;
    if (mode==AppModel::WINDOW) {
        if (appModel->windowId == 1 && subsceneI >= 3) active = true;
        if (appModel->windowId == 2 && subsceneI >= 5) active = true;
        if (appModel->windowId == 3 && subsceneI >= 6) active = true;
        if (appModel->windowId == 4 && subsceneI >= 7) active = true;
        if (subsceneI > 8) active = false;
    }
    return active;
}

// Master only
// listener for window volume OSC messages
void IgniteScene::onWindowVolume(OscClient::VolumeEventArgs& args) {
    if (isMaster()) {
        int i = args.windowId - 1;
        if (args.windowId == subsceneI - 3 || subsceneI == 8) {
            //ofLogVerbose() << "window : " + ofToString(i) + " vol : " + ofToString(args.volume);
            float vol = args.volume;
            windowVolumes[i] = vol;
            if (vol > targetVolume) {
               osc->sendLightSoundCue(inCues[i]);
                //osc->sendLightingCue(inCues[i].lightCue);
                //osc->sendSoundCue(inCues[i].soundCue);
                if (targetHitCount++ > targetFrames && minTime.isComplete()) {
                    if (subsceneI == 8) {
                        // this is the final mode in which all windows are active
                        // mark this window as triggered
                        // when all are triggered, next scene will be called
                        windowTriggers[i] = true;
                    } else {
                        nextSubscene();
                        ofLogNotice() << "IgniteScene::update target volume reached, triggering next scene";
                        targetHitCount = 0;
                    }
                }
            }
            else {
                //osc->sendLightSoundCue(outCues[i]);
            }
        }
    }
}

void IgniteScene::onWindowVolumeTrigger(OscClient::VolumeEventArgs& args) {
}

//////////////////////////////////////////////////////////////////////////////////
// custom event handlers
//////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////
// oF event handlers
//////////////////////////////////////////////////////////////////////////////////

void IgniteScene::keyPressed (int key) {}

void IgniteScene::keyReleased (int key) {}

void IgniteScene::mouseMoved(int x, int y) {}

void IgniteScene::mouseDragged(int x, int y, int button) {}

void IgniteScene::mousePressed(int x, int y, int button) {}

void IgniteScene::mouseReleased(int x, int y, int button) {}

void IgniteScene::windowResized(int w, int h) {}

void IgniteScene::dragEvent(ofDragInfo dragInfo) {}

void IgniteScene::gotMessage(ofMessage msg) {}
<commit_msg>Turned off wall light-ups in lightbox sub scene 8<commit_after>//
//  IgniteScene.cpp
//  show
//
//  Created by Chris Mullany on 02/09/2015.
//
//

#include "IgniteScene.h"

IgniteScene::IgniteScene() {
    name = "Ignite";
    averageVolume = 0;
}

void IgniteScene::setup() {
    radiusMin.set("radius min", 10, 0, 500);
    radiusMax.set("radius max", 200, 0, 500);
    noiseScale.set("noise scale", 80, 0, 500);
    threshold.set("threshold", 0.5, 0.0, 1.0);
    debugDraw.set("debug draw", false);
    // subscenes
    subsceneStart = 3;
    subsceneEnd = 9;
    // master needs to listen out for window volumes
    ofAddListener(this->osc->volumeEvent, this, &IgniteScene::onWindowVolume);
    ofAddListener(this->osc->volumeTriggerEvent, this, &IgniteScene::onWindowVolumeTrigger);
    SceneBase::setup();
}

void IgniteScene::update() {

    if (isWindow() && getWindowActive()) {
        mic->fftLive.setThreshold(threshold);
        mic->update();
        averageVolume = ofLerp(averageVolume, mic->fftLive.getAveragePeak(), 0.3);
        osc->sendVolume(averageVolume, appModel->windowId);
    }

    if (isMaster()) minTime.update();
    // In Subscene 8, each window is active
    // master listens to volumes sent over OSC
    // and triggers next scene when all have reached max
    if (subsceneI == 8 && isMaster()) {
        // Every window is active, need to get overall average/max
        bool allActive = true;
        for (int i = 0; i<WINDOW_COUNT; i++) {
            if (!windowTriggers[i]) allActive = false;
        }
        if (allActive) {
            ofLogNotice() << "IgniteScene::update target volume reached FOR ALL";
            nextSubscene();
        }
    }

    SceneBase::update();
}

void IgniteScene::draw() {
    /*
    if (isWindow() && getWindowActive()) {
        // draw a blob based on the average volume of the mic input
        float x = ofGetWidth()/2;
        float y = ofGetHeight()/2;
        int pointCount = 30;
        float outerRadius = ofMap(averageVolume, 0, 0.8, radiusMin, radiusMax);
        ofPath path;
        path.newSubPath();
        auto angleChangePerPt = ((pi) * 2) / pointCount;
        auto angle = pi * 0.5;
        path.moveTo(x + (outerRadius * cos(angle)), y + (outerRadius * sin(angle)));
        float time = ofGetElapsedTimef();
        ofPoint firstPoint;
        for (int i = 0; i < pointCount; i++) {
            auto rad = outerRadius + ofNoise(cos(angle)*time, sin(angle)*time) * noiseScale * averageVolume;
            auto vertX = x + (rad * cos(angle));
            auto vertY = y + (rad * sin(angle));
            if (i==0) firstPoint.set(vertX, vertY);
            path.curveTo(vertX, vertY);
            //path.circle(vertX, vertY, 10);
            angle += angleChangePerPt;
        };
        path.curveTo(firstPoint);
        path.setColor(ofColor(255));
        path.close();
        path.draw();
    }
     */

    if (isMaster()) {
        for (int i = 0; i<WINDOW_COUNT; i++) {
            if (windowTriggers[i]) ofSetColor(255);
            else ofSetColor(150);
            float h = windowVolumes[i] * (ofGetHeight()/2);
            ofRect(i*40, ofGetHeight(), 40, -h);
        }
        //int remaining = targetFrames - targetHitCount;
        ofDrawBitmapStringHighlight("Min time remaining: " + ofToString(minTime.progress), 10, ofGetHeight() - 220, ofColor(200, 0, 0));
        ofDrawBitmapStringHighlight("Audio peak count: " + ofToString(targetHitCount)+"/"+ofToString(targetFrames), 10, ofGetHeight() - 200, ofColor(200, 0, 0));
        ofSetColor(255);
    }

    SceneBase::draw();

    if (debugDraw) {
        mic->draw();
    }
}

//////////////////////////////////////////////////////////////////////////////////
// public
//////////////////////////////////////////////////////////////////////////////////
void IgniteScene::play(int i){

    // Initial subscene is blank
    if (i == 3) {
        if (isSlave()) led->show(title1.get());
        if (isMaster()) {
            countdown->start(0);//timeIntro.get());
        }
    }
    if(i == 4) {
        //osc->sendSoundCue(3); //Another Horrible Hack I'M SORRY CHRIS!
        if (isMaster()) {
            osc->sendLightSoundCue(intro);
            //osc->sendSoundCue(intro.soundCue);
        }
    }
    if(i == 5) {
        if (isMaster()) {
//            osc->sendLightingCue(FourToFive.lightCue, FourToFive.lightList);
//            osc->sendSoundCue(FourToFive.soundCue);
            osc->sendLightSoundCue(FourToFive);
        }
    }
    if(i == 6) {
        if (isMaster()) {
//            osc->sendLightingCue(FiveToSix.lightCue, FiveToSix.lightList);
//            osc->sendSoundCue(FiveToSix.soundCue);
            osc->sendLightSoundCue(FiveToSix);

        }
    }
    if(i == 7) {
        if (isMaster()) {
//            osc->sendLightingCue(SixToSeven.lightCue, SixToSeven.lightList);
//            osc->sendSoundCue(SixToSeven.soundCue);
            osc->sendLightSoundCue(SixToSeven);

        }
    }
    if(i == 8) {
        if (isMaster()) {
            osc->sendLightSoundCue(SevenToEight);
            osc->sendSoundCue(6.5);
//            osc->sendLightingCue(SevenToEight.lightCue, SevenToEight.lightList);
//            osc->sendSoundCue(SevenToEight.soundCue);
        }
    }

    // Active mic scenes, 1 to 4, then all 4
    if (i >= 4 && i <= 8) {
        if (isSlave()) {
            led->show(title1.get());
        }
        if (isMaster()) {
            int cueI = i - 4;
            countdown->stop();
            minTime.start(minMicTime.get());
            // reset values
            for (int i = 0; i<WINDOW_COUNT; i++) {
                windowTriggers[i] = false;
                windowVolumes[i] = 0;
                //osc->sendLightSoundCue(outCues[i]);
            }
        }
        // start audio input if this is the active window
        if (isWindow() && getWindowActive()) {
            targetHitCount = 0;
            mic->start();
        }
    }

    // countdown outro
    else if (i == 9) {
        if (isSlave()) {
            led->hide();
            led->queue(LedDisplay::Params(title1.get(), 0, 1, 15, false, 0));
            led->queue(LedDisplay::Params("", 0, 14, 0, false, 0));
            led->queue(LedDisplay::Params(title2, 0, 2, 0, false, 0));
            led->queue(LedDisplay::Params(title2, 0, 5, 0, false, 5));
            led->playQueue();
            //led->show(title2, countdownDuration);
        }
        if (isMaster()) {
            countdown->start(countdownDuration);
            cout<<"sent lighting cue 2 and sound cue 7"<<endl;
            osc->sendLightingCue(2);
            osc->sendSoundCue(7);
        }
    }

    SceneBase::play(i);
}

void IgniteScene::stop(){
    mic->stop();
    SceneBase::stop();
}

void IgniteScene::setupGui() {
    guiName = "Ignite";
    panel.setup(guiName, "settings/ignite.xml");

    // titles, times
    panel.add(title1.set("title 1", "VERY LOUD I CONE"));
    panel.add(title2.set("title 2", "Next Level"));
    panel.add(minMicTime.set("min mic time", 20, 1, 60));
    panel.add(timeIntro.set("intro time", 30, 1, 60));
    panel.add(countdownDuration.set("countdown", 37, 0, 20));

    // audio
    panel.add(targetVolume.set("target volume", 0.5, 0, 1));
    panel.add(targetFrames.set("target frames", 60, 1, 180));
    panel.add(threshold);
    panel.add(debugDraw);

    // cues
    for (int i=0; i<CUE_COUNT; i++) {
        panel.add(inCues[i].setup("Cue in" + ofToString(i), (i+1)*2));
        panel.add(outCues[i].setup("Cue out" + ofToString(i), ((i+1)*2)+1));
    }
    panel.add(intro.setup("Wall 1 Open", 1));
    panel.add(FourToFive.setup("Wall 2 Open", 1));
    panel.add(FiveToSix.setup("Wall 3 Open", 1));
    panel.add(SixToSeven.setup("Wall 4 Open", 1));
    panel.add(SevenToEight.setup("All Walls Open", 1));
    panel.add(nextCue.setup("Cue Next", 2));
    panel.loadFromFile("settings/ignite.xml");
}

void IgniteScene::drawGui() {
    GuiableBase::drawGui();
}

//////////////////////////////////////////////////////////////////////////////////
// protected
//////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////
// private
//////////////////////////////////////////////////////////////////////////////////
bool IgniteScene::getWindowActive() {
    bool active = false;
    if (mode==AppModel::WINDOW) {
        if (appModel->windowId == 1 && subsceneI >= 3) active = true;
        if (appModel->windowId == 2 && subsceneI >= 5) active = true;
        if (appModel->windowId == 3 && subsceneI >= 6) active = true;
        if (appModel->windowId == 4 && subsceneI >= 7) active = true;
        if (subsceneI > 8) active = false;
    }
    return active;
}

// Master only
// listener for window volume OSC messages
void IgniteScene::onWindowVolume(OscClient::VolumeEventArgs& args) {
    if (isMaster()) {
        int i = args.windowId - 1;
        if (args.windowId == subsceneI - 3 || subsceneI == 8) {
            //ofLogVerbose() << "window : " + ofToString(i) + " vol : " + ofToString(args.volume);
            float vol = args.volume;
            windowVolumes[i] = vol;
            if (vol > targetVolume) {
               if (subsceneI != 8) osc->sendLightSoundCue(inCues[i]);
                //osc->sendLightingCue(inCues[i].lightCue);
                //osc->sendSoundCue(inCues[i].soundCue);
                if (targetHitCount++ > targetFrames && minTime.isComplete()) {
                    if (subsceneI == 8) {
                        // this is the final mode in which all windows are active
                        // mark this window as triggered
                        // when all are triggered, next scene will be called
                        windowTriggers[i] = true;
                    } else {
                        nextSubscene();
                        ofLogNotice() << "IgniteScene::update target volume reached, triggering next scene";
                        targetHitCount = 0;
                    }
                }
            }
            else {
                //osc->sendLightSoundCue(outCues[i]);
            }
        }
    }
}

void IgniteScene::onWindowVolumeTrigger(OscClient::VolumeEventArgs& args) {
}

//////////////////////////////////////////////////////////////////////////////////
// custom event handlers
//////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////
// oF event handlers
//////////////////////////////////////////////////////////////////////////////////

void IgniteScene::keyPressed (int key) {}

void IgniteScene::keyReleased (int key) {}

void IgniteScene::mouseMoved(int x, int y) {}

void IgniteScene::mouseDragged(int x, int y, int button) {}

void IgniteScene::mousePressed(int x, int y, int button) {}

void IgniteScene::mouseReleased(int x, int y, int button) {}

void IgniteScene::windowResized(int w, int h) {}

void IgniteScene::dragEvent(ofDragInfo dragInfo) {}

void IgniteScene::gotMessage(ofMessage msg) {}
<|endoftext|>


<commit_before>//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// Copyright (c) 2012, Matthew Renaud
// All rights reserved.
//
// Licensed under the FreeBSD license. See LICENSE file for details.
//
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#ifndef MRR_POSIX_FD_SELECT_HXX_
#define MRR_POSIX_FD_SELECT_HXX_

#include <sys/select.h>
#include <functional>
#include <vector>

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

namespace mrr {
namespace posix {

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

struct fd_select
{
  using function_type = std::function<void(int)>;

  fd_select()
    : timeout_is_set(false)
  {
    FD_ZERO(&readset);
    FD_ZERO(&writeset);
    FD_ZERO(&exceptset);
  }

  void set_timeout(long sec, long usec)
  {
    timeout.tv_sec = sec;
    timeout.tv_usec = usec;
    timeout_is_set = true;
  }

  int multiplex()
  {
    int retval;

    read_checkset = readset;
    write_checkset = writeset;
    except_checkset = exceptset;

    errno = 0;
    retval = ::select(
      FD_SETSIZE,
      &read_checkset,
      &write_checkset,
      &except_checkset,
      (timeout_is_set) ? &timeout : NULL   // Optionally set a timeout
    );

    if(retval == -1)
      return -1;

    std::size_t pos = 0;

    for(int fd : read_fds)
    {
      if(FD_ISSET(fd, &read_checkset))
	read_actions[pos](fd);
      ++pos;
    }

    pos = 0;
    for(int fd : write_fds)
    {
      if(FD_ISSET(fd, &write_checkset))
	write_actions[pos](fd);
      ++pos;
    }

    pos = 0;
    for(int fd : except_fds)
    {
      if(FD_ISSET(fd, &except_checkset))
	except_actions[pos](fd);
      ++pos;
    }

    return retval;

  } // int listen_with_action()

  void register_read_fd(int fd, function_type&& f)
  {
    read_fds.push_back(fd);
    FD_SET(fd, &readset);
    read_actions.push_back(f);
  }

  void register_write_fd(int fd, function_type&& f)
  {
    write_fds.push_back(fd);
    FD_SET(fd, &writeset);
    write_actions.push_back(f);
  }

  void register_except_fd(int fd, function_type&& f)
  {
    except_fds.push_back(fd);
    FD_SET(fd, &exceptset);
    except_actions.push_back(f);
  }

private:
  fd_set readset, read_checkset;
  fd_set writeset, write_checkset;
  fd_set exceptset, except_checkset;

  bool timeout_is_set;
  struct timeval timeout;

  std::vector<int> read_fds;
  std::vector<function_type> read_actions;

  std::vector<int> write_fds;
  std::vector<function_type> write_actions;

  std::vector<int> except_fds;
  std::vector<function_type> except_actions;

}; // struct fd_select

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

} // namespace posix
} // namespace mrr

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#endif // #ifndef MRR_POSIX_FD_SELECT_HXX_
<commit_msg>Modified fd_select's register functions to take function_type const&<commit_after>//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// Copyright (c) 2012, Matthew Renaud
// All rights reserved.
//
// Licensed under the FreeBSD license. See LICENSE file for details.
//
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#ifndef MRR_POSIX_FD_SELECT_HXX_
#define MRR_POSIX_FD_SELECT_HXX_

#include <sys/select.h>
#include <functional>
#include <vector>

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

namespace mrr {
namespace posix {

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

struct fd_select
{
  using function_type = std::function<void(int)>;

  fd_select()
    : timeout_is_set(false)
  {
    FD_ZERO(&readset);
    FD_ZERO(&writeset);
    FD_ZERO(&exceptset);
  }

  void set_timeout(long sec, long usec)
  {
    timeout.tv_sec = sec;
    timeout.tv_usec = usec;
    timeout_is_set = true;
  }

  int multiplex()
  {
    int retval;

    read_checkset = readset;
    write_checkset = writeset;
    except_checkset = exceptset;

    errno = 0;
    retval = ::select(
      FD_SETSIZE,
      &read_checkset,
      &write_checkset,
      &except_checkset,
      (timeout_is_set) ? &timeout : NULL   // Optionally set a timeout
    );

    if(retval == -1)
      return -1;

    std::size_t pos = 0;

    for(int fd : read_fds)
    {
      if(FD_ISSET(fd, &read_checkset))
	read_actions[pos](fd);
      ++pos;
    }

    pos = 0;
    for(int fd : write_fds)
    {
      if(FD_ISSET(fd, &write_checkset))
	write_actions[pos](fd);
      ++pos;
    }

    pos = 0;
    for(int fd : except_fds)
    {
      if(FD_ISSET(fd, &except_checkset))
	except_actions[pos](fd);
      ++pos;
    }

    return retval;

  } // int listen_with_action()

  void register_read_fd(int fd, function_type const& f)
  {
    read_fds.push_back(fd);
    FD_SET(fd, &readset);
    read_actions.push_back(f);
  }

  void register_write_fd(int fd, function_type const& f)
  {
    write_fds.push_back(fd);
    FD_SET(fd, &writeset);
    write_actions.push_back(f);
  }

  void register_except_fd(int fd, function_type const& f)
  {
    except_fds.push_back(fd);
    FD_SET(fd, &exceptset);
    except_actions.push_back(f);
  }

private:
  fd_set readset, read_checkset;
  fd_set writeset, write_checkset;
  fd_set exceptset, except_checkset;

  bool timeout_is_set;
  struct timeval timeout;

  std::vector<int> read_fds;
  std::vector<function_type> read_actions;

  std::vector<int> write_fds;
  std::vector<function_type> write_actions;

  std::vector<int> except_fds;
  std::vector<function_type> except_actions;

}; // struct fd_select

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

} // namespace posix
} // namespace mrr

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#endif // #ifndef MRR_POSIX_FD_SELECT_HXX_
<|endoftext|>


<commit_before>#include "recorder_base.h"
#include "globals.h"
#include "threads.h"
#include "sift_assert.h"
#include "recorder_control.h"
#include "syscall_modeling.h"

#include <iostream>

VOID countInsns(THREADID threadid, INT32 count)
{
   thread_data[threadid].icount += count;

   if (!any_thread_in_detail && thread_data[threadid].output)
   {
      thread_data[threadid].icount_reported += count;
      if (thread_data[threadid].icount_reported > KnobFlowControlFF.Value())
      {
         Sift::Mode mode = thread_data[threadid].output->InstructionCount(thread_data[threadid].icount_reported);
         thread_data[threadid].icount_reported = 0;
         setInstrumentationMode(mode);
      }
   }

   if (thread_data[threadid].icount >= fast_forward_target && !in_roi && !KnobUseROI.Value() && !KnobMPIImplicitROI.Value())
   {
      if (KnobVerbose.Value())
         std::cerr << "[SIFT_RECORDER:" << app_id << ":" << thread_data[threadid].thread_num << "] Changing to detailed after " << thread_data[threadid].icount << " instructions" << std::endl;
      if (!thread_data[threadid].output)
         openFile(threadid);
      thread_data[threadid].icount = 0;
      in_roi = true;
      setInstrumentationMode(Sift::ModeDetailed);
   }
}

VOID sendInstruction(THREADID threadid, ADDRINT addr, UINT32 size, UINT32 num_addresses, BOOL is_branch, BOOL taken, BOOL is_predicate, BOOL executing, BOOL isbefore, BOOL ispause)
{
   // We're still called for instructions in the same basic block as ROI end, ignore these
   if (!thread_data[threadid].output)
      return;

   ++thread_data[threadid].icount;
   ++thread_data[threadid].icount_detailed;

   // Reconstruct basic blocks (we could ask Pin, but do it the same way as TraceThread will do it)
   if (thread_data[threadid].bbv_end || thread_data[threadid].bbv_last != addr)
   {
      // We're the start of a new basic block
      thread_data[threadid].bbv->count(thread_data[threadid].bbv_base, thread_data[threadid].bbv_count);
      thread_data[threadid].bbv_base = addr;
      thread_data[threadid].bbv_count = 0;
   }
   thread_data[threadid].bbv_count++;
   thread_data[threadid].bbv_last = addr + size;
   // Force BBV end on non-taken branches
   thread_data[threadid].bbv_end = is_branch;

   sift_assert(thread_data[threadid].num_dyn_addresses == num_addresses);
   if (isbefore)
   {
      for(uint8_t i = 0; i < num_addresses; ++i)
      {
         // If the instruction hasn't executed yet, access the address to ensure a page fault if the mapping wasn't set up yet
         static char dummy = 0;
         dummy += *(char *)thread_data[threadid].dyn_addresses[i];
      }
   }

   thread_data[threadid].output->Instruction(addr, size, num_addresses, thread_data[threadid].dyn_addresses, is_branch, taken, is_predicate, executing);
   thread_data[threadid].num_dyn_addresses = 0;

   if (KnobUseResponseFiles.Value() && KnobFlowControl.Value() && (thread_data[threadid].icount > thread_data[threadid].flowcontrol_target || ispause))
   {
      Sift::Mode mode = thread_data[threadid].output->Sync();
      thread_data[threadid].flowcontrol_target = thread_data[threadid].icount + KnobFlowControl.Value();
      setInstrumentationMode(mode);
   }

   if (detailed_target != 0 && thread_data[threadid].icount_detailed >= detailed_target)
   {
      closeFile(threadid);
      PIN_Detach();
      return;
   }

   if (blocksize && thread_data[threadid].icount >= blocksize)
   {
      openFile(threadid);
      thread_data[threadid].icount = 0;
   }
}

VOID cacheOnlyUpdateInsCount(THREADID threadid, UINT32 icount)
{
   thread_data[threadid].icount_cacheonly_pending += icount;
}

VOID cacheOnlyConsumeAddresses(THREADID threadid)
{
   thread_data[threadid].num_dyn_addresses = 0;
}

VOID sendCacheOnly(THREADID threadid, UINT32 icount, UINT32 type, ADDRINT eip, ADDRINT arg)
{
   // We're still called for instructions in the same basic block as ROI end, ignore these
   if (!thread_data[threadid].output)
      return;

   cacheOnlyUpdateInsCount(threadid, icount);

   ADDRINT address;
   switch(Sift::CacheOnlyType(type))
   {
      case Sift::CacheOnlyMemRead:
      case Sift::CacheOnlyMemWrite:
         address = thread_data[threadid].dyn_addresses[arg];
         break;
      default:
         address = arg;
         break;
   }
   thread_data[threadid].output->CacheOnly(thread_data[threadid].icount_cacheonly_pending, Sift::CacheOnlyType(type), eip, address);

   thread_data[threadid].icount_cacheonly += thread_data[threadid].icount_cacheonly_pending;
   thread_data[threadid].icount_reported += thread_data[threadid].icount_cacheonly_pending;
   thread_data[threadid].icount_cacheonly_pending = 0;

   if (thread_data[threadid].icount_reported > KnobFlowControlFF.Value())
   {
      Sift::Mode mode = thread_data[threadid].output->Sync();
      thread_data[threadid].icount_reported = 0;
      setInstrumentationMode(mode);
   }
}

VOID handleMemory(THREADID threadid, ADDRINT address)
{
   // We're still called for instructions in the same basic block as ROI end, ignore these
   if (!thread_data[threadid].output)
      return;

   thread_data[threadid].dyn_addresses[thread_data[threadid].num_dyn_addresses++] = address;
}

UINT32 addMemoryModeling(INS ins)
{
   UINT32 num_addresses = 0;

   if (INS_IsMemoryRead (ins) || INS_IsMemoryWrite (ins))
   {
      for (unsigned int i = 0; i < INS_MemoryOperandCount(ins); i++)
      {
         INS_InsertCall(ins, IPOINT_BEFORE,
               AFUNPTR(handleMemory),
               IARG_THREAD_ID,
               IARG_MEMORYOP_EA, i,
               IARG_END);
         num_addresses++;
      }
   }
   sift_assert(num_addresses <= Sift::MAX_DYNAMIC_ADDRESSES);

   return num_addresses;
}

VOID insertCall(INS ins, IPOINT ipoint, UINT32 num_addresses, BOOL is_branch, BOOL taken)
{
   INS_InsertCall(ins, ipoint,
      AFUNPTR(sendInstruction),
      IARG_THREAD_ID,
      IARG_ADDRINT, INS_Address(ins),
      IARG_UINT32, UINT32(INS_Size(ins)),
      IARG_UINT32, num_addresses,
      IARG_BOOL, is_branch,
      IARG_BOOL, taken,
      IARG_BOOL, INS_IsPredicated(ins),
      IARG_EXECUTING,
      IARG_BOOL, ipoint == IPOINT_BEFORE,
      IARG_BOOL, INS_Opcode(ins) == XED_ICLASS_PAUSE,
      IARG_END);
}

static VOID traceCallback(TRACE trace, void *v)
{
   BBL bbl_head = TRACE_BblHead(trace);

   for (BBL bbl = bbl_head; BBL_Valid(bbl); bbl = BBL_Next(bbl))
   {
      for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
      {
         // Simics-style magic instruction: xchg bx, bx
         if (INS_IsXchg(ins) && INS_OperandReg(ins, 0) == REG_BX && INS_OperandReg(ins, 1) == REG_BX)
         {
            INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)handleMagic, IARG_RETURN_REGS, REG_GAX, IARG_THREAD_ID, IARG_REG_VALUE, REG_GAX,
#ifdef TARGET_IA32
                                     IARG_REG_VALUE, REG_GDX,
#else
                                     IARG_REG_VALUE, REG_GBX,
#endif
                                     IARG_REG_VALUE, REG_GCX, IARG_END);
         }

         // Handle emulated syscalls
         if (INS_IsSyscall(ins))
         {
            INS_InsertPredicatedCall(ins, IPOINT_BEFORE, AFUNPTR(emulateSyscallFunc), IARG_THREAD_ID, IARG_CONST_CONTEXT, IARG_END);
         }

         if (ins == BBL_InsTail(bbl))
            break;
      }

      if (!any_thread_in_detail)
      {
         BBL_InsertCall(bbl, IPOINT_ANYWHERE, (AFUNPTR)countInsns, IARG_THREAD_ID, IARG_UINT32, BBL_NumIns(bbl), IARG_END);
      }
      else if (current_mode == Sift::ModeDetailed)
      {
         for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
         {
            // For memory instructions, collect all addresses at IPOINT_BEFORE
            UINT32 num_addresses = addMemoryModeling(ins);

            bool is_branch = INS_IsBranch(ins) && INS_HasFallThrough(ins);

            if (is_branch)
            {
               insertCall(ins, IPOINT_AFTER,        num_addresses, true  /* is_branch */, false /* taken */);
               insertCall(ins, IPOINT_TAKEN_BRANCH, num_addresses, true  /* is_branch */, true  /* taken */);
            }
            else
            {
               // Whenever possible, use IPOINT_AFTER as this allows us to process addresses after the application has used them.
               // This ensures that their logical to physical mapping has been set up.
               insertCall(ins, INS_HasFallThrough(ins) ? IPOINT_AFTER : IPOINT_BEFORE, num_addresses, false /* is_branch */, false /* taken */);
            }

            if (ins == BBL_InsTail(bbl))
               break;
         }
      }
      else if (current_mode == Sift::ModeMemory)
      {
         UINT32 inscount = 0;

         for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
         {
            ++inscount;

            // For memory instructions, collect all addresses at IPOINT_BEFORE
            addMemoryModeling(ins);

            if (INS_IsMemoryRead (ins) || INS_IsMemoryWrite (ins))
            {
               // Prefer IPOINT_AFTER to maximize probability of physical mapping to be available
               IPOINT ipoint = INS_HasFallThrough(ins) ? IPOINT_AFTER : IPOINT_BEFORE;
               for (unsigned int idx = 0; idx < INS_MemoryOperandCount(ins); ++idx)
               {
                  if (INS_MemoryOperandIsRead(ins, idx))
                  {
                     INS_InsertCall(ins, ipoint,
                           AFUNPTR(sendCacheOnly),
                           IARG_THREAD_ID,
                           IARG_UINT32, inscount,
                           IARG_UINT32, UINT32(Sift::CacheOnlyMemRead),
                           IARG_ADDRINT, INS_Address(ins),
                           IARG_UINT32, UINT32(idx),
                           IARG_END);
                     inscount = 0;
                  }
                  if (INS_MemoryOperandIsWritten(ins, idx))
                  {
                     INS_InsertCall(ins, ipoint,
                           AFUNPTR(sendCacheOnly),
                           IARG_THREAD_ID,
                           IARG_UINT32, inscount,
                           IARG_UINT32, UINT32(Sift::CacheOnlyMemWrite),
                           IARG_ADDRINT, INS_Address(ins),
                           IARG_UINT32, UINT32(idx),
                           IARG_END);
                     inscount = 0;
                  }
               }
               INS_InsertCall(ins, ipoint,
                     AFUNPTR(cacheOnlyConsumeAddresses),
                     IARG_THREAD_ID,
                     IARG_END);
            }
            if (INS_IsBranch(ins) && INS_HasFallThrough(ins))
            {
               INS_InsertCall(ins, IPOINT_TAKEN_BRANCH,
                  AFUNPTR(sendCacheOnly),
                  IARG_THREAD_ID,
                  IARG_UINT32, inscount,
                  IARG_UINT32, UINT32(Sift::CacheOnlyBranchTaken),
                  IARG_ADDRINT, INS_Address(ins),
                  IARG_BRANCH_TARGET_ADDR,
                  IARG_END);
               INS_InsertCall(ins, IPOINT_AFTER,
                  AFUNPTR(sendCacheOnly),
                  IARG_THREAD_ID,
                  IARG_UINT32, inscount,
                  IARG_UINT32, Sift::CacheOnlyBranchNotTaken,
                  IARG_ADDRINT, INS_Address(ins),
                  IARG_FALLTHROUGH_ADDR,
                  IARG_END);
               inscount = 0;
            }

            if (ins == BBL_InsTail(bbl))
            {
               if (inscount)
                  INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(cacheOnlyUpdateInsCount), IARG_THREAD_ID, IARG_UINT32, inscount, IARG_END);
               break;
            }
         }
      }
   }
}

void initRecorderBase()
{
   TRACE_AddInstrumentFunction(traceCallback, 0);
}
<commit_msg>[sift] When ignoring instructions, also throw away their addresses<commit_after>#include "recorder_base.h"
#include "globals.h"
#include "threads.h"
#include "sift_assert.h"
#include "recorder_control.h"
#include "syscall_modeling.h"

#include <iostream>

VOID countInsns(THREADID threadid, INT32 count)
{
   thread_data[threadid].icount += count;

   if (!any_thread_in_detail && thread_data[threadid].output)
   {
      thread_data[threadid].icount_reported += count;
      if (thread_data[threadid].icount_reported > KnobFlowControlFF.Value())
      {
         Sift::Mode mode = thread_data[threadid].output->InstructionCount(thread_data[threadid].icount_reported);
         thread_data[threadid].icount_reported = 0;
         setInstrumentationMode(mode);
      }
   }

   if (thread_data[threadid].icount >= fast_forward_target && !in_roi && !KnobUseROI.Value() && !KnobMPIImplicitROI.Value())
   {
      if (KnobVerbose.Value())
         std::cerr << "[SIFT_RECORDER:" << app_id << ":" << thread_data[threadid].thread_num << "] Changing to detailed after " << thread_data[threadid].icount << " instructions" << std::endl;
      if (!thread_data[threadid].output)
         openFile(threadid);
      thread_data[threadid].icount = 0;
      in_roi = true;
      setInstrumentationMode(Sift::ModeDetailed);
   }
}

VOID sendInstruction(THREADID threadid, ADDRINT addr, UINT32 size, UINT32 num_addresses, BOOL is_branch, BOOL taken, BOOL is_predicate, BOOL executing, BOOL isbefore, BOOL ispause)
{
   // We're still called for instructions in the same basic block as ROI end, ignore these
   if (!thread_data[threadid].output)
   {
      thread_data[threadid].num_dyn_addresses = 0;
      return;
   }

   ++thread_data[threadid].icount;
   ++thread_data[threadid].icount_detailed;

   // Reconstruct basic blocks (we could ask Pin, but do it the same way as TraceThread will do it)
   if (thread_data[threadid].bbv_end || thread_data[threadid].bbv_last != addr)
   {
      // We're the start of a new basic block
      thread_data[threadid].bbv->count(thread_data[threadid].bbv_base, thread_data[threadid].bbv_count);
      thread_data[threadid].bbv_base = addr;
      thread_data[threadid].bbv_count = 0;
   }
   thread_data[threadid].bbv_count++;
   thread_data[threadid].bbv_last = addr + size;
   // Force BBV end on non-taken branches
   thread_data[threadid].bbv_end = is_branch;

   sift_assert(thread_data[threadid].num_dyn_addresses == num_addresses);
   if (isbefore)
   {
      for(uint8_t i = 0; i < num_addresses; ++i)
      {
         // If the instruction hasn't executed yet, access the address to ensure a page fault if the mapping wasn't set up yet
         static char dummy = 0;
         dummy += *(char *)thread_data[threadid].dyn_addresses[i];
      }
   }

   thread_data[threadid].output->Instruction(addr, size, num_addresses, thread_data[threadid].dyn_addresses, is_branch, taken, is_predicate, executing);
   thread_data[threadid].num_dyn_addresses = 0;

   if (KnobUseResponseFiles.Value() && KnobFlowControl.Value() && (thread_data[threadid].icount > thread_data[threadid].flowcontrol_target || ispause))
   {
      Sift::Mode mode = thread_data[threadid].output->Sync();
      thread_data[threadid].flowcontrol_target = thread_data[threadid].icount + KnobFlowControl.Value();
      setInstrumentationMode(mode);
   }

   if (detailed_target != 0 && thread_data[threadid].icount_detailed >= detailed_target)
   {
      closeFile(threadid);
      PIN_Detach();
      return;
   }

   if (blocksize && thread_data[threadid].icount >= blocksize)
   {
      openFile(threadid);
      thread_data[threadid].icount = 0;
   }
}

VOID cacheOnlyUpdateInsCount(THREADID threadid, UINT32 icount)
{
   thread_data[threadid].icount_cacheonly_pending += icount;
}

VOID cacheOnlyConsumeAddresses(THREADID threadid)
{
   thread_data[threadid].num_dyn_addresses = 0;
}

VOID sendCacheOnly(THREADID threadid, UINT32 icount, UINT32 type, ADDRINT eip, ADDRINT arg)
{
   // We're still called for instructions in the same basic block as ROI end, ignore these
   if (!thread_data[threadid].output)
      return;

   cacheOnlyUpdateInsCount(threadid, icount);

   ADDRINT address;
   switch(Sift::CacheOnlyType(type))
   {
      case Sift::CacheOnlyMemRead:
      case Sift::CacheOnlyMemWrite:
         address = thread_data[threadid].dyn_addresses[arg];
         break;
      default:
         address = arg;
         break;
   }
   thread_data[threadid].output->CacheOnly(thread_data[threadid].icount_cacheonly_pending, Sift::CacheOnlyType(type), eip, address);

   thread_data[threadid].icount_cacheonly += thread_data[threadid].icount_cacheonly_pending;
   thread_data[threadid].icount_reported += thread_data[threadid].icount_cacheonly_pending;
   thread_data[threadid].icount_cacheonly_pending = 0;

   if (thread_data[threadid].icount_reported > KnobFlowControlFF.Value())
   {
      Sift::Mode mode = thread_data[threadid].output->Sync();
      thread_data[threadid].icount_reported = 0;
      setInstrumentationMode(mode);
   }
}

VOID handleMemory(THREADID threadid, ADDRINT address)
{
   // We're still called for instructions in the same basic block as ROI end, ignore these
   if (!thread_data[threadid].output)
      return;

   thread_data[threadid].dyn_addresses[thread_data[threadid].num_dyn_addresses++] = address;
}

UINT32 addMemoryModeling(INS ins)
{
   UINT32 num_addresses = 0;

   if (INS_IsMemoryRead (ins) || INS_IsMemoryWrite (ins))
   {
      for (unsigned int i = 0; i < INS_MemoryOperandCount(ins); i++)
      {
         INS_InsertCall(ins, IPOINT_BEFORE,
               AFUNPTR(handleMemory),
               IARG_THREAD_ID,
               IARG_MEMORYOP_EA, i,
               IARG_END);
         num_addresses++;
      }
   }
   sift_assert(num_addresses <= Sift::MAX_DYNAMIC_ADDRESSES);

   return num_addresses;
}

VOID insertCall(INS ins, IPOINT ipoint, UINT32 num_addresses, BOOL is_branch, BOOL taken)
{
   INS_InsertCall(ins, ipoint,
      AFUNPTR(sendInstruction),
      IARG_THREAD_ID,
      IARG_ADDRINT, INS_Address(ins),
      IARG_UINT32, UINT32(INS_Size(ins)),
      IARG_UINT32, num_addresses,
      IARG_BOOL, is_branch,
      IARG_BOOL, taken,
      IARG_BOOL, INS_IsPredicated(ins),
      IARG_EXECUTING,
      IARG_BOOL, ipoint == IPOINT_BEFORE,
      IARG_BOOL, INS_Opcode(ins) == XED_ICLASS_PAUSE,
      IARG_END);
}

static VOID traceCallback(TRACE trace, void *v)
{
   BBL bbl_head = TRACE_BblHead(trace);

   for (BBL bbl = bbl_head; BBL_Valid(bbl); bbl = BBL_Next(bbl))
   {
      for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
      {
         // Simics-style magic instruction: xchg bx, bx
         if (INS_IsXchg(ins) && INS_OperandReg(ins, 0) == REG_BX && INS_OperandReg(ins, 1) == REG_BX)
         {
            INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)handleMagic, IARG_RETURN_REGS, REG_GAX, IARG_THREAD_ID, IARG_REG_VALUE, REG_GAX,
#ifdef TARGET_IA32
                                     IARG_REG_VALUE, REG_GDX,
#else
                                     IARG_REG_VALUE, REG_GBX,
#endif
                                     IARG_REG_VALUE, REG_GCX, IARG_END);
         }

         // Handle emulated syscalls
         if (INS_IsSyscall(ins))
         {
            INS_InsertPredicatedCall(ins, IPOINT_BEFORE, AFUNPTR(emulateSyscallFunc), IARG_THREAD_ID, IARG_CONST_CONTEXT, IARG_END);
         }

         if (ins == BBL_InsTail(bbl))
            break;
      }

      if (!any_thread_in_detail)
      {
         BBL_InsertCall(bbl, IPOINT_ANYWHERE, (AFUNPTR)countInsns, IARG_THREAD_ID, IARG_UINT32, BBL_NumIns(bbl), IARG_END);
      }
      else if (current_mode == Sift::ModeDetailed)
      {
         for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
         {
            // For memory instructions, collect all addresses at IPOINT_BEFORE
            UINT32 num_addresses = addMemoryModeling(ins);

            bool is_branch = INS_IsBranch(ins) && INS_HasFallThrough(ins);

            if (is_branch)
            {
               insertCall(ins, IPOINT_AFTER,        num_addresses, true  /* is_branch */, false /* taken */);
               insertCall(ins, IPOINT_TAKEN_BRANCH, num_addresses, true  /* is_branch */, true  /* taken */);
            }
            else
            {
               // Whenever possible, use IPOINT_AFTER as this allows us to process addresses after the application has used them.
               // This ensures that their logical to physical mapping has been set up.
               insertCall(ins, INS_HasFallThrough(ins) ? IPOINT_AFTER : IPOINT_BEFORE, num_addresses, false /* is_branch */, false /* taken */);
            }

            if (ins == BBL_InsTail(bbl))
               break;
         }
      }
      else if (current_mode == Sift::ModeMemory)
      {
         UINT32 inscount = 0;

         for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
         {
            ++inscount;

            // For memory instructions, collect all addresses at IPOINT_BEFORE
            addMemoryModeling(ins);

            if (INS_IsMemoryRead (ins) || INS_IsMemoryWrite (ins))
            {
               // Prefer IPOINT_AFTER to maximize probability of physical mapping to be available
               IPOINT ipoint = INS_HasFallThrough(ins) ? IPOINT_AFTER : IPOINT_BEFORE;
               for (unsigned int idx = 0; idx < INS_MemoryOperandCount(ins); ++idx)
               {
                  if (INS_MemoryOperandIsRead(ins, idx))
                  {
                     INS_InsertCall(ins, ipoint,
                           AFUNPTR(sendCacheOnly),
                           IARG_THREAD_ID,
                           IARG_UINT32, inscount,
                           IARG_UINT32, UINT32(Sift::CacheOnlyMemRead),
                           IARG_ADDRINT, INS_Address(ins),
                           IARG_UINT32, UINT32(idx),
                           IARG_END);
                     inscount = 0;
                  }
                  if (INS_MemoryOperandIsWritten(ins, idx))
                  {
                     INS_InsertCall(ins, ipoint,
                           AFUNPTR(sendCacheOnly),
                           IARG_THREAD_ID,
                           IARG_UINT32, inscount,
                           IARG_UINT32, UINT32(Sift::CacheOnlyMemWrite),
                           IARG_ADDRINT, INS_Address(ins),
                           IARG_UINT32, UINT32(idx),
                           IARG_END);
                     inscount = 0;
                  }
               }
               INS_InsertCall(ins, ipoint,
                     AFUNPTR(cacheOnlyConsumeAddresses),
                     IARG_THREAD_ID,
                     IARG_END);
            }
            if (INS_IsBranch(ins) && INS_HasFallThrough(ins))
            {
               INS_InsertCall(ins, IPOINT_TAKEN_BRANCH,
                  AFUNPTR(sendCacheOnly),
                  IARG_THREAD_ID,
                  IARG_UINT32, inscount,
                  IARG_UINT32, UINT32(Sift::CacheOnlyBranchTaken),
                  IARG_ADDRINT, INS_Address(ins),
                  IARG_BRANCH_TARGET_ADDR,
                  IARG_END);
               INS_InsertCall(ins, IPOINT_AFTER,
                  AFUNPTR(sendCacheOnly),
                  IARG_THREAD_ID,
                  IARG_UINT32, inscount,
                  IARG_UINT32, Sift::CacheOnlyBranchNotTaken,
                  IARG_ADDRINT, INS_Address(ins),
                  IARG_FALLTHROUGH_ADDR,
                  IARG_END);
               inscount = 0;
            }

            if (ins == BBL_InsTail(bbl))
            {
               if (inscount)
                  INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(cacheOnlyUpdateInsCount), IARG_THREAD_ID, IARG_UINT32, inscount, IARG_END);
               break;
            }
         }
      }
   }
}

void initRecorderBase()
{
   TRACE_AddInstrumentFunction(traceCallback, 0);
}
<|endoftext|>