<commit_before>/*
 * This file is part of SpeakEasy.
 * Copyright (C) 2011-2013  Lambert Clara <lambert.clara@yahoo.fr>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @mainpage SpeakEasy documentation
 * @file    main.cpp
 * @brief   SpeakEasy main
 *
 * @author  Lambert Clara <lambert.clara@yahoo.fr>
 * @date    Created : 2011-08-19
 */

// activate debug console output on WIN32 and debug target
#if defined(WIN32) && ! defined(NDEBUG)
#    pragma comment(linker, "/SUBSYSTEM:CONSOLE")
#endif // WIN32 && !NDEBUG

#include <csignal>
#include <cstdlib>
#include <thread>

#include "SE_CGUIManager.h"
#include "SE_CLogManager.h"
#include "SE_CMemoryManager.h"
#include "SE_CRenderManager.h"

#include "SE_CClock.h"

const U32 g_IdealFPS = 60;
const F32 g_IdealFrameTime = 1000.f/g_IdealFPS;

bool gs_EngineRunning = true;

static SE_CLogManager      gs_LogManager;
static SE_CMemoryManager   gs_MemoryManager;
static SE_CGUIManager      gs_GUIManager;
static SE_CRenderManager   gs_RenderManager;

static SE_CClock           gs_MainClock;

// AudioManager
// InputManager
// ErrorManager
// ResourceManager
// PhysicsManager
// SceneManager

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void handleCommandLineArguments(I32 const inArgc,
                                const char * const * const inpArgv)
{
    for(I32 i = 0; i < inArgc; ++i)
    {
        seLogDebug("inpArgv[", i, "] = ", inpArgv[i]);
    }
}

#if !defined(WIN32)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void signalHandler(const I32 inSignalCode)
{
    seLogDebug("Caught signal ", inSignalCode);
    gs_EngineRunning = false;
}
#endif // !defined(WIN32)

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
I32 main(I32 const inArgc,
         char const * const * const inpArgv)
{
#ifdef WIN32
    // get the arguments usually set by WinMain
    HINSTANCE const hInstance = GetModuleHandle(nullptr);
    int const       nCmdShow  = SW_SHOWDEFAULT;
    (void)hInstance;
    (void)nCmdShow;
#else // WIN32
    // Setup signal catching
    struct sigaction currentAction;
    currentAction.sa_handler = signalHandler;
    sigaction(SIGINT, &currentAction, NULL);
#endif // WIN32

    // Start up engine systems in the correct order, starting with log manager
    bool startUpSuccess = gs_LogManager.startUp(ELogLevel::kDebug);
    seLogDebug("SE_DEBUG defined");

    // handle the command line arguments
    handleCommandLineArguments(inArgc, inpArgv);

    startUpSuccess = startUpSuccess && gs_MemoryManager.startUp();
    startUpSuccess = startUpSuccess && gs_GUIManager.startUp();
    startUpSuccess = startUpSuccess && gs_RenderManager.startUp();

    if(startUpSuccess)
    {
        // Start the main clock
        gs_MainClock.start();

        seLogDebug("SpeakEasy subsystems successfully started");

        U32 framesCount = 0;
        F32 timeSeconds = 0.f;
        while(gs_EngineRunning) // main game loop
        {
            F32 const deltaSeconds = gs_MainClock.update();
            {
                gs_RenderManager.render();
                ++framesCount;
                gs_EngineRunning &= gs_GUIManager.doWork();
            }

            // Output FPS to command line
            timeSeconds += deltaSeconds;
            if(timeSeconds > 1000.0f)
            {
                seLogDebug("FPS:", (1000*framesCount)/timeSeconds);
                timeSeconds = 0.f;
                framesCount = 0;
            }
        }
    }
    else
    {
        seLogDebug("SpeakEasy subsystems failed to start");
    }

    seLogDebug("Exiting...");

    // Shut everything down, in reverse order
    bool shutDownSuccess = gs_RenderManager.shutDown();
    shutDownSuccess &= gs_GUIManager.shutDown();
    shutDownSuccess &= gs_MemoryManager.shutDown();
    shutDownSuccess &= gs_LogManager.shutDown();

    return shutDownSuccess ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>Add a message when subsystems correctly shut downed<commit_after>/*
 * This file is part of SpeakEasy.
 * Copyright (C) 2011-2013  Lambert Clara <lambert.clara@yahoo.fr>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @mainpage SpeakEasy documentation
 * @file    main.cpp
 * @brief   SpeakEasy main
 *
 * @author  Lambert Clara <lambert.clara@yahoo.fr>
 * @date    Created : 2011-08-19
 */

// activate debug console output on WIN32 and debug target
#if defined(WIN32) && ! defined(NDEBUG)
#    pragma comment(linker, "/SUBSYSTEM:CONSOLE")
#endif // WIN32 && !NDEBUG

#include <csignal>
#include <cstdlib>
#include <thread>

#include "SE_CGUIManager.h"
#include "SE_CLogManager.h"
#include "SE_CMemoryManager.h"
#include "SE_CRenderManager.h"

#include "SE_CClock.h"

const U32 g_IdealFPS = 60;
const F32 g_IdealFrameTime = 1000.f/g_IdealFPS;

bool gs_EngineRunning = true;

static SE_CLogManager      gs_LogManager;
static SE_CMemoryManager   gs_MemoryManager;
static SE_CGUIManager      gs_GUIManager;
static SE_CRenderManager   gs_RenderManager;

static SE_CClock           gs_MainClock;

// AudioManager
// InputManager
// ErrorManager
// ResourceManager
// PhysicsManager
// SceneManager

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void handleCommandLineArguments(I32 const inArgc,
                                const char * const * const inpArgv)
{
    for(I32 i = 0; i < inArgc; ++i)
    {
        seLogDebug("inpArgv[", i, "] = ", inpArgv[i]);
    }
}

#if !defined(WIN32)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void signalHandler(const I32 inSignalCode)
{
    seLogDebug("Caught signal ", inSignalCode);
    gs_EngineRunning = false;
}
#endif // !defined(WIN32)

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
I32 main(I32 const inArgc,
         char const * const * const inpArgv)
{
#ifdef WIN32
    // get the arguments usually set by WinMain
    HINSTANCE const hInstance = GetModuleHandle(nullptr);
    int const       nCmdShow  = SW_SHOWDEFAULT;
    (void)hInstance;
    (void)nCmdShow;
#else // WIN32
    // Setup signal catching
    struct sigaction currentAction;
    currentAction.sa_handler = signalHandler;
    sigaction(SIGINT, &currentAction, NULL);
#endif // WIN32

    // Start up engine systems in the correct order, starting with log manager
    bool startUpSuccess = gs_LogManager.startUp(ELogLevel::kDebug);
    seLogDebug("SE_DEBUG defined");

    // handle the command line arguments
    handleCommandLineArguments(inArgc, inpArgv);

    startUpSuccess = startUpSuccess && gs_MemoryManager.startUp();
    startUpSuccess = startUpSuccess && gs_GUIManager.startUp();
    startUpSuccess = startUpSuccess && gs_RenderManager.startUp();

    if(startUpSuccess)
    {
        // Start the main clock
        gs_MainClock.start();

        seLogDebug("SpeakEasy subsystems successfully started");

        U32 framesCount = 0;
        F32 timeSeconds = 0.f;
        while(gs_EngineRunning) // main game loop
        {
            F32 const deltaSeconds = gs_MainClock.update();
            {
                gs_RenderManager.render();
                ++framesCount;
                gs_EngineRunning &= gs_GUIManager.doWork();
            }

            // Output FPS to command line
            timeSeconds += deltaSeconds;
            if(timeSeconds > 1000.0f)
            {
                seLogDebug("FPS:", (1000*framesCount)/timeSeconds);
                timeSeconds = 0.f;
                framesCount = 0;
            }
        }
    }
    else
    {
        seLogDebug("SpeakEasy subsystems failed to start");
    }

    seLogDebug("Exiting...");

    // Shut everything down, in reverse order
    bool shutDownSuccess = gs_RenderManager.shutDown();
    shutDownSuccess &= gs_GUIManager.shutDown();
    shutDownSuccess &= gs_MemoryManager.shutDown();
    shutDownSuccess &= gs_LogManager.shutDown();

    if(shutDownSuccess)
    {
        seLogDebug("SpeakEasy subsystems successfully shut downed");
    }

    return shutDownSuccess ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>

using namespace std;

void connectors(string userinput, vector<int> &x, vector<int> &y, bool &first) {
	for(unsigned int i = 0; i < userinput.size() - 1; i++) {
		if((userinput.at(i) == '|') && (userinput.at(i + 1) == '|')) {
			x.push_back(0);
			y.push_back(i);
		}
		else if((userinput.at(i) == '&') && (userinput.at(i + 1) == '&')) {
			x.push_back(1);
			y.push_back(i);
		}
		else if((userinput.at(i) == ';')) {
			x.push_back(2);
			y.push_back(i);
		}
	}
	if(userinput.at(0) == '&' || userinput.at(0) == '|' || userinput.at(0) == ';')
		first = true;
	x.push_back(-1);
}

int main() {
	string userinput;
	string login;
	if(!getlogin())
		perror("getlogin");
	else
		login = getlogin();
	char hostname[128];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");
	char limits[6] = ";&| \t";
	bool ext  = false;
	while(!ext) {
		cout << getlogin() << "@" << hostname << " $ ";
		char *command_a;
		char *command;
		getline(cin, userinput);
		if(userinput.size() == 0)
			userinput+="#";
		command = new char[userinput.size()];
		vector<int> c_pat;
		vector<int> c_pos;
		bool first = false;
		userinput.size();
		connectors(userinput, c_pat, c_pos, first);
		int x = 0;
		unsigned int b = 0;
		int y = 0;
		char *arg[100000];
		while(userinput.substr(x, c_pos.at(y) -x)) {
			if(first) {
				cout << "Error: file does not exist" << endl;
				break;
			}
			if(c_pat.size() == 1)
				strcpy(command, userinput.c_str());
			else
				strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
			command_a = strtok(command,limits);
			while(command_a != NULL) {
				if(command_a[0] == '#')
					break;
				arg[b] = command_a;
				command_a = strtok(NULL, limits);
				b++;
			}
			int i = fork();
			if(i ==  -1)
				perror("fork");
			if(i == 0) {
				if(execvp(arg[0], arg) == -1)
					perror("execvp");
				exit(0);
			}
			int status;
			wait(&status);
			x = c_pos.at(y);
			unsigned int help = c_pat.at(y);
			for(unsigned int i = 0; i < b; i++)
				arg[i] = NULL;
			if(help == 0 && status != -1 && userinput.find("&&", y) != string::npos && userinput.find(";", y) != string::npos)
				y++;
			else if(help == 0 && status != -1) {
				y++;
				break;
			}
			if(help == 1 && status == -1 && userinput.find("||", y) != string::npos && userinput.find(";", y) != string::npos)
				y++;
			else if(help == 1 && status == -1) {
				y++;
				break;
			}
			else
				y++;
			b = 0;
		}

	}
	return 0;
}
<commit_msg>found algorithm solution?<commit_after>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>

using namespace std;

void connectors(string userinput, vector<int> &x, vector<int> &y, bool &first) {
	for(unsigned int i = 0; i < userinput.size() - 1; i++) {
		if((userinput.at(i) == '|') && (userinput.at(i + 1) == '|')) {
			x.push_back(0);
			y.push_back(i);
		}
		else if((userinput.at(i) == '&') && (userinput.at(i + 1) == '&')) {
			x.push_back(1);
			y.push_back(i);
		}
		else if((userinput.at(i) == ';')) {
			x.push_back(2);
			y.push_back(i);
		}
	}
	if(userinput.at(0) == '&' || userinput.at(0) == '|' || userinput.at(0) == ';')
		first = true;
	x.push_back(userinput.size() - 1);
	y.push_back(userinput.size() - 1);
}

int main() {
	string userinput;
	string login;
	if(!getlogin())
		perror("getlogin");
	else
		login = getlogin();
	char hostname[128];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");
	char limits[6] = ";&| \t";
	bool ext  = false;
	while(!ext) {
		cout << getlogin() << "@" << hostname << " $ ";
		char *command_a;
		char *command;
		getline(cin, userinput);
		if(userinput.size() == 0)
			userinput+="#";
		command = new char[userinput.size()];
		vector<int> c_pat;
		vector<int> c_pos;
		bool first = false;
		userinput.size();
		connectors(userinput, c_pat, c_pos, first);
		int x = 0;
		unsigned int b = 0;
		int y = 0;
		char *arg[100000];
		while(userinput.substr(x + 1, 1) != ""){
			if(first) {
				cout << "Error: file does not exist" << endl;
				break;
			}
			if(c_pat.size() == 1)
				strcpy(command, userinput.c_str());
			else
				strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
			command_a = strtok(command,limits);
			while(command_a != NULL) {
				if(command_a[0] == '#')
					break;
				arg[b] = command_a;
				command_a = strtok(NULL, limits);
				b++;
			}
			int i = fork();
			if(i ==  -1)
				perror("fork");
			if(i == 0) {
				if(execvp(arg[0], arg) == -1)
					perror("execvp");
				exit(0);
			}
			int status;
			wait(&status);
			x = c_pos.at(y);
			unsigned int help = c_pat.at(y);
			for(unsigned int i = 0; i < b; i++)
				arg[i] = NULL;
			if(help == 0 && status != -1 && userinput.find("&&", y) != string::npos && userinput.find(";", y) != string::npos)
				y++;
			else if(help == 0 && status != -1) {
				y++;
				break;
			}
			if(help == 1 && status == -1 && userinput.find("||", y) != string::npos && userinput.find(";", y) != string::npos)
				y++;
			else if(help == 1 && status == -1) {
				y++;
				break;
			}
			else
				y++;
			b = 0;
		}

	}
	return 0;
}
<|endoftext|>


<commit_before><commit_msg>fix compilation of LONG unit tests<commit_after><|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.
 */

/**
 * \file ir_algebraic.cpp
 *
 * Takes advantage of association, commutivity, and other algebraic
 * properties to simplify expressions.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_optimization.h"
#include "glsl_types.h"

/**
 * Visitor class for replacing expressions with ir_constant values.
 */

class ir_algebraic_visitor : public ir_hierarchical_visitor {
public:
   ir_algebraic_visitor()
   {
      this->progress = false;
   }

   virtual ~ir_algebraic_visitor()
   {
   }

   virtual ir_visitor_status visit_leave(ir_assignment *);
   virtual ir_visitor_status visit_leave(ir_call *);
   virtual ir_visitor_status visit_leave(ir_dereference_array *);
   virtual ir_visitor_status visit_leave(ir_expression *);
   virtual ir_visitor_status visit_leave(ir_if *);
   virtual ir_visitor_status visit_leave(ir_return *);
   virtual ir_visitor_status visit_leave(ir_swizzle *);
   virtual ir_visitor_status visit_leave(ir_texture *);

   ir_rvalue *handle_expression(ir_rvalue *in_ir);

   bool progress;
};

static bool
is_vec_zero(ir_constant *ir)
{
   int c;

   if (!ir)
      return false;
   if (!ir->type->is_scalar() &&
       !ir->type->is_vector())
      return false;

   for (c = 0; c < ir->type->vector_elements; c++) {
      switch (ir->type->base_type) {
      case GLSL_TYPE_FLOAT:
	 if (ir->value.f[c] != 0.0)
	    return false;
	 break;
      case GLSL_TYPE_INT:
	 if (ir->value.i[c] != 0)
	    return false;
	 break;
      case GLSL_TYPE_UINT:
	 if (ir->value.u[c] != 0)
	    return false;
	 break;
      case GLSL_TYPE_BOOL:
	 if (ir->value.b[c] != false)
	    return false;
	 break;
      default:
	 assert(!"bad base type");
	 return false;
      }
   }

   return true;
}

static bool
is_vec_one(ir_constant *ir)
{
   int c;

   if (!ir)
      return false;
   if (!ir->type->is_scalar() &&
       !ir->type->is_vector())
      return false;

   for (c = 0; c < ir->type->vector_elements; c++) {
      switch (ir->type->base_type) {
      case GLSL_TYPE_FLOAT:
	 if (ir->value.f[c] != 1.0)
	    return false;
	 break;
      case GLSL_TYPE_INT:
	 if (ir->value.i[c] != 1)
	    return false;
	 break;
      case GLSL_TYPE_UINT:
	 if (ir->value.u[c] != 1)
	    return false;
	 break;
      case GLSL_TYPE_BOOL:
	 if (ir->value.b[c] != true)
	    return false;
	 break;
      default:
	 assert(!"bad base type");
	 return false;
      }
   }

   return true;
}

ir_rvalue *
ir_algebraic_visitor::handle_expression(ir_rvalue *in_ir)
{
   ir_expression *ir = (ir_expression *)in_ir;
   ir_constant *op_const[2] = {NULL, NULL};
   ir_expression *op_expr[2] = {NULL, NULL};
   unsigned int i;

   if (!in_ir)
      return NULL;

   if (in_ir->ir_type != ir_type_expression)
      return in_ir;

   for (i = 0; i < ir->get_num_operands(); i++) {
      if (ir->operands[i]->type->is_matrix())
	 return in_ir;

      op_const[i] = ir->operands[i]->constant_expression_value();
      op_expr[i] = ir->operands[i]->as_expression();
   }

   switch (ir->operation) {
   case ir_unop_logic_not: {
      enum ir_expression_operation new_op = ir_unop_logic_not;

      if (op_expr[0] == NULL)
	 break;

      switch (op_expr[0]->operation) {
      case ir_binop_equal:   new_op = ir_binop_nequal;  break;
      case ir_binop_nequal:  new_op = ir_binop_equal;   break;

      default:
	 /* The default case handler is here to silence a warning from GCC.
	  */
	 break;
      }

      if (new_op != ir_unop_logic_not) {
	 this->progress = true;
	 return new(ir) ir_expression(new_op,
				      ir->type,
				      op_expr[0]->operands[0],
				      op_expr[0]->operands[1]);
      }

      break;
   }

   case ir_binop_add:
      if (is_vec_zero(op_const[0])) {
	 this->progress = true;
	 return ir->operands[1];
      }
      if (is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      }
      break;

   case ir_binop_sub:
      if (is_vec_zero(op_const[0])) {
	 this->progress = true;
	 return new(ir) ir_expression(ir_unop_neg,
				      ir->type,
				      ir->operands[1],
				      NULL);
      }
      if (is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      }
      break;

   case ir_binop_mul:
      if (is_vec_one(op_const[0])) {
	 this->progress = true;
	 return ir->operands[1];
      }
      if (is_vec_one(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      }

      if (is_vec_zero(op_const[0]) || is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir_constant::zero(ir, ir->type);
      }
      break;

   case ir_binop_div:
      if (is_vec_one(op_const[0]) && ir->type->base_type == GLSL_TYPE_FLOAT) {
	 this->progress = true;
	 return new(ir) ir_expression(ir_unop_rcp,
				      ir->type,
				      ir->operands[1],
				      NULL);
      }
      if (is_vec_one(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      }
      break;

   case ir_unop_rcp:
      if (op_expr[0] && op_expr[0]->operation == ir_unop_rcp) {
	 this->progress = true;
	 return op_expr[0]->operands[0];
      }

      /* FINISHME: We should do rcp(rsq(x)) -> sqrt(x) for some
       * backends, except that some backends will have done sqrt ->
       * rcp(rsq(x)) and we don't want to undo it for them.
       */

      /* As far as we know, all backends are OK with rsq. */
      if (op_expr[0] && op_expr[0]->operation == ir_unop_sqrt) {
	 this->progress = true;
	 return new(ir) ir_expression(ir_unop_rsq,
				      ir->type,
				      op_expr[0]->operands[0],
				      NULL);
      }

      break;

   default:
      break;
   }

   return in_ir;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_expression *ir)
{
   unsigned int operand;

   for (operand = 0; operand < ir->get_num_operands(); operand++) {
      ir->operands[operand] = handle_expression(ir->operands[operand]);
   }

   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_texture *ir)
{
   ir->coordinate = handle_expression(ir->coordinate);
   ir->projector = handle_expression(ir->projector);
   ir->shadow_comparitor = handle_expression(ir->shadow_comparitor);

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

   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_swizzle *ir)
{
   ir->val = handle_expression(ir->val);
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_dereference_array *ir)
{
   ir->array_index = handle_expression(ir->array_index);
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_assignment *ir)
{
   ir->rhs = handle_expression(ir->rhs);
   ir->condition = handle_expression(ir->condition);
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_call *ir)
{
   foreach_iter(exec_list_iterator, iter, *ir) {
      ir_rvalue *param = (ir_rvalue *)iter.get();
      ir_rvalue *new_param = handle_expression(param);

      if (new_param != param) {
	 param->replace_with(new_param);
      }
   }
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_return *ir)
{
   ir->value = handle_expression(ir->value);;
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_if *ir)
{
   ir->condition = handle_expression(ir->condition);
   return visit_continue;
}

bool
do_algebraic(exec_list *instructions)
{
   ir_algebraic_visitor v;

   visit_list_elements(&v, instructions);

   return v.progress;
}
<commit_msg>ir_algebraic: Support other comparisons in ir_unop_logic_not<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.
 */

/**
 * \file ir_algebraic.cpp
 *
 * Takes advantage of association, commutivity, and other algebraic
 * properties to simplify expressions.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_optimization.h"
#include "glsl_types.h"

/**
 * Visitor class for replacing expressions with ir_constant values.
 */

class ir_algebraic_visitor : public ir_hierarchical_visitor {
public:
   ir_algebraic_visitor()
   {
      this->progress = false;
   }

   virtual ~ir_algebraic_visitor()
   {
   }

   virtual ir_visitor_status visit_leave(ir_assignment *);
   virtual ir_visitor_status visit_leave(ir_call *);
   virtual ir_visitor_status visit_leave(ir_dereference_array *);
   virtual ir_visitor_status visit_leave(ir_expression *);
   virtual ir_visitor_status visit_leave(ir_if *);
   virtual ir_visitor_status visit_leave(ir_return *);
   virtual ir_visitor_status visit_leave(ir_swizzle *);
   virtual ir_visitor_status visit_leave(ir_texture *);

   ir_rvalue *handle_expression(ir_rvalue *in_ir);

   bool progress;
};

static bool
is_vec_zero(ir_constant *ir)
{
   int c;

   if (!ir)
      return false;
   if (!ir->type->is_scalar() &&
       !ir->type->is_vector())
      return false;

   for (c = 0; c < ir->type->vector_elements; c++) {
      switch (ir->type->base_type) {
      case GLSL_TYPE_FLOAT:
	 if (ir->value.f[c] != 0.0)
	    return false;
	 break;
      case GLSL_TYPE_INT:
	 if (ir->value.i[c] != 0)
	    return false;
	 break;
      case GLSL_TYPE_UINT:
	 if (ir->value.u[c] != 0)
	    return false;
	 break;
      case GLSL_TYPE_BOOL:
	 if (ir->value.b[c] != false)
	    return false;
	 break;
      default:
	 assert(!"bad base type");
	 return false;
      }
   }

   return true;
}

static bool
is_vec_one(ir_constant *ir)
{
   int c;

   if (!ir)
      return false;
   if (!ir->type->is_scalar() &&
       !ir->type->is_vector())
      return false;

   for (c = 0; c < ir->type->vector_elements; c++) {
      switch (ir->type->base_type) {
      case GLSL_TYPE_FLOAT:
	 if (ir->value.f[c] != 1.0)
	    return false;
	 break;
      case GLSL_TYPE_INT:
	 if (ir->value.i[c] != 1)
	    return false;
	 break;
      case GLSL_TYPE_UINT:
	 if (ir->value.u[c] != 1)
	    return false;
	 break;
      case GLSL_TYPE_BOOL:
	 if (ir->value.b[c] != true)
	    return false;
	 break;
      default:
	 assert(!"bad base type");
	 return false;
      }
   }

   return true;
}

ir_rvalue *
ir_algebraic_visitor::handle_expression(ir_rvalue *in_ir)
{
   ir_expression *ir = (ir_expression *)in_ir;
   ir_constant *op_const[2] = {NULL, NULL};
   ir_expression *op_expr[2] = {NULL, NULL};
   unsigned int i;

   if (!in_ir)
      return NULL;

   if (in_ir->ir_type != ir_type_expression)
      return in_ir;

   for (i = 0; i < ir->get_num_operands(); i++) {
      if (ir->operands[i]->type->is_matrix())
	 return in_ir;

      op_const[i] = ir->operands[i]->constant_expression_value();
      op_expr[i] = ir->operands[i]->as_expression();
   }

   switch (ir->operation) {
   case ir_unop_logic_not: {
      enum ir_expression_operation new_op = ir_unop_logic_not;

      if (op_expr[0] == NULL)
	 break;

      switch (op_expr[0]->operation) {
      case ir_binop_less:    new_op = ir_binop_gequal;  break;
      case ir_binop_greater: new_op = ir_binop_lequal;  break;
      case ir_binop_lequal:  new_op = ir_binop_greater; break;
      case ir_binop_gequal:  new_op = ir_binop_less;    break;
      case ir_binop_equal:   new_op = ir_binop_nequal;  break;
      case ir_binop_nequal:  new_op = ir_binop_equal;   break;

      default:
	 /* The default case handler is here to silence a warning from GCC.
	  */
	 break;
      }

      if (new_op != ir_unop_logic_not) {
	 this->progress = true;
	 return new(ir) ir_expression(new_op,
				      ir->type,
				      op_expr[0]->operands[0],
				      op_expr[0]->operands[1]);
      }

      break;
   }

   case ir_binop_add:
      if (is_vec_zero(op_const[0])) {
	 this->progress = true;
	 return ir->operands[1];
      }
      if (is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      }
      break;

   case ir_binop_sub:
      if (is_vec_zero(op_const[0])) {
	 this->progress = true;
	 return new(ir) ir_expression(ir_unop_neg,
				      ir->type,
				      ir->operands[1],
				      NULL);
      }
      if (is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      }
      break;

   case ir_binop_mul:
      if (is_vec_one(op_const[0])) {
	 this->progress = true;
	 return ir->operands[1];
      }
      if (is_vec_one(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      }

      if (is_vec_zero(op_const[0]) || is_vec_zero(op_const[1])) {
	 this->progress = true;
	 return ir_constant::zero(ir, ir->type);
      }
      break;

   case ir_binop_div:
      if (is_vec_one(op_const[0]) && ir->type->base_type == GLSL_TYPE_FLOAT) {
	 this->progress = true;
	 return new(ir) ir_expression(ir_unop_rcp,
				      ir->type,
				      ir->operands[1],
				      NULL);
      }
      if (is_vec_one(op_const[1])) {
	 this->progress = true;
	 return ir->operands[0];
      }
      break;

   case ir_unop_rcp:
      if (op_expr[0] && op_expr[0]->operation == ir_unop_rcp) {
	 this->progress = true;
	 return op_expr[0]->operands[0];
      }

      /* FINISHME: We should do rcp(rsq(x)) -> sqrt(x) for some
       * backends, except that some backends will have done sqrt ->
       * rcp(rsq(x)) and we don't want to undo it for them.
       */

      /* As far as we know, all backends are OK with rsq. */
      if (op_expr[0] && op_expr[0]->operation == ir_unop_sqrt) {
	 this->progress = true;
	 return new(ir) ir_expression(ir_unop_rsq,
				      ir->type,
				      op_expr[0]->operands[0],
				      NULL);
      }

      break;

   default:
      break;
   }

   return in_ir;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_expression *ir)
{
   unsigned int operand;

   for (operand = 0; operand < ir->get_num_operands(); operand++) {
      ir->operands[operand] = handle_expression(ir->operands[operand]);
   }

   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_texture *ir)
{
   ir->coordinate = handle_expression(ir->coordinate);
   ir->projector = handle_expression(ir->projector);
   ir->shadow_comparitor = handle_expression(ir->shadow_comparitor);

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

   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_swizzle *ir)
{
   ir->val = handle_expression(ir->val);
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_dereference_array *ir)
{
   ir->array_index = handle_expression(ir->array_index);
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_assignment *ir)
{
   ir->rhs = handle_expression(ir->rhs);
   ir->condition = handle_expression(ir->condition);
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_call *ir)
{
   foreach_iter(exec_list_iterator, iter, *ir) {
      ir_rvalue *param = (ir_rvalue *)iter.get();
      ir_rvalue *new_param = handle_expression(param);

      if (new_param != param) {
	 param->replace_with(new_param);
      }
   }
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_return *ir)
{
   ir->value = handle_expression(ir->value);;
   return visit_continue;
}

ir_visitor_status
ir_algebraic_visitor::visit_leave(ir_if *ir)
{
   ir->condition = handle_expression(ir->condition);
   return visit_continue;
}

bool
do_algebraic(exec_list *instructions)
{
   ir_algebraic_visitor v;

   visit_list_elements(&v, instructions);

   return v.progress;
}
<|endoftext|>


<commit_before><commit_msg>Adding missing file from previous commit.<commit_after><|endoftext|>


<commit_before>/*
 * shrenderer.cpp
 *
 * Created on: 03.07.2012
 * @author Ralph Schurade
 */
#include "shrenderer.h"
#include "shrendererthread.h"
#include "glfunctions.h"

#include "../../data/datasets/datasetsh.h"
#include "../../data/enums.h"
#include "../../data/models.h"
#include "../../data/vptr.h"
#include "../../algos/fmath.h"
#include "../../algos/qball.h"

#include "../../data/mesh/tesselation.h"
#include "../../data/mesh/trianglemesh2.h"

#include "../../thirdparty/newmat10/newmat.h"

#include <QGLShaderProgram>
#include <QDebug>

#include <limits>

SHRenderer::SHRenderer( std::vector<ColumnVector>* data ) :
    ObjectRenderer(),
    m_tris( 0 ),
    vboIds( new GLuint[ 4 ] ),
    m_data( data ),
    m_scaling( 1.0 ),
    m_orient( 0 ),
    m_offset( 0 ),
    m_lod( 0 ),
    m_minMaxScaling( false ),
    m_order( 4 ),
    m_oldLoD( -1 ),
    m_pickId( GLFunctions::getPickIndex() ),
    m_updateThread( 0 ),
    m_glyphsUpdated( false ),
    m_updateRunning( false )
{
}

SHRenderer::~SHRenderer()
{
    glDeleteBuffers(1, &( vboIds[ 0 ] ) );
    glDeleteBuffers(1, &( vboIds[ 1 ] ) );
    glDeleteBuffers(1, &( vboIds[ 2 ] ) );
    glDeleteBuffers(1, &( vboIds[ 3 ] ) );
}

void SHRenderer::init()
{
    initializeOpenGLFunctions();
    glGenBuffers( 4, vboIds );
}

void SHRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup& props )
{
    float alpha = 1.0; //props.get( Fn::Property::D_ALPHA ).toFloat();
    m_renderMode = renderMode;

    m_pMatrix = p_matrix;
    m_mvMatrix = mv_matrix;

    switch ( renderMode )
    {
        case 0:
            break;
        case 1:
        {
            if ( alpha < 1.0 ) // obviously not opaque
            {
                return;
            }
            break;
        }
        default:
        {
            if ( alpha == 1.0  ) // not transparent
            {
                return;
            }
            break;
        }
    }

    setRenderParams( props );

    if ( m_orient == 0 )
    {
        return;
    }

    QGLShaderProgram* program = GLFunctions::getShader( "mesh" );

    program->bind();

    GLFunctions::setupTextures();
    GLFunctions::setTextureUniforms( GLFunctions::getShader( "mesh" ), "maingl" );
    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
    program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() );

    QMatrix4x4 mat;
    program->setUniformValue( "userTransformMatrix", mat );

    program->setUniformValue( "u_colorMode", 2 );
    program->setUniformValue( "u_colormap", m_colormap );
    program->setUniformValue( "u_color", m_color.redF(), m_color.greenF(), m_color.blueF(), 1.0 );
    program->setUniformValue( "u_selectedMin", m_selectedMin );
    program->setUniformValue( "u_selectedMax", m_selectedMax );
    program->setUniformValue( "u_lowerThreshold", m_lowerThreshold );
    program->setUniformValue( "u_upperThreshold", m_upperThreshold );

    float nx = props.get( Fn::Property::D_NX ).toFloat();
    float ny = props.get( Fn::Property::D_NY ).toFloat();
    float nz = props.get( Fn::Property::D_NZ ).toFloat();
    float sx = props.get( Fn::Property::G_SAGITTAL ).toFloat();
    float sy = props.get( Fn::Property::G_CORONAL ).toFloat();
    float sz = props.get( Fn::Property::G_AXIAL ).toFloat();
    float dx = props.get( Fn::Property::D_DX ).toFloat();
    float dy = props.get( Fn::Property::D_DY ).toFloat();
    float dz = props.get( Fn::Property::D_DZ ).toFloat();

    program->setUniformValue( "u_x", sx * dx + dx / 2.0f );
    program->setUniformValue( "u_y", sy * dy + dy / 2.0f );
    program->setUniformValue( "u_z", sz * dz + dz / 2.0f );
    program->setUniformValue( "u_cutLowerX", false );
    program->setUniformValue( "u_cutLowerY", false );
    program->setUniformValue( "u_cutLowerZ", false );
    program->setUniformValue( "u_cutHigherX", false );
    program->setUniformValue( "u_cutHigherY", false );
    program->setUniformValue( "u_cutHigherZ", false );

    program->setUniformValue( "u_adjustX",   0.0f );
    program->setUniformValue( "u_adjustY", 0.0f );
    program->setUniformValue( "u_adjustZ", 0.0f );

    program->setUniformValue( "u_alpha", alpha );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );

    program->setUniformValue( "u_lighting", props.get( Fn::Property::D_LIGHT_SWITCH ).toBool() );
    program->setUniformValue( "u_lightAmbient", props.get( Fn::Property::D_LIGHT_AMBIENT ).toFloat() );
    program->setUniformValue( "u_lightDiffuse", props.get( Fn::Property::D_LIGHT_DIFFUSE ).toFloat() );
    program->setUniformValue( "u_materialAmbient", props.get( Fn::Property::D_MATERIAL_AMBIENT ).toFloat() );
    program->setUniformValue( "u_materialDiffuse", props.get( Fn::Property::D_MATERIAL_DIFFUSE ).toFloat() );
    program->setUniformValue( "u_materialSpecular", props.get( Fn::Property::D_MATERIAL_SPECULAR ).toFloat() );
    program->setUniformValue( "u_materialShininess", props.get( Fn::Property::D_MATERIAL_SHININESS ).toFloat() );

    float pAlpha =  1.0;
    float blue = (float) ( ( m_pickId ) & 0xFF ) / 255.f;
    float green = (float) ( ( m_pickId >> 8 ) & 0xFF ) / 255.f;
    float red = (float) ( ( m_pickId >> 16 ) & 0xFF ) / 255.f;
    program->setUniformValue( "u_pickColor", red, green , blue, pAlpha );

    program->setUniformValue( "u_dims", nx * dx, ny * dy, nz * dz );

    if ( !m_updateRunning )
    {
        initGeometry( props );
    }

    if ( m_glyphsUpdated )
    {
        updateGlyphs();
    }

    if ( m_tris == 0 )
    {
        return;
    }

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    setShaderVars( props );

    glEnable(GL_CULL_FACE);
    glCullFace( GL_BACK );
    glFrontFace( GL_CW );

    glDrawElements( GL_TRIANGLES, m_tris, GL_UNSIGNED_INT, 0 );

    glDisable(GL_CULL_FACE);

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}

void SHRenderer::setShaderVars( PropertyGroup& props )
{
    QGLShaderProgram* program = GLFunctions::getShader( "mesh" );

    program->bind();

    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (const void *) offset );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] );
    int normalLocation = program->attributeLocation( "a_normal" );
    program->enableAttributeArray( normalLocation );
    glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (const void *) offset );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] );
    int colorLocation = program->attributeLocation( "a_color" );
    program->enableAttributeArray( colorLocation );
    glVertexAttribPointer( colorLocation, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}

void SHRenderer::setRenderParams( PropertyGroup& props )
{
    m_scaling = props.get( Fn::Property::D_SCALING ).toFloat();
    m_offset = props.get( Fn::Property::D_OFFSET ).toInt();
    m_lod = props.get( Fn::Property::D_LOD ).toInt();
    m_minMaxScaling = props.get( Fn::Property::D_MINMAX_SCALING ).toBool();
    m_hideNegativeLobes = props.get( Fn::Property::D_HIDE_NEGATIVE_LOBES ).toBool();
    m_order = props.get( Fn::Property::D_ORDER ).toInt();

    m_orient = 0;
    if ( props.get( Fn::Property::D_RENDER_AXIAL ).toBool() )
    {
        m_orient = 1;
    }
    if ( props.get( Fn::Property::D_RENDER_CORONAL ).toBool() )
    {
        m_orient += 2;
    }
    if ( props.get( Fn::Property::D_RENDER_SAGITTAL ).toBool() )
    {
        m_orient += 4;
    }

    m_colorMode = props.get( Fn::Property::D_COLORMODE ).toInt();
    m_colormap = props.get( Fn::Property::D_COLORMAP ).toInt();
    m_selectedMin = props.get( Fn::Property::D_SELECTED_MIN ).toFloat();
    m_selectedMax = props.get( Fn::Property::D_SELECTED_MAX ).toFloat();
    m_lowerThreshold = props.get( Fn::Property::D_LOWER_THRESHOLD ).toFloat();
    m_upperThreshold = props.get( Fn::Property::D_UPPER_THRESHOLD ).toFloat();
    m_color = props.get( Fn::Property::D_COLOR ).value<QColor>();
}

TriangleMesh2* SHRenderer::getMesh()
{
    //return m_mesh;
}

void SHRenderer::initGeometry( PropertyGroup& props )
{
    float x = Models::getGlobal( Fn::Property::G_SAGITTAL ).toFloat();
    float y = Models::getGlobal( Fn::Property::G_CORONAL ).toFloat();
    float z = Models::getGlobal( Fn::Property::G_AXIAL ).toFloat();

    float zoom = Models::getGlobal( Fn::Property::G_ZOOM ).toFloat();
    float moveX = Models::getGlobal( Fn::Property::G_MOVEX ).toFloat();
    float moveY = Models::getGlobal( Fn::Property::G_MOVEY ).toFloat();

    QString s = createSettingsString( { x, y, z, m_orient, zoom, m_minMaxScaling, m_scaling, m_hideNegativeLobes, moveX, moveY, m_lod, m_offset } );
    if ( ( s == m_previousSettings ) || ( m_orient == 0 ) )
    {
        return;
    }
    m_previousSettings = s;

    m_updateRunning = true;
    m_glyphsUpdated = false;

    if ( m_updateThread )
    {
        delete m_updateThread;
    }
    m_updateThread = new SHRendererThread( m_data, m_pMatrix, m_mvMatrix, props );
    connect( m_updateThread, SIGNAL( finished( bool ) ), this, SLOT( updateThreadFinished( bool ) ) );
    m_updateThread->start();
}

void SHRenderer::updateThreadFinished( bool success )
{
    if ( success )
    {
        m_glyphsUpdated = true;
    }
    m_updateRunning = false;
    Models::g()->submit();
}

void SHRenderer::updateGlyphs()
{
    glDeleteBuffers( 4, vboIds );
    glGenBuffers( 4, vboIds );

    m_tris = m_updateThread->getIndices()->size();

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, m_tris * sizeof(GLuint), m_updateThread->getIndices()->data(), GL_STATIC_DRAW );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    glBufferData( GL_ARRAY_BUFFER, m_updateThread->getVerts()->size() * sizeof(GLfloat), m_updateThread->getVerts()->data(), GL_STATIC_DRAW );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] );
    glBufferData( GL_ARRAY_BUFFER, m_updateThread->getColors()->size() * sizeof(GLfloat), m_updateThread->getColors()->data(), GL_DYNAMIC_DRAW );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] );
    glBufferData( GL_ARRAY_BUFFER, m_updateThread->getNormals()->size() * sizeof(GLfloat), m_updateThread->getNormals()->data(), GL_STATIC_DRAW );

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    delete m_updateThread;
    m_updateThread = 0;
    m_glyphsUpdated = false;
}
<commit_msg>fixed crash with csd renderer when displaying a slice with no csd glyphs visible<commit_after>/*
 * shrenderer.cpp
 *
 * Created on: 03.07.2012
 * @author Ralph Schurade
 */
#include "shrenderer.h"
#include "shrendererthread.h"
#include "glfunctions.h"

#include "../../data/datasets/datasetsh.h"
#include "../../data/enums.h"
#include "../../data/models.h"
#include "../../data/vptr.h"
#include "../../algos/fmath.h"
#include "../../algos/qball.h"

#include "../../data/mesh/tesselation.h"
#include "../../data/mesh/trianglemesh2.h"

#include "../../thirdparty/newmat10/newmat.h"

#include <QGLShaderProgram>
#include <QDebug>

#include <limits>

SHRenderer::SHRenderer( std::vector<ColumnVector>* data ) :
    ObjectRenderer(),
    m_tris( 0 ),
    vboIds( new GLuint[ 4 ] ),
    m_data( data ),
    m_scaling( 1.0 ),
    m_orient( 0 ),
    m_offset( 0 ),
    m_lod( 0 ),
    m_minMaxScaling( false ),
    m_order( 4 ),
    m_oldLoD( -1 ),
    m_pickId( GLFunctions::getPickIndex() ),
    m_updateThread( 0 ),
    m_glyphsUpdated( false ),
    m_updateRunning( false )
{
}

SHRenderer::~SHRenderer()
{
    glDeleteBuffers(1, &( vboIds[ 0 ] ) );
    glDeleteBuffers(1, &( vboIds[ 1 ] ) );
    glDeleteBuffers(1, &( vboIds[ 2 ] ) );
    glDeleteBuffers(1, &( vboIds[ 3 ] ) );
}

void SHRenderer::init()
{
    initializeOpenGLFunctions();
    glGenBuffers( 4, vboIds );
}

void SHRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup& props )
{
    float alpha = 1.0; //props.get( Fn::Property::D_ALPHA ).toFloat();
    m_renderMode = renderMode;

    m_pMatrix = p_matrix;
    m_mvMatrix = mv_matrix;

    switch ( renderMode )
    {
        case 0:
            break;
        case 1:
        {
            if ( alpha < 1.0 ) // obviously not opaque
            {
                return;
            }
            break;
        }
        default:
        {
            if ( alpha == 1.0  ) // not transparent
            {
                return;
            }
            break;
        }
    }

    setRenderParams( props );

    if ( m_orient == 0 )
    {
        return;
    }

    QGLShaderProgram* program = GLFunctions::getShader( "mesh" );

    program->bind();

    GLFunctions::setupTextures();
    GLFunctions::setTextureUniforms( GLFunctions::getShader( "mesh" ), "maingl" );
    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
    program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() );

    QMatrix4x4 mat;
    program->setUniformValue( "userTransformMatrix", mat );

    program->setUniformValue( "u_colorMode", 2 );
    program->setUniformValue( "u_colormap", m_colormap );
    program->setUniformValue( "u_color", m_color.redF(), m_color.greenF(), m_color.blueF(), 1.0 );
    program->setUniformValue( "u_selectedMin", m_selectedMin );
    program->setUniformValue( "u_selectedMax", m_selectedMax );
    program->setUniformValue( "u_lowerThreshold", m_lowerThreshold );
    program->setUniformValue( "u_upperThreshold", m_upperThreshold );

    float nx = props.get( Fn::Property::D_NX ).toFloat();
    float ny = props.get( Fn::Property::D_NY ).toFloat();
    float nz = props.get( Fn::Property::D_NZ ).toFloat();
    float sx = props.get( Fn::Property::G_SAGITTAL ).toFloat();
    float sy = props.get( Fn::Property::G_CORONAL ).toFloat();
    float sz = props.get( Fn::Property::G_AXIAL ).toFloat();
    float dx = props.get( Fn::Property::D_DX ).toFloat();
    float dy = props.get( Fn::Property::D_DY ).toFloat();
    float dz = props.get( Fn::Property::D_DZ ).toFloat();

    program->setUniformValue( "u_x", sx * dx + dx / 2.0f );
    program->setUniformValue( "u_y", sy * dy + dy / 2.0f );
    program->setUniformValue( "u_z", sz * dz + dz / 2.0f );
    program->setUniformValue( "u_cutLowerX", false );
    program->setUniformValue( "u_cutLowerY", false );
    program->setUniformValue( "u_cutLowerZ", false );
    program->setUniformValue( "u_cutHigherX", false );
    program->setUniformValue( "u_cutHigherY", false );
    program->setUniformValue( "u_cutHigherZ", false );

    program->setUniformValue( "u_adjustX",   0.0f );
    program->setUniformValue( "u_adjustY", 0.0f );
    program->setUniformValue( "u_adjustZ", 0.0f );

    program->setUniformValue( "u_alpha", alpha );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );

    program->setUniformValue( "u_lighting", props.get( Fn::Property::D_LIGHT_SWITCH ).toBool() );
    program->setUniformValue( "u_lightAmbient", props.get( Fn::Property::D_LIGHT_AMBIENT ).toFloat() );
    program->setUniformValue( "u_lightDiffuse", props.get( Fn::Property::D_LIGHT_DIFFUSE ).toFloat() );
    program->setUniformValue( "u_materialAmbient", props.get( Fn::Property::D_MATERIAL_AMBIENT ).toFloat() );
    program->setUniformValue( "u_materialDiffuse", props.get( Fn::Property::D_MATERIAL_DIFFUSE ).toFloat() );
    program->setUniformValue( "u_materialSpecular", props.get( Fn::Property::D_MATERIAL_SPECULAR ).toFloat() );
    program->setUniformValue( "u_materialShininess", props.get( Fn::Property::D_MATERIAL_SHININESS ).toFloat() );

    float pAlpha =  1.0;
    float blue = (float) ( ( m_pickId ) & 0xFF ) / 255.f;
    float green = (float) ( ( m_pickId >> 8 ) & 0xFF ) / 255.f;
    float red = (float) ( ( m_pickId >> 16 ) & 0xFF ) / 255.f;
    program->setUniformValue( "u_pickColor", red, green , blue, pAlpha );

    program->setUniformValue( "u_dims", nx * dx, ny * dy, nz * dz );

    if ( !m_updateRunning )
    {
        initGeometry( props );
    }

    if ( m_glyphsUpdated )
    {
        updateGlyphs();
    }

    if ( m_tris == 0 )
    {
        return;
    }

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    setShaderVars( props );

    glEnable(GL_CULL_FACE);
    glCullFace( GL_BACK );
    glFrontFace( GL_CW );

    glDrawElements( GL_TRIANGLES, m_tris, GL_UNSIGNED_INT, 0 );

    glDisable(GL_CULL_FACE);

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}

void SHRenderer::setShaderVars( PropertyGroup& props )
{
    QGLShaderProgram* program = GLFunctions::getShader( "mesh" );

    program->bind();

    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (const void *) offset );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] );
    int normalLocation = program->attributeLocation( "a_normal" );
    program->enableAttributeArray( normalLocation );
    glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (const void *) offset );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] );
    int colorLocation = program->attributeLocation( "a_color" );
    program->enableAttributeArray( colorLocation );
    glVertexAttribPointer( colorLocation, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}

void SHRenderer::setRenderParams( PropertyGroup& props )
{
    m_scaling = props.get( Fn::Property::D_SCALING ).toFloat();
    m_offset = props.get( Fn::Property::D_OFFSET ).toInt();
    m_lod = props.get( Fn::Property::D_LOD ).toInt();
    m_minMaxScaling = props.get( Fn::Property::D_MINMAX_SCALING ).toBool();
    m_hideNegativeLobes = props.get( Fn::Property::D_HIDE_NEGATIVE_LOBES ).toBool();
    m_order = props.get( Fn::Property::D_ORDER ).toInt();

    m_orient = 0;
    if ( props.get( Fn::Property::D_RENDER_AXIAL ).toBool() )
    {
        m_orient = 1;
    }
    if ( props.get( Fn::Property::D_RENDER_CORONAL ).toBool() )
    {
        m_orient += 2;
    }
    if ( props.get( Fn::Property::D_RENDER_SAGITTAL ).toBool() )
    {
        m_orient += 4;
    }

    m_colorMode = props.get( Fn::Property::D_COLORMODE ).toInt();
    m_colormap = props.get( Fn::Property::D_COLORMAP ).toInt();
    m_selectedMin = props.get( Fn::Property::D_SELECTED_MIN ).toFloat();
    m_selectedMax = props.get( Fn::Property::D_SELECTED_MAX ).toFloat();
    m_lowerThreshold = props.get( Fn::Property::D_LOWER_THRESHOLD ).toFloat();
    m_upperThreshold = props.get( Fn::Property::D_UPPER_THRESHOLD ).toFloat();
    m_color = props.get( Fn::Property::D_COLOR ).value<QColor>();
}

TriangleMesh2* SHRenderer::getMesh()
{
    //return m_mesh;
}

void SHRenderer::initGeometry( PropertyGroup& props )
{
    float x = Models::getGlobal( Fn::Property::G_SAGITTAL ).toFloat();
    float y = Models::getGlobal( Fn::Property::G_CORONAL ).toFloat();
    float z = Models::getGlobal( Fn::Property::G_AXIAL ).toFloat();

    float zoom = Models::getGlobal( Fn::Property::G_ZOOM ).toFloat();
    float moveX = Models::getGlobal( Fn::Property::G_MOVEX ).toFloat();
    float moveY = Models::getGlobal( Fn::Property::G_MOVEY ).toFloat();

    QString s = createSettingsString( { x, y, z, m_orient, zoom, m_minMaxScaling, m_scaling, m_hideNegativeLobes, moveX, moveY, m_lod, m_offset } );
    if ( ( s == m_previousSettings ) || ( m_orient == 0 ) )
    {
        return;
    }
    m_previousSettings = s;

    m_updateRunning = true;
    m_glyphsUpdated = false;

    if ( m_updateThread )
    {
        delete m_updateThread;
    }
    m_updateThread = new SHRendererThread( m_data, m_pMatrix, m_mvMatrix, props );
    connect( m_updateThread, SIGNAL( finished( bool ) ), this, SLOT( updateThreadFinished( bool ) ) );
    m_updateThread->start();
}

void SHRenderer::updateThreadFinished( bool success )
{
    if ( success )
    {
        m_glyphsUpdated = true;
    }
    m_updateRunning = false;
    Models::g()->submit();
}

void SHRenderer::updateGlyphs()
{
    m_tris = m_updateThread->getIndices()->size();

    if ( m_tris == 0 )
    {
        return;
    }

    glDeleteBuffers( 4, vboIds );
    glGenBuffers( 4, vboIds );

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, m_tris * sizeof(GLuint), m_updateThread->getIndices()->data(), GL_STATIC_DRAW );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    glBufferData( GL_ARRAY_BUFFER, m_updateThread->getVerts()->size() * sizeof(GLfloat), m_updateThread->getVerts()->data(), GL_STATIC_DRAW );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] );
    glBufferData( GL_ARRAY_BUFFER, m_updateThread->getColors()->size() * sizeof(GLfloat), m_updateThread->getColors()->data(), GL_DYNAMIC_DRAW );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] );
    glBufferData( GL_ARRAY_BUFFER, m_updateThread->getNormals()->size() * sizeof(GLfloat), m_updateThread->getNormals()->data(), GL_STATIC_DRAW );

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    delete m_updateThread;
    m_updateThread = 0;
    m_glyphsUpdated = false;
}
<|endoftext|>


<commit_before><commit_msg>Fixed bug in edge-mapping parallelisation<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <stingraykit/Random.h>

#include <ctime>

namespace stingray
{

	Random::Random()
		: _seed(std::time(0) & 0x7fffffffU)
	{ }

	Random::Random(u32 seed)
		: _seed(seed & 0x7fffffffU)
	{ }

	u32 Random::Next(u32 maxValue)
	{
		static const u32 maxRand = 0x8000u;
		u32 next = Next();
		if (maxValue <= maxRand)
			next >>= 16;
		return next % maxValue;
	}

	u32 Random::Next()
	{
		_seed = (_seed * 1103515245U + 12345U) & 0x7fffffffU;
		return _seed;
	}

}
<commit_msg>replaced LCG with mathematically correct parameters from "Numeric Recipes", both low/high bits are passing tests now<commit_after>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <stingraykit/Random.h>

#include <ctime>

namespace stingray
{

	Random::Random()
		: _seed(std::time(0))
	{ }

	Random::Random(u32 seed)
		: _seed(seed)
	{ }

	u32 Random::Next(u32 maxValue)
	{ return Next() % maxValue; }

	u32 Random::Next()
	{
		_seed = _seed * 1664525U + 1013904223U;
		return _seed;
	}

}
<|endoftext|>


<commit_before><commit_msg>Added stubs for bmp width and height<commit_after><|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <map>
#include <utility>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <vector>
#include <string>
#include <iostream>

#include "functions.h"

int main(int argc, char** argv) {
  std::string prompt;
  getPrompt(prompt);

  bool quit = false;

  // print welcome message and prompt
  printf("Welcome to rshell!\n");

  while (!quit) {
    // holds a single command and its arguments
    Command_t cmd;
    // holds multiple commands
    std::vector<Command_t> cmds;
    // hold a raw line of input
    std::string line;

    // print prompt and get a line of text (done in condition)
    printf("%s", prompt.c_str());
    preProcessLine(line);

    int mode = GETWORD;
    unsigned begin = 0;

    // prepare cmd
    cmd.connector = NONE;

    // syntax error flag
    bool se = false;

    // starts with a connector? I don't think so
    if (line.size() > 0 && isConn(line[0]) && line[0] != ';') {
      se = true;
    } else if (line.size() > 0 && (isRedir(line[0]) || isdigit(line[0]))) {
      mode = GETREDIR;
    }

    // handle the input
    for(unsigned i = 0; i < line.size() && !se; ++i) {
      bool con   = isConn(line[i]);
      // bool dig   = isdigit(line[i]);
      bool redir = isRedir(line[i]);
      bool space = isspace(line[i]);

      // if we're getting a word and there's a whitespace or connector here
      if (mode == GETWORD && (space || con || redir)) {
        // only happens for blank lines:
        if (i == 0 && con) break;
        if (redir) {
          mode = GETREDIR;
          continue;
        }
        // chunk the last term and throw it into the vector
        addArg(cmd, line, begin, i);

        if (space) {
          mode = TRIMSPACE;
        } else if (con) {
          handleCon(cmds, cmd, line, mode, begin, i, se);
        }
      } else if (mode == TRIMSPACE && !space) {
        if (con && cmd.args.empty() && line[i] != ';') {
          se = true;
        } else if (con) {
          handleCon(cmds, cmd, line, mode, begin, i, se);
        } else if (redir) {
          begin = i;
          mode = GETREDIR;
        } else {
          begin = i;
          mode = GETWORD;
        }
      } else if (mode == HANDLESEMI && line[i] != ';') {
        if (isConn(line[i])) {
          se = true;
        } else if (isspace(line[i])) {
          mode = TRIMSPACE;
        } else { // it's a word
          begin = i;
          mode = GETWORD;
        }
      } else if (mode == GETREDIR && line[i] == '"') {
        mode = GETSTRING;
      } else if (mode == GETREDIR && space) {
        handleRedir(cmds, cmd, line, mode, begin, i, se);
        mode = TRIMSPACE;
      } else if (mode == GETSTRING && line[i] == '"') {
        mode = ENDQUOTE;
      } else if (mode == ENDQUOTE) {
        if (space) {
          handleRedir(cmds, cmd, line, mode, begin, i, se);
          mode = TRIMSPACE;
        } else {
          se = true;
          continue;
        }
      }
    }

    // if the last command has a continuation connector, syntax error
    if (cmds.size() > 0 && (cmds[cmds.size()-1].connector == AND
                        ||  cmds[cmds.size()-1].connector == OR
                        ||  cmds[cmds.size()-1].connector == PIPE)) {
      se = true;
    }

    if (mode == GETSTRING) se = true;

    // if there was a syntax error
    if (se) {
      printf("Syntax error\n");
      continue;
    }

    /* code for debugging
    for(unsigned i = 0; i < cmds.size(); ++i) {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j) {
        printf("cmd %d arg %d: \"%s\"\n", i, j, cmds[i].args[j]);
      }
      if (cmds[i].connector == NONE) printf("connector: NONE\n");
      else if (cmds[i].connector == AND) printf("connector: AND\n");
      else if (cmds[i].connector == OR) printf("connector: OR\n");
      else if (cmds[i].connector == SEMI) printf("connector: SEMI\n");
      else if (cmds[i].connector == PIPE) printf("connector: PIPE\n");
      printf("file descriptor modifications:\n");
      for(unsigned j = 0; j < cmds[i].fdChanges.size(); ++j) {
        if (cmds[i].fdChanges[j].type == INPUT) {
          printf("change fd %d to ",
          (cmds[i].fdChanges[j].orig == DEFAULT) ? 0 :
           cmds[i].fdChanges[j].orig);

          if (cmds[i].fdChanges[j].moveTo == UNDEFINED)
            printf("UNDEFINED\n");
          else if (cmds[i].fdChanges[j].moveTo == FROMSTR)
            printf("FROMSTR (\"%s\")\n", cmds[i].fdChanges[j].s.c_str());
          else
            printf("Some other fd (%d)\n", cmds[i].fdChanges[j].moveTo);
        }

        if (cmds[i].fdChanges[j].type == OUTPUT) {
          printf("change fd %d to ",
          (cmds[i].fdChanges[j].orig == DEFAULT) ? 1 :
           cmds[i].fdChanges[j].orig);

          if (cmds[i].fdChanges[j].moveTo == UNDEFINED)
            printf("UNDEFINED\n");
          else
            printf("Some other fd (%d)\n", cmds[i].fdChanges[j].moveTo);
        }
      }
    }
    // */

    // now to execute all the commands
    // pipe
    int pa[2];
    std::vector<char*> paths;
    // getPaths
    fillPaths(paths);

    // prepare argv so I can delete them later
    std::vector<char**> argvs;
    for(unsigned i = 0; i < cmds.size(); ++i) {
      argvs.push_back(new char*[cmds[i].args.size()+1]);
    }

    for(unsigned cmdi = 0; cmdi < cmds.size(); ++cmdi) {
      size_t argsSize = cmds[cmdi].args.size();
      int exitStatus = 0;

      char* arg = cmds[cmdi].args[0];
      if (strcmp(arg, "exit") == 0) {
        quit = true;
        break;
      }
      char** subargv = argvs[cmdi];
      for(unsigned j = 0; j < argsSize; ++j) {
        subargv[j] = cmds[cmdi].args[j];
      }
      subargv[argsSize] = 0;

      if (cmds[cmdi].connector == PIPE) {
        // 1. make pipe
        if (-1 == pipe(pa)) {
          perror("pipe");
          exit(1);
        }
        // 2. this program gets output and next program gets input
        // this program:
        fdChange_t outfdC(1, pa[1], OUTPUT);
        fdChange_t infdC(0, pa[0], INPUT);

        cmds[cmdi].fdChanges.push_back(outfdC);
        cmds[cmdi].closefd.push_back(pa[1]);
        // next program:
        cmds[cmdi+1].fdChanges.push_back(infdC);
        cmds[cmdi+1].closefd.push_back(pa[0]);

      }

      std::map<int, fdData_t> fds;
      for(unsigned j = 0; j < cmds[cmdi].fdChanges.size(); ++j) {
        int o           = cmds[cmdi].fdChanges[j].orig;
        int mt          = cmds[cmdi].fdChanges[j].moveTo;
        int t           = cmds[cmdi].fdChanges[j].type;
        std::string str = cmds[cmdi].fdChanges[j].s;

        if (t == INPUT) {
          if (mt == FILEIN) {
            fds.insert(std::pair<int, fdData_t>(o, fdData_t(-1, DT_FIN, str)));
            // printf("Adding %d pointing to the file %s in input mode\n", o, str.c_str());
          } else if (mt == FROMSTR) {
            fds.insert(std::pair<int, fdData_t>(o, fdData_t(-1, DT_STR, str)));
            // printf("Adding %d pointing to the string %s in input mode\n", o, str.c_str());
          } else {
            fds.insert(std::pair<int, fdData_t>(o, fdData_t(mt, DT_FDIN, str)));
            // printf("Adding %d pointing to the fd %d in input mode\n", mt, o);
          }
        } else if (t == OUTPUT) {
          if (mt == FILEOUT) {
            fds.insert(std::pair<int, fdData_t>(-1, fdData_t(o, DT_FOW, str)));
            // printf("Adding %d pointing to the file %s in output write mode\n", o, str.c_str());
          } else if (mt == FILEAPP) {
            // if (fds
            fds.insert(std::pair<int, fdData_t>(-1, fdData_t(o, DT_FOA, str)));
            // printf("Adding %d pointing to the file %s in output append mode\n", o, str.c_str());
          } else {
            fds.insert(std::pair<int, fdData_t>(mt, fdData_t(o, DT_FDO, str)));
            // printf("Adding %d pointing to the fd %d in output mode\n", o, mt);
          }
        }
      }
      debugMap(fds);

      // arg and argv are now prepared
      pid_t pid = fork();
      if (-1 == pid) {
        perror("fork");
        exit(1); // fatal error
      } else if (0 == pid) { // child process
        deltaFD(fds);
        for(unsigned i = 0; i < paths.size(); ++i) {
          char* executable = new char[strlen(paths[i]) + strlen(arg) + 2];
          strcpy(executable, paths[i]);
          strcat(executable, "/");
          strcat(executable, arg);
          struct stat statRes;
          if (-1 != stat(executable, &statRes)) {
            if (-1 == execv(executable, subargv)) {
              // if there's a return value (-1), there was a problem
              debug("executing");
              perror(executable);
              delete[] subargv;
              delete[] executable;
              exit(1);
            }
          }
          errno = 0;
          delete[] executable;
        }
        fprintf(stderr, "%s: command not found\n", arg);
        delete[] subargv;
        exit(1);
      } else { // parent process
        // close current fd's
        /*
        for(unsigned j = 0; j < cmds[cmdi].closefd.size(); ++j) {
          if (-1 == close(cmds[cmdi].closefd[j])) {
            perror("closing in parent");
            exit(1);
          }
        } */
        // only wait for non-pipes
        if (cmds[cmdi].connector != PIPE && -1 == waitpid(pid, &exitStatus, 0)) {
          perror("waitpid");
          exit(1);
        }
      }
      if (!exitStatus) { // all is good (0)
        while (cmdi < cmds.size() && cmds[cmdi].connector == OR) {
          ++cmdi;
        }
      } else { // last command failed
        while (cmdi < cmds.size() && cmds[cmdi].connector == AND) {
          ++cmdi;
        }
      }
    }

    // deallocate allocated memory
    for(unsigned i = 0; i < cmds.size(); ++i) {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j) {
        delete[] cmds[i].args[j];
      }
    }
    for(unsigned i = 0; i < paths.size(); ++i) {
      delete[] paths[i];
    }
    for(unsigned i = 0; i < argvs.size(); ++i) {
      delete[] argvs[i];
    }
  }
  printf("Goodbye!\n");
  return 0;
}

<commit_msg>implemented cd and changed prompt to show current path<commit_after>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <map>
#include <utility>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <vector>
#include <string>
#include <iostream>
#include <limits.h>

#include "functions.h"

int main(int argc, char** argv) {
  std::string prompt;
  getPrompt(prompt);

  bool quit = false;

  // print welcome message and prompt
  printf("Welcome to rshell!\n");

  while (!quit) {
    // holds a single command and its arguments
    Command_t cmd;
    // holds multiple commands
    std::vector<Command_t> cmds;
    // hold a raw line of input
    std::string line;

    char cwd[4 * PATH_MAX];
    if (NULL == getcwd(cwd + 1, 4 * PATH_MAX)) {
      perror("getcwd");
    }
    cwd[0] = '[';

    // print prompt and get a line of text (done in condition)
    printf("%s", (cwd + ("] " + prompt)).c_str());
    preProcessLine(line);

    int mode = GETWORD;
    unsigned begin = 0;

    // prepare cmd
    cmd.connector = NONE;

    // syntax error flag
    bool se = false;

    // starts with a connector? I don't think so
    if (line.size() > 0 && isConn(line[0]) && line[0] != ';') {
      se = true;
    } else if (line.size() > 0 && (isRedir(line[0]) || isdigit(line[0]))) {
      mode = GETREDIR;
    }

    // handle the input
    for(unsigned i = 0; i < line.size() && !se; ++i) {
      bool con   = isConn(line[i]);
      // bool dig   = isdigit(line[i]);
      bool redir = isRedir(line[i]);
      bool space = isspace(line[i]);

      // if we're getting a word and there's a whitespace or connector here
      if (mode == GETWORD && (space || con || redir)) {
        // only happens for blank lines:
        if (i == 0 && con) break;
        if (redir) {
          mode = GETREDIR;
          continue;
        }
        // chunk the last term and throw it into the vector
        addArg(cmd, line, begin, i);

        if (space) {
          mode = TRIMSPACE;
        } else if (con) {
          handleCon(cmds, cmd, line, mode, begin, i, se);
        }
      } else if (mode == TRIMSPACE && !space) {
        if (con && cmd.args.empty() && line[i] != ';') {
          se = true;
        } else if (con) {
          handleCon(cmds, cmd, line, mode, begin, i, se);
        } else if (redir) {
          begin = i;
          mode = GETREDIR;
        } else {
          begin = i;
          mode = GETWORD;
        }
      } else if (mode == HANDLESEMI && line[i] != ';') {
        if (isConn(line[i])) {
          se = true;
        } else if (isspace(line[i])) {
          mode = TRIMSPACE;
        } else { // it's a word
          begin = i;
          mode = GETWORD;
        }
      } else if (mode == GETREDIR && line[i] == '"') {
        mode = GETSTRING;
      } else if (mode == GETREDIR && space) {
        handleRedir(cmds, cmd, line, mode, begin, i, se);
        mode = TRIMSPACE;
      } else if (mode == GETSTRING && line[i] == '"') {
        mode = ENDQUOTE;
      } else if (mode == ENDQUOTE) {
        if (space) {
          handleRedir(cmds, cmd, line, mode, begin, i, se);
          mode = TRIMSPACE;
        } else {
          se = true;
          continue;
        }
      }
    }

    // if the last command has a continuation connector, syntax error
    if (cmds.size() > 0 && (cmds[cmds.size()-1].connector == AND
                        ||  cmds[cmds.size()-1].connector == OR
                        ||  cmds[cmds.size()-1].connector == PIPE)) {
      se = true;
    }

    if (mode == GETSTRING) se = true;

    // if there was a syntax error
    if (se) {
      printf("Syntax error\n");
      continue;
    }

    /* code for debugging
    for(unsigned i = 0; i < cmds.size(); ++i) {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j) {
        printf("cmd %d arg %d: \"%s\"\n", i, j, cmds[i].args[j]);
      }
      if (cmds[i].connector == NONE) printf("connector: NONE\n");
      else if (cmds[i].connector == AND) printf("connector: AND\n");
      else if (cmds[i].connector == OR) printf("connector: OR\n");
      else if (cmds[i].connector == SEMI) printf("connector: SEMI\n");
      else if (cmds[i].connector == PIPE) printf("connector: PIPE\n");
      printf("file descriptor modifications:\n");
      for(unsigned j = 0; j < cmds[i].fdChanges.size(); ++j) {
        if (cmds[i].fdChanges[j].type == INPUT) {
          printf("change fd %d to ",
          (cmds[i].fdChanges[j].orig == DEFAULT) ? 0 :
           cmds[i].fdChanges[j].orig);

          if (cmds[i].fdChanges[j].moveTo == UNDEFINED)
            printf("UNDEFINED\n");
          else if (cmds[i].fdChanges[j].moveTo == FROMSTR)
            printf("FROMSTR (\"%s\")\n", cmds[i].fdChanges[j].s.c_str());
          else
            printf("Some other fd (%d)\n", cmds[i].fdChanges[j].moveTo);
        }

        if (cmds[i].fdChanges[j].type == OUTPUT) {
          printf("change fd %d to ",
          (cmds[i].fdChanges[j].orig == DEFAULT) ? 1 :
           cmds[i].fdChanges[j].orig);

          if (cmds[i].fdChanges[j].moveTo == UNDEFINED)
            printf("UNDEFINED\n");
          else
            printf("Some other fd (%d)\n", cmds[i].fdChanges[j].moveTo);
        }
      }
    }
    // */

    // now to execute all the commands
    // pipe
    int pa[2];
    std::vector<char*> paths;
    // getPaths
    fillPaths(paths);

    // prepare argv so I can delete them later
    std::vector<char**> argvs;
    for(unsigned i = 0; i < cmds.size(); ++i) {
      argvs.push_back(new char*[cmds[i].args.size()+1]);
    }

    for(unsigned cmdi = 0; cmdi < cmds.size(); ++cmdi) {
      size_t argsSize = cmds[cmdi].args.size();
      int exitStatus = 0;

      char* arg = cmds[cmdi].args[0];
      char** argv = argvs[cmdi];
      for(unsigned j = 0; j < argsSize; ++j) {
        argv[j] = cmds[cmdi].args[j];
      }
      argv[argsSize] = NULL;

      if (strcmp(arg, "exit") == 0) {
        quit = true;
        break;
      } else if (strcmp(arg, "cd") == 0) {
        if (argv[1] == NULL) {
          if (-1 == chdir(getenv("HOME"))) {
            perror("cd");
          }
        } else {
          if (-1 == chdir(argv[1])) {
            perror("cd");
          }
        }
        continue;
      }

      if (cmds[cmdi].connector == PIPE) {
        // 1. make pipe
        if (-1 == pipe(pa)) {
          perror("pipe");
          exit(1);
        }
        // 2. this program gets output and next program gets input
        // this program:
        fdChange_t outfdC(1, pa[1], OUTPUT);
        fdChange_t infdC(0, pa[0], INPUT);

        cmds[cmdi].fdChanges.push_back(outfdC);
        cmds[cmdi].closefd.push_back(pa[1]);
        // next program:
        cmds[cmdi+1].fdChanges.push_back(infdC);
        cmds[cmdi+1].closefd.push_back(pa[0]);

      }

      std::map<int, fdData_t> fds;
      for(unsigned j = 0; j < cmds[cmdi].fdChanges.size(); ++j) {
        int o           = cmds[cmdi].fdChanges[j].orig;
        int mt          = cmds[cmdi].fdChanges[j].moveTo;
        int t           = cmds[cmdi].fdChanges[j].type;
        std::string str = cmds[cmdi].fdChanges[j].s;

        if (t == INPUT) {
          if (mt == FILEIN) {
            fds.insert(std::pair<int, fdData_t>(o, fdData_t(-1, DT_FIN, str)));
            // printf("Adding %d pointing to the file %s in input mode\n", o, str.c_str());
          } else if (mt == FROMSTR) {
            fds.insert(std::pair<int, fdData_t>(o, fdData_t(-1, DT_STR, str)));
            // printf("Adding %d pointing to the string %s in input mode\n", o, str.c_str());
          } else {
            fds.insert(std::pair<int, fdData_t>(o, fdData_t(mt, DT_FDIN, str)));
            // printf("Adding %d pointing to the fd %d in input mode\n", mt, o);
          }
        } else if (t == OUTPUT) {
          if (mt == FILEOUT) {
            fds.insert(std::pair<int, fdData_t>(-1, fdData_t(o, DT_FOW, str)));
            // printf("Adding %d pointing to the file %s in output write mode\n", o, str.c_str());
          } else if (mt == FILEAPP) {
            // if (fds
            fds.insert(std::pair<int, fdData_t>(-1, fdData_t(o, DT_FOA, str)));
            // printf("Adding %d pointing to the file %s in output append mode\n", o, str.c_str());
          } else {
            fds.insert(std::pair<int, fdData_t>(mt, fdData_t(o, DT_FDO, str)));
            // printf("Adding %d pointing to the fd %d in output mode\n", o, mt);
          }
        }
      }
      debugMap(fds);

      // arg and argv are now prepared
      pid_t pid = fork();
      if (-1 == pid) {
        perror("fork");
        exit(1); // fatal error
      } else if (0 == pid) { // child process
        deltaFD(fds);
        for(unsigned i = 0; i < paths.size(); ++i) {
          char* executable = new char[strlen(paths[i]) + strlen(arg) + 2];
          strcpy(executable, paths[i]);
          strcat(executable, "/");
          strcat(executable, arg);
          struct stat statRes;
          if (-1 != stat(executable, &statRes)) {
            if (-1 == execv(executable, argv)) {
              // if there's a return value (-1), there was a problem
              debug("executing");
              perror(executable);
              delete[] argv;
              delete[] executable;
              exit(1);
            }
          }
          if (false) {
            perror("stat");
          }
          errno = 0;
          delete[] executable;
        }
        fprintf(stderr, "%s: command not found\n", arg);
        delete[] argv;
        exit(1);
      } else { // parent process
        // close current fd's
        /*
        for(unsigned j = 0; j < cmds[cmdi].closefd.size(); ++j) {
          if (-1 == close(cmds[cmdi].closefd[j])) {
            perror("closing in parent");
            exit(1);
          }
        } */
        // only wait for non-pipes
        if (cmds[cmdi].connector != PIPE && -1 == waitpid(pid, &exitStatus, 0)) {
          perror("waitpid");
          exit(1);
        }
      }
      if (!exitStatus) { // all is good (0)
        while (cmdi < cmds.size() && cmds[cmdi].connector == OR) {
          ++cmdi;
        }
      } else { // last command failed
        while (cmdi < cmds.size() && cmds[cmdi].connector == AND) {
          ++cmdi;
        }
      }
    }

    // deallocate allocated memory
    for(unsigned i = 0; i < cmds.size(); ++i) {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j) {
        delete[] cmds[i].args[j];
      }
    }
    for(unsigned i = 0; i < paths.size(); ++i) {
      delete[] paths[i];
    }
    for(unsigned i = 0; i < argvs.size(); ++i) {
      delete[] argvs[i];
    }
  }
  printf("Goodbye!\n");
  return 0;
}

<|endoftext|>


<commit_before>#include <node.h>
#include <vector>
#include <map>
#include <iostream>

#include "Pump.h"
#include "calculator/PumpEfficiency.h"
#include "calculator/OptimalPumpEfficiency.h"
#include "calculator/MotorRatedPower.h"
#include "calculator/OptimalMotorRatedPower.h"
#include "calculator/MotorShaftPower.h"
#include "calculator/OptimalMotorShaftPower.h"
#include "calculator/PumpShaftPower.h"
#include "calculator/OptimalPumpShaftPower.h"
#include "calculator/MotorEfficiency.h"
#include "calculator/OptimalMotorEfficiency.h"
#include "calculator/MotorPowerFactor.h"
#include "calculator/OptimalMotorPowerFactor.h"
#include "calculator/MotorCurrent.h"
#include "calculator/OptimalMotorCurrent.h"
#include "calculator/MotorPower.h"
#include "calculator/OptimalMotorPower.h"
#include "AnnualEnergy.h"
#include "AnnualCost.h"
#include "AnnualSavingsPotential.h"
#include "OptimizationRating.h"

using namespace v8;
using namespace std;

Isolate* iso;
Local<Object> inp;

double Get(const char *nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();
  auto r = Object::New(iso);

  auto drive = (Pump::Drive)(int)Get("drive");
  auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");

  auto loadMeth = FieldData::LoadEstimationMethod::POWER;
  double mp = Get("motor_field_power");
  double mc = Get("motor_field_current");
  if (mc>0) {
    loadMeth = FieldData::LoadEstimationMethod::CURRENT;
    mp = (new MotorPower(Get("motor_rated_voltage"),mc,0))->calculate();//power factor
  } else {
    mc = (new MotorCurrent(Get("motor_rated_power"),Get("motor_rated_speed"),effCls,0))->calculate();//loadf
  }

  auto msp = (new MotorShaftPower(Get("motor_rated_power"),mp,Get("motor_rated_speed"),effCls,Get("motor_rated_voltage")));

  map<const char *,vector<double>> out = {
    {"Motor Shaft Power",{msp->calculate(),0}},
    {"Motor Current",{msp->calculateCurrent(),0}},
    {"Motor Efficiency",{msp->calculateEfficiency(),0}},
    {"Motor Power Factor",{msp->calculateElectricPower(),0}},
    {"Motor Power", {msp->calculateElectricPower(),0}}
  };
  for(auto p: out) {
    auto a = Array::New(iso);
    a->Set(0,Number::New(iso,p.second[0]));
    a->Set(1,Number::New(iso,p.second[1]));
    r->Set(String::NewFromUtf8(iso,p.first),a);
  }
  // SetR({
  //   0,//(new PumpEfficiency(Get("specific_gravity"),Get("flow"),Get("head"),0))->calculate(),//pumpShaftPower
  //   0,//(new OptimalPumpEfficiency(static_cast<Pump::Style>(Get("style")),
  //     //Get("pump_rated_speed"),Get("viscosity"),Get("stages"),Get("flow"),Get("head"),static_cast<Pump::Speed>(!Get("speed"))))->calculate(),
  //   0,//mp,
  //   0,//(new OptimalMotorRatedPower(0,Get("margin")))->calculate(),//motorshaftpower
  //   (new MotorShaftPower(Get("motor_rated_power"),mp,Get("motor_rated_speed"),effCls,Get("motor_rated_voltage")))->calculate(),
  //   0,//(new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower
  //   0,//(new PumpShaftPower(0,drive))->calculate(),//motorshaftpower
  //   0,//(new OptimalPumpShaftPower(Get("flow"),Get("head"),Get("specific_gravity"),0))->calculate(),//pumpeff
  //   0,//(new MotorEfficiency(Get("motor_rated_speed"),effCls,Get("motor_rated_power"),mp,0))->calculate(),//loadF
  //   0,//(new OptimalMotorEfficiency(Get("motor_rated_power"),0))->calculate(),//motor shaft power
  //   0,//(new MotorPowerFactor(Get("motor_rated_power"),0,mc,0,Get("motor_rated_voltage")))->calculate(),//loadFactor??, motor eff
  //   0,//(new OptimalMotorPowerFactor(Get("motor_rated_power"),0))->calculate(),//opt motor power?
  //   0,//mc,
  //   0,//(new OptimalMotorCurrent(0,Get("field_voltage")))->calculate(),//opt motor power
  //   0,//mp,
  //   0,//(new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff
  //   0,//(new AnnualEnergy(mp,Get("fraction")))->calculate(),//motorpower
  //   0,//(new AnnualEnergy(0,Get("fraction")))->calculate(),//opt motorpower
  //   0,//(new AnnualCost(0,Get("cost")))->calculate(),//ex ann energy
  //   0,//(new AnnualCost(0,Get("cost")))->calculate(),//opt ann energy
  //   -1,
  //   0,//(new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost
  //   -1,
  //   0,//(new OptimizationRating(0,0))->calculate()//ex an cost, opt an cost
  // });
  args.GetReturnValue().Set(r);
}
void EstFLA(const FunctionCallbackInfo<Value>& args) {
  args[0]->NumberValue();//hp
  args[1]->NumberValue();//speed
  args[2]->NumberValue();//v
  args[3]->NumberValue();//cls
  args[4]->NumberValue();//cus cls
  args.GetReturnValue().Set(args[4]);
}
void Check(double exp, double act, const char* nm="") {
  if (abs(exp-act)>.01*exp) {
    printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
    assert(!"equal");
  }
}
void TestSame() {
  auto msp = (new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460));
  for (int i=1; i<=10000; i=i+2) {
    Check(msp->calculate(),msp->calculate(),"SAME");
  }
}
void Test(const FunctionCallbackInfo<Value>& args) {
  //TestSame();
  Check(101.255,(new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460))->calculate());
  Check(143.4,(new MotorShaftPower(200,111.855,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460))->calculate());
}
void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
  NODE_SET_METHOD(exports, "estFLA", EstFLA);
  NODE_SET_METHOD(exports, "test", Test);
}

NODE_MODULE(bridge, Init)

<commit_msg>no message<commit_after>#include <node.h>
#include <vector>
#include <map>
#include <iostream>

#include "Pump.h"
#include "calculator/PumpEfficiency.h"
#include "calculator/OptimalPumpEfficiency.h"
#include "calculator/MotorRatedPower.h"
#include "calculator/OptimalMotorRatedPower.h"
#include "calculator/MotorShaftPower.h"
#include "calculator/OptimalMotorShaftPower.h"
#include "calculator/PumpShaftPower.h"
#include "calculator/OptimalPumpShaftPower.h"
#include "calculator/MotorEfficiency.h"
#include "calculator/OptimalMotorEfficiency.h"
#include "calculator/MotorPowerFactor.h"
#include "calculator/OptimalMotorPowerFactor.h"
#include "calculator/MotorCurrent.h"
#include "calculator/OptimalMotorCurrent.h"
#include "calculator/MotorPower.h"
#include "calculator/OptimalMotorPower.h"
#include "AnnualEnergy.h"
#include "AnnualCost.h"
#include "AnnualSavingsPotential.h"
#include "OptimizationRating.h"

using namespace v8;
using namespace std;

Isolate* iso;
Local<Object> inp;

double Get(const char *nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();
  auto r = Object::New(iso);

  auto drive = (Pump::Drive)(int)Get("drive");
  auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");

  auto loadMeth = FieldData::LoadEstimationMethod::POWER;
  double mp = Get("motor_field_power");
  double mc = Get("motor_field_current");
  if (mc>0) {
    loadMeth = FieldData::LoadEstimationMethod::CURRENT;
    mp = (new MotorPower(Get("motor_rated_voltage"),mc,0))->calculate();//power factor
  } else {
    mc = (new MotorCurrent(Get("motor_rated_power"),Get("motor_rated_speed"),effCls,0))->calculate();//loadf
  }

  auto msp = (new MotorShaftPower(Get("motor_rated_power"),mp,Get("motor_rated_speed"),effCls,Get("motor_rated_voltage")));

  map<const char *,vector<double>> out = {
    {"Motor Shaft Power",{msp->calculate(),0}},
    {"Motor Efficiency",{msp->calculateEfficiency(),0}},
    {"Motor Current",{msp->calculateCurrent(),0}},
    {"Motor Power Factor",{msp->calculatePowerFactor(),0}},
    {"Motor Power", {msp->calculateElectricPower(),0}}
  };
  for(auto p: out) {
    auto a = Array::New(iso);
    a->Set(0,Number::New(iso,p.second[0]));
    a->Set(1,Number::New(iso,p.second[1]));
    r->Set(String::NewFromUtf8(iso,p.first),a);
  }
  // SetR({
  //   0,//(new PumpEfficiency(Get("specific_gravity"),Get("flow"),Get("head"),0))->calculate(),//pumpShaftPower
  //   0,//(new OptimalPumpEfficiency(static_cast<Pump::Style>(Get("style")),
  //     //Get("pump_rated_speed"),Get("viscosity"),Get("stages"),Get("flow"),Get("head"),static_cast<Pump::Speed>(!Get("speed"))))->calculate(),
  //   0,//mp,
  //   0,//(new OptimalMotorRatedPower(0,Get("margin")))->calculate(),//motorshaftpower
  //   (new MotorShaftPower(Get("motor_rated_power"),mp,Get("motor_rated_speed"),effCls,Get("motor_rated_voltage")))->calculate(),
  //   0,//(new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower
  //   0,//(new PumpShaftPower(0,drive))->calculate(),//motorshaftpower
  //   0,//(new OptimalPumpShaftPower(Get("flow"),Get("head"),Get("specific_gravity"),0))->calculate(),//pumpeff
  //   0,//(new MotorEfficiency(Get("motor_rated_speed"),effCls,Get("motor_rated_power"),mp,0))->calculate(),//loadF
  //   0,//(new OptimalMotorEfficiency(Get("motor_rated_power"),0))->calculate(),//motor shaft power
  //   0,//(new MotorPowerFactor(Get("motor_rated_power"),0,mc,0,Get("motor_rated_voltage")))->calculate(),//loadFactor??, motor eff
  //   0,//(new OptimalMotorPowerFactor(Get("motor_rated_power"),0))->calculate(),//opt motor power?
  //   0,//mc,
  //   0,//(new OptimalMotorCurrent(0,Get("field_voltage")))->calculate(),//opt motor power
  //   0,//mp,
  //   0,//(new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff
  //   0,//(new AnnualEnergy(mp,Get("fraction")))->calculate(),//motorpower
  //   0,//(new AnnualEnergy(0,Get("fraction")))->calculate(),//opt motorpower
  //   0,//(new AnnualCost(0,Get("cost")))->calculate(),//ex ann energy
  //   0,//(new AnnualCost(0,Get("cost")))->calculate(),//opt ann energy
  //   -1,
  //   0,//(new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost
  //   -1,
  //   0,//(new OptimizationRating(0,0))->calculate()//ex an cost, opt an cost
  // });
  args.GetReturnValue().Set(r);
}
void EstFLA(const FunctionCallbackInfo<Value>& args) {
  args[0]->NumberValue();//hp
  args[1]->NumberValue();//speed
  args[2]->NumberValue();//v
  args[3]->NumberValue();//cls
  args[4]->NumberValue();//cus cls
  args.GetReturnValue().Set(args[4]);
}
void Check(double exp, double act, const char* nm="") {
  if (abs(exp-act)>.01*exp) {
    printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
    assert(!"equal");
  }
}
void TestSame() {
  auto msp = (new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460));
  for (int i=1; i<=10000; i=i+2) {
    Check(msp->calculate(),msp->calculate(),"SAME");
  }
}
void Test(const FunctionCallbackInfo<Value>& args) {
  //TestSame();
  auto msp = new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460);
  Check(101.3,msp->calculate());
  Check(94.4,msp->calculateEfficiency());
  Check(79.5,msp->calculateCurrent());
  Check(145.2,msp->calculatePowerFactor());
  Check(80,msp->calculateElectricPower());

  Check(143.4,(new MotorShaftPower(200,111.855,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460))->calculate());
}
void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
  NODE_SET_METHOD(exports, "estFLA", EstFLA);
  NODE_SET_METHOD(exports, "test", Test);
}

NODE_MODULE(bridge, Init)

<|endoftext|>


<commit_before><commit_msg>Fix typo in ASTStructuralEquivalence.cpp for UnaryTransform types.<commit_after><|endoftext|>


<commit_before>#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

int main(int argc, char *argv[])
{
    // For this example, wizard-generates single line code would be good enough,
    // but very soon it won't be enough for you anyway, so use this more detailed example from start
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    Factorizer fact;

#ifdef QT_QML_DEBUG
    runUnitTests();
#endif

//    Here's how you will add QML components whenever you start using them
//    Check https://github.com/amarchen/Wikipedia for a more full example
//    view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString());
    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->setTitle("Sailfactor");

    app->setApplicationName("harbour-sailfactor");
    app->setApplicationDisplayName("Sailfactor");

    view->show();

    return app->exec();
}
<commit_msg>Remove comments originating from Helloworld Pro...<commit_after>#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    Factorizer fact;

#ifdef QT_QML_DEBUG
    runUnitTests();
#endif

    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->setTitle("Sailfactor");

    app->setApplicationName("harbour-sailfactor");
    app->setApplicationDisplayName("Sailfactor");

    view->show();

    return app->exec();
}
<|endoftext|>