Example #1
0
int		AcServerHandle::Accept()
{
    //static socklen_t	s_addr_len = sizeof(sockaddr_in);
    int client_fd;
    sockaddr_in	addr;
    client_fd = net_accept(fd_, &addr);
    if(client_fd < 1) {
        ERROR_OUT("Failed to accept");
        return -1;
    }

    DEBUG_MSG("Accept fd: %d", client_fd);
    AcHandle	*handle	= new AcConnectHandle;
    if(NULL == handle) {
        ERROR_OUT("Failed to allocate memory");
        close(client_fd);
        return -1;
    }

    assert(dispatcher_);

    handle->set_fd(client_fd);
    handle->set_address(addr);
    handle->set_dispatcher(dispatcher_);

    dispatcher_->AddEvent(handle,EVENT_READ);

    return 0;
}
Example #2
0
bs_error_t bitstring_create_alloc(bs_t** bst)
{
	bs_t* _bst							= NULL;
	bs_error_t err					= BS_ERR_NONE;

	if(NULL == bst)					{ ERROR_OUT(BS_NULL_ARG) }
	if(NULL != (*bst))			{ ERROR_OUT(BS_INVALID_ARG) }

	_bst										= calloc(1, sizeof(bst));
	if(NULL == _bst)				{ ERROR_OUT(BS_ALLOC_FAIL) }

	err											= bitstring_create(_bst);
	if(BS_ERR_NONE != err)	{ ERROR_OUT(err) }

	(*bst)									= _bst;

cleanup:
	// if the user's pointer was not set, free the allocated memory due to error
	if(NULL == (*bst))
	{
		free(_bst);
	}

	return									(err);
}
Example #3
0
//**************************************************************************
bool ipage_t::writePage( FILE *fp )
{
  uint64   pc;
  uint32   index;
  uint32   instr;
  int      numwritten;

  // write the physical PC
  ASSERT ( sizeof(pa_t) == sizeof(uint64) );
  pc = m_header.m_physical_addr;
  numwritten = myfwrite( &pc, sizeof(uint64), 1, fp );
  if (numwritten != 1) {
    ERROR_OUT("write fails: ipage_t writePage (%d)\n", numwritten);
    return (false);
  }

  // for each non-NULL instruction
  for (index = 0; index < IPAGE_MAX_INSTR; index ++) {
    if (m_instr[index]) {
      // get the instruction from the static instruction
      instr = m_instr[index]->getInst();
    } else {
      // a version of the illegal trap instruction
      instr = 0;
    }
    numwritten = myfwrite( &instr, sizeof(uint32), 1, fp );
    if (numwritten != 1) {
      ERROR_OUT("write fails: ipage_t writePage (%d)\n", numwritten);
      return (false);
    }
  }
  return (true);
}
Example #4
0
int BSplineBasis2D::indexDerivativeBasisFunction(int _derivDegree, int _uDerivIndex,
        int _vDerivIndex, int _basisIndex) {
    /*
     * Returns the correct index when sorting the basis functions and the their derivatives in an 1D pointer array with the rule:
     * _basisFctsAndDerivs = new double[(_derivDegree - _vDerivIndex) * (_derivDegree - _vDerivIndex+1) * noBasisFcts/2 + _uDerivIndex * noBasisFcts + _basisIndex]
     */

    // Read input
    if (_uDerivIndex + _vDerivIndex > _derivDegree) {
        ERROR_OUT() << "in BSplineBasis2D::indexDerivativeBasisFunction";
        ERROR_OUT() << "It has been requested the " << _uDerivIndex << "-th partial derivative w.r.t. u and" << endl;
        ERROR_OUT() << "the " << _vDerivIndex << "-th partial derivative w.r.t. v of the basis functions but the maximum absolute derivative selected is of " << _derivDegree << "-th order" << endl;
    }

    // The polynomial degrees of the NURBS basis in both directions
    int pDegree = uBSplineBasis1D->getPolynomialDegree();
    int qDegree = vBSplineBasis1D->getPolynomialDegree();

    // The number of basis functions
    int noBasisFcts = (pDegree + 1) * (qDegree + 1);

    // Compute the index of the functional value
    return (_derivDegree - _vDerivIndex) * (_derivDegree - _vDerivIndex + 1) * noBasisFcts / 2
            + _uDerivIndex * noBasisFcts + _basisIndex;
}
/**
* Create a socket and use ZeroMQ to poll.
*/
void listener()
{
    WSADATA wsaData;
    int nResult = 0;
    int nOptOffVal = 0;
    int nOptOnVal = 1;
    int nOptLen = sizeof(int);

    // Initialize Winsock
    nResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (nResult != NO_ERROR) 
    {
        ERROR_OUT("zmqListen : WSAStartup failed");
    }

    //  Create UDP socket
    SOCKET fdSocket;
    fdSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (fdSocket == INVALID_SOCKET)
    {
        ERROR_OUT("zmqListen : Socket creation failed");
    }

    // Set up the sockaddr structure
    struct sockaddr_in saListen = {0};
    saListen.sin_family = AF_INET;
    saListen.sin_port = htons(PING_PORT_NUMBER);
    saListen.sin_addr.s_addr = htonl(INADDR_ANY);

    //  Bind the socket
    nResult = bind(fdSocket, (sockaddr*)&saListen, sizeof(saListen));
    if (nResult != NO_ERROR)
    {
        ERROR_OUT("zmqListen : socket bind failed");
    }

    while (!g_threadInterupted)
    {
        //  Poll socket for a message
        zmq::pollitem_t items[] = {{NULL, fdSocket, ZMQ_POLLIN, 0}};
        zmq::poll(&items[0], 1, SOCKET_POLL_TIMEOUT);

        //  If we get a message, print the contents
        if (items[0].revents & ZMQ_POLLIN)
        {
            char recvBuf[PING_MSG_SIZE] = {0};
            int saSize = sizeof(struct sockaddr_in);
            size_t size = recvfrom(fdSocket, recvBuf, PING_MSG_SIZE + 1, 0, (sockaddr*)&saListen, &saSize);
            {
                std::string ip(inet_ntoa(saListen.sin_addr));
                INFO_OUT("received: " + std::string(recvBuf) + " from " + ip);
            }
        }
    }

    closesocket(fdSocket);
    WSACleanup();
}
//-------------------------------------------------------------------------------
// @ IvFragmentShaderOGL::CreateFromFile()
//-------------------------------------------------------------------------------
// Load shader from a textfile
//-------------------------------------------------------------------------------
bool
IvFragmentShaderOGL::CreateFromFile( const char* filename )
{
    // Add the expected extension:
    std::string fullFilename = filename;

    fullFilename = fullFilename + std::string(".glslf");

    FILE* fp = fopen(fullFilename.c_str(), "r");

    if (!fp)
        return false;

    fseek(fp, 0, SEEK_END);
    unsigned int length = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    char* shaderSrc = new char[length+1];

    length = fread(shaderSrc, 1, length, fp);
    shaderSrc[length] = 0;

    // allocate the shader id
    mShaderID = glCreateShader( GL_FRAGMENT_SHADER );
    if ( mShaderID == 0 )
        return false;
    
    // load in the source
    GLint shaderLength = strlen(shaderSrc);
    glShaderSource( mShaderID, 1, (const GLchar**)&shaderSrc, &shaderLength );
    
    // compile it
    glCompileShader( mShaderID );
    GLint status = 0;
    glGetShaderiv( mShaderID, GL_COMPILE_STATUS, &status );
    if ( 0 == status )
    {
        GLint len;
        glGetShaderiv(mShaderID, GL_INFO_LOG_LENGTH, &len);
        if(len > 0) 
        {
            char* str = new char[len];
            glGetShaderInfoLog(mShaderID, len, nullptr, str);
            ERROR_OUT("Fragment shader error: ");
            ERROR_OUT(str << std::endl);
        }
        Destroy();
        return false;
    }

    return true;
}
Example #7
0
IGAPatchSurface* IGAMesh::addPatch(int _pDegree, int _uNoKnots, double* _uKnotVector, int _qDegree,
        int _vNoKnots, double* _vKnotVector, int _uNoControlPoints, int _vNoControlPoints,
        double* _controlPointNet, int* _dofIndexNet) {

    std::string patchName = name + " Patch";
    int IDBasis = 0;

    int numCPs = _uNoControlPoints * _vNoControlPoints;
    IGAControlPoint **cpNet;
    cpNet = new IGAControlPoint*[numCPs];

    for (int i = 0; i < numCPs; i++) {
        if (_dofIndexNet[i] < numNodes && _dofIndexNet[i] >= 0)
            cpNet[i] = new IGAControlPoint(_dofIndexNet[i], &_controlPointNet[i * 4]);
        else {
            ERROR_OUT() << "DOF " << _dofIndexNet[i] << " has not been defined" << endl;
            exit(-1);
        }
    }

    surfacePatches.push_back(
            new IGAPatchSurface(IDBasis, _pDegree, _uNoKnots, _uKnotVector, _qDegree, _vNoKnots,
                    _vKnotVector, _uNoControlPoints, _vNoControlPoints, cpNet));
    return surfacePatches.back();
}
Example #8
0
Message &operator<<(Message &message, NurbsBasis2D &nurbsBasis2D) {
    message << "\t" << "NurbsBasis2D: " << endl;

    message << "\t\tpDegree:  " << nurbsBasis2D.getUBSplineBasis1D()->getPolynomialDegree() << endl;
    message << "\t\tqDegree:  " << nurbsBasis2D.getVBSplineBasis1D()->getPolynomialDegree() << endl;

    message << "\t\tKnots Vector U: [\t";
    for (int i = 0; i < nurbsBasis2D.getUBSplineBasis1D()->getNoKnots(); i++)
        message << nurbsBasis2D.getUBSplineBasis1D()->getKnotVector()[i] << "\t";
    message << "]" << endl;

    message << "\t\tKnots Vector V: [\t";
    for (int i = 0; i < nurbsBasis2D.getVBSplineBasis1D()->getNoKnots(); i++)
        message << nurbsBasis2D.getVBSplineBasis1D()->getKnotVector()[i] << "\t";
    message << "]" << endl;

    message << "\t\tControl Points Net: " << endl;
    int count = 0;
    for (int j = 0; j < nurbsBasis2D.getVNoBasisFnc(); j++) {
        ERROR_OUT() << "\t\t";
        for (int i = 0; i < nurbsBasis2D.getUNoBasisFnc(); i++) {
            int Index = j * nurbsBasis2D.getUNoBasisFnc() + i;
            message << nurbsBasis2D.getIGAControlPointWeights()[Index] << "\t";
            count++;
        }
        message << endl;
    }

    message() << "\t" << "---------------------------------" << endl;
    return message;
}
void FUPluginManager::LoadPlugins(const FUObjectType& pluginType)
{
	for (PluginLibraryList::iterator it = loadedLibraries.begin(); it != loadedLibraries.end(); ++it)
	{
#ifndef _DEBUG
		try
#endif // _DEBUG
		{
			DEBUG_OUT("Loading plug-in: %s\n", TO_STRING((*it)->filename).c_str());
			FUAssert((*it)->createPlugin != NULL && (*it)->getPluginType != NULL && (*it)->getPluginCount != NULL, continue);
			uint32 pluginCount = (*((*it)->getPluginCount))();
			for (uint32 i = 0; i < pluginCount; ++i)
			{
				// Retrieve the types of all the plug-ins within this library.
				// Compare them against the wanted types and create the wanted plug-ins.
				const FUObjectType* type = (*((*it)->getPluginType))(i);
				if (type->Includes(pluginType))
				{
					FUPlugin* plugin = (*((*it)->createPlugin))(i);
					if (plugin == NULL) continue;
					loadedPlugins.push_back(plugin);
				}
			}
		}
#ifndef _DEBUG
		catch (...)
		{
			fm::string _filename = TO_STRING((*it)->filename);
			ERROR_OUT("Unhandled exception when loading plugin: %s.", _filename.c_str());
		}
#endif // _DEBUG
	}
}
Example #10
0
    void connectToServer(const char *address, const char *port,
            EventHandler *pProcessor) {
        sockaddr_in sin = { 0 };

        sin.sin_family = AF_INET;
        sin.sin_port = htons(atoi(port));
        inet_pton(AF_INET, address, &(sin.sin_addr));

        // Investigate: set reuse address and make socket nonblocking?

        bufferevent *bev = bufferevent_socket_new(m_ebase, -1,
                BEV_OPT_CLOSE_ON_FREE);

        bufferevent_setcb(bev, readfn, NULL, errorfn, (void*) pProcessor);
        pProcessor->setContext((Context*) bev);
        setParent(pProcessor);
        if (bufferevent_socket_connect(bev, (struct sockaddr *) &sin,
                sizeof(sin)) < 0) {
            ERROR_OUT("Cannot bind to port %s", port);
            /* Error starting connection */
            bufferevent_free(bev);
            exit(1);
        }

    }
Example #11
0
    void process() {

        while (!loopEnd) {
        	if (sem_wait(semNext) == -1) {
        		diep("sem_wait");
        	}
            if (!pbuff || !pbuff->len) {
                ERROR_OUT("Invalid buffer");
                exit(1);
            }
            EventHandler *dest = (pbuff->destId == ClientDest) ? client : server;
            if (dest == NULL) {
            	ERROR_OUT("Invalid dest");
            	exit(1);
            }
            dest->process(pbuff->buffer, pbuff->len, true);
        }

    }
Example #12
0
NurbsBasis2D::NurbsBasis2D(int _ID = 0, int _pDegree = 0, int _noKnotsU = 0, double* _KnotVectorU =
        NULL, int _qDegree = 0, int _noKnotsV = 0, double* _KnotVectorV = NULL,
        int _uNoBasisFnc = 0, int _vNoBasisFnc = 0, double* _igaControlPointWeights = NULL) :
        BSplineBasis2D(_ID, _pDegree, _noKnotsU, _KnotVectorU, _qDegree, _noKnotsV, _KnotVectorV), uNoBasisFnc(
                _uNoBasisFnc), vNoBasisFnc(_vNoBasisFnc) {

    // Read input
    bool ucondition = uNoBasisFnc
            != uBSplineBasis1D->getNoKnots() - uBSplineBasis1D->getPolynomialDegree() - 1;
    bool vcondition = vNoBasisFnc
            != vBSplineBasis1D->getNoKnots() - vBSplineBasis1D->getPolynomialDegree() - 1;
    if (ucondition || vcondition) {
        ERROR_OUT() << "Error in NurbsBasis2D::NurbsBasis2D" << endl;
        ERROR_OUT() << "The number of Control Points, the polynomial degrees and the knot vectors do not match" << endl;
        exit(-1);
    }

    // Assign the pointer of the Control Point Weights to the protected member of the class
    IGAControlPointWeights = _igaControlPointWeights;
}
Example #13
0
//**************************************************************************
bool ipage_t::readPage( FILE *fp, pa_t tag, uint32 &totalread )
{
  uint64   pc;
  uint32   index;
  uint32   instr;
  int      numread;
  int      count = 0;

  // right shift the bits, so the offset can simply be masked on
  tag = tag << IPAGE_PAGE_BITS;

  // read the physical PC
  ASSERT ( sizeof(pa_t) == sizeof(uint64) );
  numread = myfread( &pc, sizeof(uint64), 1, fp );
  if (numread != 1) {
    ERROR_OUT("read fails: ipage_t readPage (%d)\n", numread);
    return (false);
  }
  m_header.m_physical_addr = pc;

  for (index = 0; index < IPAGE_MAX_INSTR; index ++) {

    numread = myfread( &instr, sizeof(uint32), 1, fp );
    if (numread != 1) {
      ERROR_OUT("read fails: ipage_t readPage (%d)\n", numread);
      return (false);
    }
    
    if (instr == 0) {
      m_instr[index] = NULL;
    } else {
      // decode and add this instruction to the page
      pa_t ppc = m_header.m_physical_addr | index;
      m_instr[index] = new static_inst_t( ppc, instr );    
      count++;
    }
  }

  totalread += count;
  return (true);
}
Example #14
0
//**************************************************************************
void debugio_t::openLog( const char *logFileName )
{
  if ( g_compressed_output ) {
    char   cmd[FILEIO_MAX_FILENAME];
    sprintf( cmd, "/s/std/bin/gzip > %s.gz", logFileName );
    m_logfp = popen( cmd, "w" );
  } else {
    m_logfp = fopen( logFileName, "w" );
    if ( m_logfp == NULL ) {
      ERROR_OUT("debugio_t: openLog error: unable to open log file %s\n", logFileName );
    }
  }
}
Example #15
0
static int RsaFunction(const byte* in, word32 inLen, byte* out, word32* outLen,
                       int type, RsaKey* key)
{
    #define ERROR_OUT(x) { ret = x; goto done;}

    mp_int tmp;
    int    ret = 0;
    word32 keyLen, len;

    if (mp_init(&tmp) != MP_OKAY)
        return MP_INIT_E;

    if (mp_read_unsigned_bin(&tmp, (byte*)in, inLen) != MP_OKAY)
        ERROR_OUT(MP_READ_E);

    if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) {
        #ifdef RSA_LOW_MEM      /* half as much memory but twice as slow */
            if (mp_exptmod(&tmp, &key->d, &key->n, &tmp) != MP_OKAY)
                ERROR_OUT(MP_EXPTMOD_E);
        #else
            #define INNER_ERROR_OUT(x) { ret = x; goto inner_done; }

            mp_int tmpa, tmpb;

            if (mp_init(&tmpa) != MP_OKAY)
                ERROR_OUT(MP_INIT_E);

            if (mp_init(&tmpb) != MP_OKAY) {
                mp_clear(&tmpa);
                ERROR_OUT(MP_INIT_E);
            }

            /* tmpa = tmp^dP mod p */
            if (mp_exptmod(&tmp, &key->dP, &key->p, &tmpa) != MP_OKAY)
                INNER_ERROR_OUT(MP_EXPTMOD_E);

            /* tmpb = tmp^dQ mod q */
            if (mp_exptmod(&tmp, &key->dQ, &key->q, &tmpb) != MP_OKAY)
                INNER_ERROR_OUT(MP_EXPTMOD_E);

            /* tmp = (tmpa - tmpb) * qInv (mod p) */
            if (mp_sub(&tmpa, &tmpb, &tmp) != MP_OKAY)
                INNER_ERROR_OUT(MP_SUB_E);

            if (mp_mulmod(&tmp, &key->u, &key->p, &tmp) != MP_OKAY)
                INNER_ERROR_OUT(MP_MULMOD_E);

            /* tmp = tmpb + q * tmp */
            if (mp_mul(&tmp, &key->q, &tmp) != MP_OKAY)
                INNER_ERROR_OUT(MP_MUL_E);

            if (mp_add(&tmp, &tmpb, &tmp) != MP_OKAY)
                INNER_ERROR_OUT(MP_ADD_E);

        inner_done:
            mp_clear(&tmpa);
            mp_clear(&tmpb);

            if (ret != 0) return ret;

        #endif   /* RSA_LOW_MEM */
    }
    else if (type == RSA_PUBLIC_ENCRYPT || type == RSA_PUBLIC_DECRYPT) {
        if (mp_exptmod(&tmp, &key->e, &key->n, &tmp) != MP_OKAY)
            ERROR_OUT(MP_EXPTMOD_E);
    }
    else
        ERROR_OUT(RSA_WRONG_TYPE_E);

    keyLen = mp_unsigned_bin_size(&key->n);
    if (keyLen > *outLen)
        ERROR_OUT(RSA_BUFFER_E);

    len = mp_unsigned_bin_size(&tmp);

    /* pad front w/ zeros to match key length */
    while (len < keyLen) {
        *out++ = 0x00;
        len++;
    }

    *outLen = keyLen;

    /* convert */
    if (mp_to_unsigned_bin(&tmp, out) != MP_OKAY)
        ERROR_OUT(MP_TO_E);
   
done: 
    mp_clear(&tmp);
    return ret;
}
Example #16
0
/**
* Run broadcast and listen in seperate threads
*/
int main()
{
    g_threadInterupted = false;
    
    // Start listener in a seperate thread
    std::thread listenerThread(listener);

    Sleep(1000);

    {
        WSADATA wsaData;
        int nResult = 0;
        int nOptOffVal = 0;
        int nOptOnVal = 1;
        int nOptLen = sizeof(int);

        // Initialize Winsock
        nResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if (nResult != NO_ERROR)
        {
            ERROR_OUT("broadcast : WSAStartup failed");
        }

        //  Create UDP socket
        SOCKET fdSocket;
        fdSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (fdSocket == INVALID_SOCKET)
        {
            ERROR_OUT("broadcast : socket creation failed");
        }

        //  Ask operating system to let us do broadcasts from socket
        nResult = setsockopt(fdSocket, SOL_SOCKET, SO_BROADCAST, (char *)&nOptOnVal, nOptLen);
        if (nResult != NO_ERROR)
        {
            ERROR_OUT("broadcast : setsockopt SO_BROADCAST failed");
        }

        // Set up the sockaddr structure
        struct sockaddr_in saBroadcast = {0};
        saBroadcast.sin_family = AF_INET;
        saBroadcast.sin_port = htons(PING_PORT_NUMBER);
        saBroadcast.sin_addr.s_addr = htonl(INADDR_BROADCAST);

        //  Broadcast 5 beacon messages
        for (int i = 0; i < 5; i++)
        {
            char buffer[PING_MSG_SIZE] = {0};
            strcpy(&buffer[0], "!");
            int bytes = sendto(fdSocket, buffer, PING_MSG_SIZE + 1, 0, (sockaddr*)&saBroadcast, sizeof(struct sockaddr_in));
            if (bytes == SOCKET_ERROR)
            {
                ERROR_OUT("broadcast : sendto failed");
            }
            Sleep(PING_INTERVAL);
        }

        closesocket(fdSocket);
        WSACleanup();
    }

    Sleep(1000);
    
    g_threadInterupted = true;

    listenerThread.join();

    return 0;
}
Example #17
0
int main(int argc, char *argv[])
{
	struct kingrid_info data;
	freenect_context *kn;
	freenect_device *kn_dev;
	int rows = 40, cols = 96; // terminal size
	int opt;

	sigdata = &data;
	data.out_of_range = 0;
	data.done = 0;
	data.divisions = 6;
	data.boxwidth = 10;
	data.histrows = 8;
	data.frame = 0;
	data.zmin = 0.5;
	data.zmax = 5.0;
	data.disp_mode = STATS;

	if(getenv("LINES")) {
		rows = atoi(getenv("LINES"));
	}
	if(getenv("COLUMNS")) {
		cols = atoi(getenv("COLUMNS"));
	}

	// Handle command-line options
	while((opt = getopt(argc, argv, "shag:z:Z:")) != -1) {
		switch(opt) {
			case 's':
				// Stats mode
				data.disp_mode = STATS;
				break;
			case 'h':
				// Histogram mode
				data.disp_mode = HISTOGRAM;
				break;
			case 'a':
				// ASCII art mode
				data.disp_mode = ASCII;
				break;
			case 'g':
				// Grid divisions
				data.divisions = atoi(optarg);
				break;
			case 'z':
				// Near clipping
				data.zmin = atof(optarg);
				break;
			case 'Z':
				// Far clipping
				data.zmax = atof(optarg);
				break;
			default:
				fprintf(stderr, "Usage: %s -[sha] [-g divisions] [-zZ distance]\n", argv[0]);
				fprintf(stderr, "Use up to one of:\n");
				fprintf(stderr, "\ts - Stats mode (default)\n");
				fprintf(stderr, "\th - Histogram mode\n");
				fprintf(stderr, "\ta - ASCII art mode\n");
				fprintf(stderr, "Use any of:\n");
				fprintf(stderr, "\tg - Set grid divisions for both dimensions\n");
				fprintf(stderr, "\tz - Set near clipping plane in meters for ASCII art mode (default 0.5)\n");
				fprintf(stderr, "\tZ - Set far clipping plane in meters for ASCII art mode (default 5.0)\n");
				return -1;
		}
	}

	data.boxwidth = (cols - 1) / data.divisions - 3;
	if(data.boxwidth < 10) {
		data.boxwidth = 10;
	}
	data.histrows = (rows - 2) / data.divisions - 1;
	
	init_lut(data.depth_lut);

	if(signal(SIGINT, intr) == SIG_ERR ||
			signal(SIGTERM, intr) == SIG_ERR) {
		ERROR_OUT("Error setting signal handlers\n");
		return -1;
	}

	if(freenect_init(&kn, NULL) < 0) {
		ERROR_OUT("libfreenect init failed.\n");
		return -1;
	}

	INFO_OUT("Found %d Kinect devices.\n", freenect_num_devices(kn));

	if(freenect_num_devices(kn) == 0) {
		ERROR_OUT("No Kinect devices present.\n");
		return -1;
	}

	if(freenect_open_device(kn, &kn_dev, 0)) {
		ERROR_OUT("Error opening Kinect #0.\n");
		return -1;
	}

	freenect_set_user(kn_dev, &data);
	freenect_set_tilt_degs(kn_dev, -5);
	freenect_set_led(kn_dev, LED_GREEN);
	freenect_set_depth_callback(kn_dev, depth);
	freenect_set_depth_format(kn_dev, FREENECT_DEPTH_11BIT);

	freenect_start_depth(kn_dev);

	int last_oor = data.out_of_range;
	while(!data.done && freenect_process_events(kn) >= 0) {
		if(last_oor != data.out_of_range) {
			freenect_set_led(kn_dev, data.out_of_range ? LED_BLINK_RED_YELLOW : LED_GREEN);
			last_oor = data.out_of_range;
		}
	}

	freenect_stop_depth(kn_dev);
	freenect_set_led(kn_dev, LED_OFF);
	freenect_close_device(kn_dev);
	freenect_shutdown(kn);

	return 0;
}
//-------------------------------------------------------------------------------
// @ IvVertexShaderOGL::CreateFromFile()
//-------------------------------------------------------------------------------
// Create a shader from a file
//-------------------------------------------------------------------------------
bool
IvVertexShaderOGL::CreateFromFile( const char* filename )
{
    // Add the expected extension:
    std::string fullFilename = filename;

    fullFilename = fullFilename + std::string(".glslv");

    FILE* fp = fopen(fullFilename.c_str(), "r");

    if (!fp)
    {
        return false;
    }

    fseek(fp, 0, SEEK_END);
    unsigned int length = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    char* shaderSrc = new char[length+1];

    length = fread(shaderSrc, 1, length, fp);
    shaderSrc[length] = 0;
    fclose(fp);

    // allocate the shader id
    mShaderID = glCreateShader( GL_VERTEX_SHADER );
    if (mShaderID == 0)
    {
        return false;
    }
    
    // load in the source
    const char* shaderSources[2] = {sShaderHeader, shaderSrc};
    GLint shaderLengths[2] =
    {
        (GLint)strlen(sShaderHeader),
        (GLint)strlen(shaderSrc)
    };
    glShaderSource( mShaderID, 2, (const GLchar**)shaderSources, shaderLengths );
    
    // compile it
    glCompileShader( mShaderID );
    GLint status = 0;
    glGetShaderiv( mShaderID, GL_COMPILE_STATUS, &status );
    if ( 0 == status )
    {
        GLint len;
        glGetShaderiv(mShaderID, GL_INFO_LOG_LENGTH, &len);
        if(len > 0) 
        {
            char* str = new char[len];
            glGetShaderInfoLog(mShaderID, len, nullptr, str);
            ERROR_OUT("Vertex shader error: ");
            ERROR_OUT(str << std::endl);
            delete [] str;
        }
        delete [] shaderSrc;
        Destroy();
        return false;
    }

    delete [] shaderSrc;
    return true;
}
Example #19
0
 /**
  * @brief Reports progress to an instance of ProgressCallback.
  * 
  * If the value is not between 0.0 (inclusive) and 1.0 (inclusive),
  * a message will appear on the console, informing about that error.
  * 
  * @see ProgressCallback
  * 
  * @param value the amount of the job that is finished (0.0 <= value <= 1.0), if applicable.
  *      if not applicable, value < 0.0.
  * @param progressMessage an optional message that might be presented to the user.
  */
 virtual void progress(double value, const std::string& progressMessage)
 {
     if ((value < 0.0) || (value > 1.0))
         ERROR_OUT("ProgressCallbackCaller: value not between 0.0 and 1.0 (" << value << ").", 50);
     callback.progress(id, value, progressMessage);
 }
Example #20
0
bool FArchiveXML::ProcessChannels(FCDAnimated* animated, FCDAnimationChannelList& channels)
{
	bool linked = false;

	StringList& qualifiers = animated->GetQualifiers();
	for (FCDAnimationChannelList::iterator it = channels.begin(); it != channels.end(); ++it)
	{
		FCDAnimationChannel* channel = *it;
		size_t curveCount = channel->GetCurveCount();
		if (curveCount == 0) continue;
		
		// Retrieve the channel's qualifier and check for a requested matrix element
		FCDAnimationChannelDataMap::iterator itChannelData = FArchiveXML::documentLinkDataMap[channel->GetDocument()].animationChannelData.find(channel);
		FUAssert(itChannelData != FArchiveXML::documentLinkDataMap[channel->GetDocument()].animationChannelData.end(),);
		FCDAnimationChannelData& channelData = itChannelData->second;

		const fm::string& qualifier = channelData.targetQualifier;
		if (!qualifier.empty())
		{
			// Qualifed curves can only target a single element?
			FUAssert(curveCount == 1,);
			int32 element = -1;
			// If the animated is part of a list (ie, morph target weight, not a transform etc)
			if (animated->GetArrayElement() != -1)
			{
				// By definition, if an animated has an array element, it can only
				// animate a single value.
				element = FUStringConversion::ParseQualifier(qualifier);
				if (animated->GetArrayElement() != element) continue;
				else 
				{
					linked = animated->AddCurve(0, channel->GetCurve(0));
				}
			}
			else
			{
				// Attempt to match the qualifier with this animated qualifiers
				size_t index;
				for (index = 0; index < qualifiers.size(); ++index)
				{
					if (qualifiers[index] == qualifier) break;
				}


				// Check for bracket notation eg -(X)- instead
				if (index == qualifiers.size()) index = FUStringConversion::ParseQualifier(qualifier);
				if (index < qualifiers.size())
				{
					linked = animated->AddCurve(index, channel->GetCurve(0));
				}
				else 
				{
					// Attempt to match with some of the standard qualifiers instead.
					size_t checkCount = min((size_t) 4u, qualifiers.size());
					for (index = 0; index < checkCount; ++index)
					{
						if (IsEquivalent(qualifier, FCDAnimatedStandardQualifiers::XYZW[index])) break;
						else if (IsEquivalent(qualifier, FCDAnimatedStandardQualifiers::RGBA[index])) break;
					}
					if (index < checkCount)
					{
						linked = animated->AddCurve(index, channel->GetCurve(0));
						WARNING_OUT("Invalid qualfiier for animation channel target: %s - %s. Using non-standard match.", channelData.targetPointer.c_str(), qualifier.c_str());
					}
					else
					{
						const char* temp1 = channelData.targetPointer.c_str();
						const char* temp2 = qualifier.c_str();
						ERROR_OUT("Invalid qualifier for animation channel target: %s - %s", temp1, temp2);
					}
				}
				//else return status.Fail(FS("Invalid qualifier for animation channel target: ") + TO_FSTRING(pointer));

			}
		}
		else
		{
Example #21
0
// ----------------------------------------------------------------
mv_t s_ss_dot_func(mv_t* pval1, mv_t* pval2) {
	int len1 = strlen(pval1->u.strv);
	int len2 = strlen(pval1->u.strv);
	int len3 = len1 + len2 + 1; // for the null-terminator byte
	char* string3 = mlr_malloc_or_die(len3);
	strcpy(&string3[0], pval1->u.strv);
	strcpy(&string3[len1], pval2->u.strv);

	// xxx encapsulate this:
	free(pval1->u.strv);
	free(pval2->u.strv);
	pval1->u.strv = NULL;
	pval2->u.strv = NULL;

	mv_t rv = {.type = MT_STRING, .u.strv = string3};
	return rv;
}

// ----------------------------------------------------------------
mv_t s_sss_sub_func(mv_t* pval1, mv_t* pval2, mv_t* pval3) {
	char* substr = strstr(pval1->u.strv, pval2->u.strv);
	if (substr == NULL) {
		return *pval1;
	} else {
		int  len1 = substr - pval1->u.strv;
		int olen2 = strlen(pval2->u.strv);
		int nlen2 = strlen(pval3->u.strv);
		int  len3 = strlen(&pval1->u.strv[len1 + olen2]);
		int  len4 = len1 + nlen2 + len3;

		char* string4 = mlr_malloc_or_die(len4);
		strncpy(&string4[0],    pval1->u.strv, len1);
		strncpy(&string4[len1], pval3->u.strv, nlen2);
		strncpy(&string4[len1+nlen2], &pval1->u.strv[len1+olen2], len3);

		free(pval1->u.strv);
		free(pval2->u.strv);
		free(pval3->u.strv);
		pval1->u.strv = NULL;
		pval2->u.strv = NULL;
		pval3->u.strv = NULL;

		mv_t rv = {.type = MT_STRING, .u.strv = string4};
		return rv;
	}
}

// ----------------------------------------------------------------
// xxx cmt mem-mgt & contract. similar to lrec-mapper contract.
mv_t s_s_tolower_func(mv_t* pval1) {
	char* string = strdup(pval1->u.strv);
	for (char* c = string; *c; c++)
		*c = tolower(*c);
	// xxx encapsulate this:
	free(pval1->u.strv);
	pval1->u.strv = NULL;

	mv_t rv = {.type = MT_STRING, .u.strv = string};
	return rv;
}

// xxx cmt mem-mgt & contract. similar to lrec-mapper contract.
mv_t s_s_toupper_func(mv_t* pval1) {
	char* string = strdup(pval1->u.strv);
	for (char* c = string; *c; c++)
		*c = toupper(*c);
	// xxx encapsulate this:
	free(pval1->u.strv);
	pval1->u.strv = NULL;

	mv_t rv = {.type = MT_STRING, .u.strv = string};
	return rv;
}

// ----------------------------------------------------------------
mv_t s_f_sec2gmt_func(mv_t* pval1) {
	ERROR_OUT(*pval1);
	mt_get_double_nullable(pval1);
	NULL_OUT(*pval1);
	if (pval1->type != MT_DOUBLE)
		return MV_ERROR;
	time_t clock = (time_t) pval1->u.dblv;
	struct tm tm;
	struct tm *ptm = gmtime_r(&clock, &tm);
	// xxx use retval which is size_t
	// xxx error-check all of this ...
	char* string = mlr_malloc_or_die(32);
	(void)strftime(string, 32, "%Y-%m-%dT%H:%M:%SZ", ptm);

	mv_t rv = {.type = MT_STRING, .u.strv = string};
	return rv;
}

mv_t i_s_gmt2sec_func(mv_t* pval1) {
	struct tm tm;
	if (*pval1->u.strv == '\0') {
		return MV_NULL;
	} else {
		strptime(pval1->u.strv, "%Y-%m-%dT%H:%M:%SZ", &tm);
		time_t t = timegm(&tm);

		mv_t rv = {.type = MT_INT, .u.intv = (long long)t};
		return rv;
	}
}

// ----------------------------------------------------------------
mv_t i_s_strlen_func(mv_t* pval1) {
	mv_t rv = {.type = MT_INT, .u.intv = strlen(pval1->u.strv)};
	return rv;
}

// ----------------------------------------------------------------
static mv_t int_i_n(mv_t* pa) { return (mv_t) {.type = MT_NULL,  .u.intv = 0}; }
static mv_t int_i_e(mv_t* pa) { return (mv_t) {.type = MT_ERROR, .u.intv = 0}; }
static mv_t int_i_b(mv_t* pa) { return (mv_t) {.type = MT_INT,   .u.intv = pa->u.boolv ? 1 : 0}; }
static mv_t int_i_d(mv_t* pa) { return (mv_t) {.type = MT_INT,   .u.intv = (long long)round(pa->u.dblv)}; }
static mv_t int_i_i(mv_t* pa) { return (mv_t) {.type = MT_INT,   .u.intv = pa->u.intv}; }
static mv_t int_i_s(mv_t* pa) {
	mv_t retval = (mv_t) {.type = MT_INT };
	if (*pa->u.strv == '\0')
		return MV_NULL;
	if (!mlr_try_int_from_string(pa->u.strv, &retval.u.intv))
		retval.type = MT_ERROR;
	return retval;
}

static mv_unary_func_t* int_dispositions[MT_MAX] = {
    /*NULL*/   int_i_n,
    /*ERROR*/  int_i_e,
    /*BOOL*/   int_i_b,
    /*DOUBLE*/ int_i_d,
    /*INT*/    int_i_i,
    /*STRING*/ int_i_s,
};

mv_t i_x_int_func(mv_t* pval1) { return (int_dispositions[pval1->type])(pval1); }

// ----------------------------------------------------------------
// xxx i'm using double & long long but saying double & int. this is confusing & needs fixing.
static mv_t float_f_n(mv_t* pa) { return (mv_t) {.type = MT_NULL,   .u.intv = 0}; }
static mv_t float_f_e(mv_t* pa) { return (mv_t) {.type = MT_ERROR,  .u.intv = 0}; }
static mv_t float_f_b(mv_t* pa) { return (mv_t) {.type = MT_DOUBLE, .u.dblv = pa->u.boolv ? 1.0 : 0.0}; }
static mv_t float_f_d(mv_t* pa) { return (mv_t) {.type = MT_DOUBLE, .u.dblv = pa->u.dblv}; }
static mv_t float_f_i(mv_t* pa) { return (mv_t) {.type = MT_DOUBLE, .u.dblv = pa->u.intv}; }
static mv_t float_f_s(mv_t* pa) {
	mv_t retval = (mv_t) {.type = MT_DOUBLE };
	if (*pa->u.strv == '\0')
		return MV_NULL;
	if (!mlr_try_double_from_string(pa->u.strv, &retval.u.dblv))
		retval.type = MT_ERROR;
	return retval;
}

static mv_unary_func_t* float_dispositions[MT_MAX] = {
    /*NULL*/   float_f_n,
    /*ERROR*/  float_f_e,
    /*BOOL*/   float_f_b,
    /*DOUBLE*/ float_f_d,
    /*INT*/    float_f_i,
    /*STRING*/ float_f_s,
};

mv_t f_x_float_func(mv_t* pval1) { return (float_dispositions[pval1->type])(pval1); }

// ----------------------------------------------------------------
static mv_t boolean_b_n(mv_t* pa) { return (mv_t) {.type = MT_NULL,  .u.intv = 0}; }
static mv_t boolean_b_e(mv_t* pa) { return (mv_t) {.type = MT_ERROR, .u.intv = 0}; }
static mv_t boolean_b_b(mv_t* pa) { return (mv_t) {.type = MT_BOOL,  .u.boolv = pa->u.boolv}; }
static mv_t boolean_b_d(mv_t* pa) { return (mv_t) {.type = MT_BOOL,  .u.boolv = (pa->u.dblv == 0.0) ? FALSE : TRUE}; }
static mv_t boolean_b_i(mv_t* pa) { return (mv_t) {.type = MT_BOOL,  .u.boolv = (pa->u.intv == 0LL) ? FALSE : TRUE}; }
static mv_t boolean_b_s(mv_t* pa) { return (mv_t) {.type = MT_BOOL,
		.u.boolv = (streq(pa->u.strv, "true") || streq(pa->u.strv, "TRUE")) ? TRUE : FALSE
	};
}

static mv_unary_func_t* boolean_dispositions[MT_MAX] = {
    /*NULL*/   boolean_b_n,
    /*ERROR*/  boolean_b_e,
    /*BOOL*/   boolean_b_b,
    /*DOUBLE*/ boolean_b_d,
    /*INT*/    boolean_b_i,
    /*STRING*/ boolean_b_s,
};

mv_t b_x_boolean_func(mv_t* pval1) { return (boolean_dispositions[pval1->type])(pval1); }

// ----------------------------------------------------------------
static mv_t string_s_n(mv_t* pa) { return (mv_t) {.type = MT_NULL,   .u.intv = 0}; }
static mv_t string_s_e(mv_t* pa) { return (mv_t) {.type = MT_ERROR,  .u.intv = 0}; }
static mv_t string_s_b(mv_t* pa) { return (mv_t) {.type = MT_STRING, .u.strv = strdup(pa->u.boolv?"true":"false")}; }
static mv_t string_s_d(mv_t* pa) {
	return (mv_t) {.type = MT_STRING, .u.strv = mlr_alloc_string_from_double(pa->u.dblv, MLR_GLOBALS.ofmt)};
}
static mv_t string_s_i(mv_t* pa) { return (mv_t) {.type = MT_STRING, .u.strv = mlr_alloc_string_from_ll(pa->u.intv)}; }
static mv_t string_s_s(mv_t* pa) { return (mv_t) {.type = MT_STRING, .u.strv = pa->u.strv}; }

static mv_unary_func_t* string_dispositions[MT_MAX] = {
    /*NULL*/   string_s_n,
    /*ERROR*/  string_s_e,
    /*BOOL*/   string_s_b,
    /*DOUBLE*/ string_s_d,
    /*INT*/    string_s_i,
    /*STRING*/ string_s_s,
};

mv_t s_x_string_func(mv_t* pval1) { return (string_dispositions[pval1->type])(pval1); }

// ----------------------------------------------------------------
static mv_t hexfmt_s_n(mv_t* pa) { return (mv_t) {.type = MT_NULL,   .u.intv = 0}; }
static mv_t hexfmt_s_e(mv_t* pa) { return (mv_t) {.type = MT_ERROR,  .u.intv = 0}; }
static mv_t hexfmt_s_b(mv_t* pa) { return (mv_t) {.type = MT_STRING, .u.strv = strdup(pa->u.boolv?"0x1":"0x0")}; }
static mv_t hexfmt_s_d(mv_t* pa) {
	return (mv_t) {.type = MT_STRING, .u.strv = mlr_alloc_hexfmt_from_ll((long long)pa->u.dblv)};
}
static mv_t hexfmt_s_i(mv_t* pa) { return (mv_t) {.type = MT_STRING, .u.strv = mlr_alloc_hexfmt_from_ll(pa->u.intv)}; }
static mv_t hexfmt_s_s(mv_t* pa) { return (mv_t) {.type = MT_STRING, .u.strv = pa->u.strv}; }

static mv_unary_func_t* hexfmt_dispositions[MT_MAX] = {
    /*NULL*/   hexfmt_s_n,
    /*ERROR*/  hexfmt_s_e,
    /*BOOL*/   hexfmt_s_b,
    /*DOUBLE*/ hexfmt_s_d,
    /*INT*/    hexfmt_s_i,
    /*STRING*/ hexfmt_s_s,
};

mv_t s_x_hexfmt_func(mv_t* pval1) { return (hexfmt_dispositions[pval1->type])(pval1); }

// ----------------------------------------------------------------
static mv_t fmtnum_s_ns(mv_t* pa, mv_t* pfmt) { return (mv_t) {.type = MT_NULL,   .u.intv = 0}; }
static mv_t fmtnum_s_es(mv_t* pa, mv_t* pfmt) { return (mv_t) {.type = MT_ERROR,  .u.intv = 0}; }
static mv_t fmtnum_s_bs(mv_t* pa, mv_t* pfmt) { return (mv_t) {.type = MT_STRING, .u.strv = strdup(pa->u.boolv?"0x1":"0x0")}; }
static mv_t fmtnum_s_ds(mv_t* pa, mv_t* pfmt) {
	return (mv_t) {.type = MT_STRING, .u.strv = mlr_alloc_string_from_double(pa->u.dblv, pfmt->u.strv)};
}
static mv_t fmtnum_s_is(mv_t* pa, mv_t* pfmt) {
	return (mv_t) {.type = MT_STRING, .u.strv = mlr_alloc_string_from_ll_and_format(pa->u.intv, pfmt->u.strv)};
}
static mv_t fmtnum_s_ss(mv_t* pa, mv_t* pfmt) { return (mv_t) {.type = MT_ERROR, .u.intv = 0}; }

static mv_binary_func_t* fmtnum_dispositions[MT_MAX] = {
    /*NULL*/   fmtnum_s_ns,
    /*ERROR*/  fmtnum_s_es,
    /*BOOL*/   fmtnum_s_bs,
    /*DOUBLE*/ fmtnum_s_ds,
    /*INT*/    fmtnum_s_is,
    /*STRING*/ fmtnum_s_ss,
};

mv_t s_xs_fmtnum_func(mv_t* pval1, mv_t* pval2) { return (fmtnum_dispositions[pval1->type])(pval1, pval2); }

// ----------------------------------------------------------------
// xxx cmt us!!!!

static mv_t op_n_xx(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_NULL, .u.intv = 0}; }
static mv_t op_e_xx(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_ERROR, .u.intv = 0}; }

static  mv_t eq_b_ii(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv == pb->u.intv}; }
static  mv_t ne_b_ii(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv != pb->u.intv}; }
static  mv_t gt_b_ii(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv >  pb->u.intv}; }
static  mv_t ge_b_ii(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv >= pb->u.intv}; }
static  mv_t lt_b_ii(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv <  pb->u.intv}; }
static  mv_t le_b_ii(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv <= pb->u.intv}; }

static  mv_t eq_b_ff(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv == pb->u.dblv}; }
static  mv_t ne_b_ff(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv != pb->u.dblv}; }
static  mv_t gt_b_ff(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv >  pb->u.dblv}; }
static  mv_t ge_b_ff(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv >= pb->u.dblv}; }
static  mv_t lt_b_ff(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv <  pb->u.dblv}; }
static  mv_t le_b_ff(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv <= pb->u.dblv}; }

static  mv_t eq_b_fi(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv == pb->u.intv}; }
static  mv_t ne_b_fi(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv != pb->u.intv}; }
static  mv_t gt_b_fi(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv >  pb->u.intv}; }
static  mv_t ge_b_fi(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv >= pb->u.intv}; }
static  mv_t lt_b_fi(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv <  pb->u.intv}; }
static  mv_t le_b_fi(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.dblv <= pb->u.intv}; }

static  mv_t eq_b_if(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv == pb->u.dblv}; }
static  mv_t ne_b_if(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv != pb->u.dblv}; }
static  mv_t gt_b_if(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv >  pb->u.dblv}; }
static  mv_t ge_b_if(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv >= pb->u.dblv}; }
static  mv_t lt_b_if(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv <  pb->u.dblv}; }
static  mv_t le_b_if(mv_t* pa, mv_t* pb) { return (mv_t) {.type = MT_BOOL, .u.boolv = pa->u.intv <= pb->u.dblv}; }

static  mv_t eq_b_xs(mv_t* pa, mv_t* pb) {
	char* a = mt_format_val(pa);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(a, pb->u.strv) == 0};
	free(a);
	return rv;
}
static  mv_t ne_b_xs(mv_t* pa, mv_t* pb) {
	char* a = mt_format_val(pa);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(a, pb->u.strv) != 0};
	free(a);
	return rv;
}
static  mv_t gt_b_xs(mv_t* pa, mv_t* pb) {
	char* a = mt_format_val(pa);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(a, pb->u.strv) >  0};
	free(a);
	return rv;
}
static  mv_t ge_b_xs(mv_t* pa, mv_t* pb) {
	char* a = mt_format_val(pa);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(a, pb->u.strv) >= 0};
	free(a);
	return rv;
}
static  mv_t lt_b_xs(mv_t* pa, mv_t* pb) {
	char* a = mt_format_val(pa);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(a, pb->u.strv) <  0};
	free(a);
	return rv;
}
static  mv_t le_b_xs(mv_t* pa, mv_t* pb) {
	char* a = mt_format_val(pa);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(a, pb->u.strv) <= 0};
	free(a);
	return rv;
}

static  mv_t eq_b_sx(mv_t* pa, mv_t* pb) {
	char* b = mt_format_val(pb);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(pa->u.strv, b) == 0};
	free(b);
	return rv;
}
static  mv_t ne_b_sx(mv_t* pa, mv_t* pb) {
	char* b = mt_format_val(pb);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(pa->u.strv, b) != 0};
	free(b);
	return rv;
}
static  mv_t gt_b_sx(mv_t* pa, mv_t* pb) {
	char* b = mt_format_val(pb);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(pa->u.strv, b) >  0};
	free(b);
	return rv;
}
static  mv_t ge_b_sx(mv_t* pa, mv_t* pb) {
	char* b = mt_format_val(pb);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(pa->u.strv, b) >= 0};
	free(b);
	return rv;
}
static  mv_t lt_b_sx(mv_t* pa, mv_t* pb) {
	char* b = mt_format_val(pb);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(pa->u.strv, b) <  0};
	free(b);
	return rv;
}
static  mv_t le_b_sx(mv_t* pa, mv_t* pb) {
	char* b = mt_format_val(pb);
	mv_t rv = {.type = MT_BOOL, .u.boolv = strcmp(pa->u.strv, b) <= 0};
	free(b);
	return rv;
}

static mv_t eq_b_ss(mv_t*pa, mv_t*pb) {return (mv_t){.type=MT_BOOL, .u.boolv=strcmp(pa->u.strv, pb->u.strv) == 0};}
static mv_t ne_b_ss(mv_t*pa, mv_t*pb) {return (mv_t){.type=MT_BOOL, .u.boolv=strcmp(pa->u.strv, pb->u.strv) != 0};}
static mv_t gt_b_ss(mv_t*pa, mv_t*pb) {return (mv_t){.type=MT_BOOL, .u.boolv=strcmp(pa->u.strv, pb->u.strv) >  0};}
static mv_t ge_b_ss(mv_t*pa, mv_t*pb) {return (mv_t){.type=MT_BOOL, .u.boolv=strcmp(pa->u.strv, pb->u.strv) >= 0};}
static mv_t lt_b_ss(mv_t*pa, mv_t*pb) {return (mv_t){.type=MT_BOOL, .u.boolv=strcmp(pa->u.strv, pb->u.strv) <  0};}
static mv_t le_b_ss(mv_t*pa, mv_t*pb) {return (mv_t){.type=MT_BOOL, .u.boolv=strcmp(pa->u.strv, pb->u.strv) <= 0};}

static mv_binary_func_t* eq_dispositions[MT_MAX][MT_MAX] = {
    //         NULL      ERROR    BOOL     DOUBLE   INT      STRING
    /*NULL*/   {op_n_xx, op_e_xx, op_e_xx, op_n_xx, op_n_xx, op_n_xx},
    /*ERROR*/  {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*BOOL*/   {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*DOUBLE*/ {op_n_xx, op_e_xx, op_e_xx, eq_b_ff, eq_b_fi, eq_b_xs},
    /*INT*/    {op_n_xx, op_e_xx, op_e_xx, eq_b_if, eq_b_ii, eq_b_xs},
    /*STRING*/ {op_n_xx, op_e_xx, op_e_xx, eq_b_sx, eq_b_sx, eq_b_ss},
};

static mv_binary_func_t* ne_dispositions[MT_MAX][MT_MAX] = {
    //         NULL      ERROR    BOOL     DOUBLE   INT      STRING
    /*NULL*/   {op_n_xx, op_e_xx, op_e_xx, op_n_xx, op_n_xx, op_n_xx},
    /*ERROR*/  {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*BOOL*/   {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*DOUBLE*/ {op_n_xx, op_e_xx, op_e_xx, ne_b_ff, ne_b_fi, ne_b_xs},
    /*INT*/    {op_n_xx, op_e_xx, op_e_xx, ne_b_if, ne_b_ii, ne_b_xs},
    /*STRING*/ {op_n_xx, op_e_xx, op_e_xx, ne_b_sx, ne_b_sx, ne_b_ss},
};

static mv_binary_func_t* gt_dispositions[MT_MAX][MT_MAX] = {
    //         NULL      ERROR    BOOL     DOUBLE   INT      STRING
    /*NULL*/   {op_n_xx, op_e_xx, op_e_xx, op_n_xx, op_n_xx, op_n_xx},
    /*ERROR*/  {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*BOOL*/   {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*DOUBLE*/ {op_n_xx, op_e_xx, op_e_xx, gt_b_ff, gt_b_fi, gt_b_xs},
    /*INT*/    {op_n_xx, op_e_xx, op_e_xx, gt_b_if, gt_b_ii, gt_b_xs},
    /*STRING*/ {op_n_xx, op_e_xx, op_e_xx, gt_b_sx, gt_b_sx, gt_b_ss},
};

static mv_binary_func_t* ge_dispositions[MT_MAX][MT_MAX] = {
    //         NULL      ERROR    BOOL     DOUBLE   INT      STRING
    /*NULL*/   {op_n_xx, op_e_xx, op_e_xx, op_n_xx, op_n_xx, op_n_xx},
    /*ERROR*/  {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*BOOL*/   {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*DOUBLE*/ {op_n_xx, op_e_xx, op_e_xx, ge_b_ff, ge_b_fi, ge_b_xs},
    /*INT*/    {op_n_xx, op_e_xx, op_e_xx, ge_b_if, ge_b_ii, ge_b_xs},
    /*STRING*/ {op_n_xx, op_e_xx, op_e_xx, ge_b_sx, ge_b_sx, ge_b_ss},
};

static mv_binary_func_t* lt_dispositions[MT_MAX][MT_MAX] = {
    //         NULL      ERROR    BOOL     DOUBLE   INT      STRING
    /*NULL*/   {op_n_xx, op_e_xx, op_e_xx, op_n_xx, op_n_xx, op_n_xx},
    /*ERROR*/  {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*BOOL*/   {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*DOUBLE*/ {op_n_xx, op_e_xx, op_e_xx, lt_b_ff, lt_b_fi, lt_b_xs},
    /*INT*/    {op_n_xx, op_e_xx, op_e_xx, lt_b_if, lt_b_ii, lt_b_xs},
    /*STRING*/ {op_n_xx, op_e_xx, op_e_xx, lt_b_sx, lt_b_sx, lt_b_ss},
};

static mv_binary_func_t* le_dispositions[MT_MAX][MT_MAX] = {
    //         NULL      ERROR    BOOL     DOUBLE   INT      STRING
    /*NULL*/   {op_n_xx, op_e_xx, op_e_xx, op_n_xx, op_n_xx, op_n_xx},
    /*ERROR*/  {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*BOOL*/   {op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx, op_e_xx},
    /*DOUBLE*/ {op_n_xx, op_e_xx, op_e_xx, le_b_ff, le_b_fi, le_b_xs},
    /*INT*/    {op_n_xx, op_e_xx, op_e_xx, le_b_if, le_b_ii, le_b_xs},
    /*STRING*/ {op_n_xx, op_e_xx, op_e_xx, le_b_sx, le_b_sx, le_b_ss},
};

mv_t eq_op_func(mv_t* pval1, mv_t* pval2) { return (eq_dispositions[pval1->type][pval2->type])(pval1, pval2); }
mv_t ne_op_func(mv_t* pval1, mv_t* pval2) { return (ne_dispositions[pval1->type][pval2->type])(pval1, pval2); }
mv_t gt_op_func(mv_t* pval1, mv_t* pval2) { return (gt_dispositions[pval1->type][pval2->type])(pval1, pval2); }
mv_t ge_op_func(mv_t* pval1, mv_t* pval2) { return (ge_dispositions[pval1->type][pval2->type])(pval1, pval2); }
mv_t lt_op_func(mv_t* pval1, mv_t* pval2) { return (lt_dispositions[pval1->type][pval2->type])(pval1, pval2); }
mv_t le_op_func(mv_t* pval1, mv_t* pval2) { return (le_dispositions[pval1->type][pval2->type])(pval1, pval2); }
Example #22
0
 void cancelLoop() {
     if (event_base_loopexit(m_ebase, NULL)) {
         ERROR_OUT("Error shutting down the server\n");
     }
 }
Example #23
0
//******************************************************************************************
void writebuffer_t::flushWriteBuffer(){
  if(m_use_write_buffer){
     #ifdef DEBUG_WRITE_BUFFER
         DEBUG_OUT("\n***WriteBuffer: flushWriteBuffer BEGIN, contents:\n");
         print();
         DEBUG_OUT("\n");
     #endif

         if(m_buffer_size > 0){
           mf_ruby_api_t *ruby_api = system_t::inst->m_ruby_api;
           // issue a miss to ruby
           if ( ruby_api == NULL || ruby_api->makeRequest == NULL ) {
             ERROR_OUT("error: ruby api is called but ruby is not installed.\n");
             SYSTEM_EXIT;
           }
           
           //issue as many writes as Ruby allows...there are 2 cases why Ruby is not ready:
           //      1) There is an outstanding miss to the same addr - either from WB or MSHR
           //      2) Ruby has too many outstanding requests
           
           ruby_request_t *next_ruby_request = static_cast<ruby_request_t*>(m_request_pool->walkList(NULL));
           while (next_ruby_request != NULL) {
             // if ruby does not accept requests, immediately return (since we issue writes from the buffer in 
             //    FIFO order)
             //  Note: Opal currently executes Stores OOO - which violates TSO!
             //Only issue requests that are already non-outstanding to Ruby:
             if(!next_ruby_request->m_is_outstanding){
               if ((*ruby_api->isReady)( m_id, next_ruby_request->m_logical_address, next_ruby_request->getAddress(), next_ruby_request->m_request_type, next_ruby_request->m_thread)) {
                 
                 //ORDER IS IMPORTANT - we MUST update m_oustanding_stores before makeRequest() bc we could
                 //   have a fastpath HIT, which calls complete() to decrement m_outstanding_stores
                 m_outstanding_stores++;
                 //mark this store as being serviced by Ruby
                 next_ruby_request->m_is_outstanding = true;

                 /* WATTCH power */
                 if(WATTCH_POWER && !(gab_flag & GAB_NO_WATTCH)){
                   system_t::inst->m_seq[m_id]->getPowerStats()->incrementDCacheAccess();
                 }

                 (*ruby_api->makeRequest)( m_id, next_ruby_request->m_logical_address, next_ruby_request->getAddress(), m_block_size,
                                           next_ruby_request->m_request_type, next_ruby_request->m_vpc, next_ruby_request->m_priv, next_ruby_request->m_thread);
               
                 
#ifdef DEBUG_WRITE_BUFFER
                 DEBUG_OUT("\tissuing request 0x%x to Ruby...total outstanding = %d\n",next_ruby_request->getAddress(), m_outstanding_stores);
#endif
              
               }
               else{
                 // Ruby is not ready, so we immediately return
#ifdef DEBUG_WRITE_BUFFER
                 DEBUG_OUT("\tRuby is NOT READY for request 0x%x\n", next_ruby_request->getAddress());
#endif
                 break;
               }
             }  //end !m_is_outstanding
             // get next write buffer entry
             next_ruby_request = static_cast<ruby_request_t*>(m_request_pool->walkList( next_ruby_request ));
           }
         }  // end buffer_size > 0

     #ifdef DEBUG_WRITE_BUFFER
         DEBUG_OUT("***WriteBuffer: flushWriteBuffer END, contents:\n");
         print();
         DEBUG_OUT("\n");
   #endif
  } // end if(m_use_write_buffer)
}
Example #24
0
//****************************************************************************************
void writebuffer_t::complete(pa_t physical_address, bool abortRequest, OpalMemop_t type, int thread ){
  if(m_use_write_buffer){

         #ifdef DEBUG_WRITE_BUFFER
           DEBUG_OUT("\n***WriteBuffer: complete BEGIN, contents:\n");
           print();
           DEBUG_OUT("\n");
         #endif
    bool        found = false;
    pa_t        lineaddr = physical_address & m_block_mask;

    //Note fastpath hits are handled like regular requests - they must remove the WB entry!
    if ( lineaddr != physical_address ) {
      ERROR_OUT("error: writebuffer: ruby returns pa 0x%0llx which is not a cache line: 0x%0llx\n", physical_address, lineaddr );
    }
    
    // search the linked list for the address
    ruby_request_t *miss = static_cast<ruby_request_t*>(m_request_pool->walkList(NULL));
    while (miss != NULL) {
      // check that request types match as well as thread ID
      if ( miss->match( lineaddr ) && (type == miss->m_request_type) && (thread == miss->m_thread)) {
        found = true;
        break;
      }
      miss = static_cast<ruby_request_t*>(m_request_pool->walkList( miss ));
    }
    
    if (found) {
      // first remove the rubymiss from the linked list
      bool found = m_request_pool->removeElement( miss );
      ASSERT( found == true );
      
      // decrement the number of WB entries
      m_buffer_size--;
      m_outstanding_stores--;
      ASSERT(m_buffer_size >= 0);
      ASSERT(m_outstanding_stores >= 0);

      //if we stalled the front-end, unstall it now (since we now have a free slot in the write buffer):
      if(m_write_buffer_full){
        m_write_buffer_full = false;
        system_t::inst->m_seq[m_id]->WBUnstallFetch();
      }

      //Wakeup all those loads that was waiting for this store to be serviced (put there by checkLoadHit)
      miss->m_wait_list.WakeupChain();
      
#ifdef DEBUG_WRITE_BUFFER
      DEBUG_OUT( "[%d] COMPLETE 0x%0llx 0x%0llx (count:%d)\n",
               m_id, lineaddr, miss->m_physical_address,
               m_buffer_size);
#endif

      //free up our dummy_store waiter 
      delete miss->m_waiter;      
      miss->m_waiter = NULL;
      delete miss;
      miss = NULL;
    } else {
      // if not found, report a warning
      ERROR_OUT("[%d] error: writebuffer: at complete, address 0x%0llx not found.\n", m_id, lineaddr);
      ERROR_OUT("writebuffer:: complete FAILS\n");
      print();
      SIM_HALT;
    }
    
         #ifdef DEBUG_WRITE_BUFFER
         DEBUG_OUT("***WriteBuffer: complete END, contents:\n");
         print();
         DEBUG_OUT("\n");
         #endif
  } // end if(m_use_write_buffer)
}
 bool ClassificationProcessor::recalculateCategoryMembershipScores(const databaseentities::Category& category, ProgressCallbackCaller* callback)
 {
     ClassificationCategory cat;
     
     conn->beginTransaction();
     
     if (callback)
         callback->progress(0.0, "init");
     
     if (category.getCategoryDescription() == NULL)
     {
         ERROR_OUT("category description may not be NULL, aborting.", 10);
         conn->rollbackTransaction();
         return false;
     }
     if (category.getCategoryDescription()->getPositiveTimbreModel().empty())
     {
         ERROR_OUT("category positive timbre model may not be empty, aborting.", 10);
         conn->rollbackTransaction();
         return false;
     }
     
     DEBUG_VAR_OUT(category.getCategoryDescription()->getPositiveTimbreModel()           , 0);
     DEBUG_VAR_OUT(category.getCategoryDescription()->getPositiveChromaModel()           , 0);
     DEBUG_VAR_OUT(category.getCategoryDescription()->getNegativeTimbreModel()           , 0);
     DEBUG_VAR_OUT(category.getCategoryDescription()->getNegativeChromaModel()           , 0);
     DEBUG_VAR_OUT(category.getCategoryDescription()->getPositiveClassifierDescription() , 0);
     DEBUG_VAR_OUT(category.getCategoryDescription()->getNegativeClassifierDescription() , 0);
     
     cat.loadFromJSON(
         category.getCategoryDescription()->getPositiveTimbreModel(),
         category.getCategoryDescription()->getPositiveChromaModel(),
         category.getCategoryDescription()->getNegativeTimbreModel(),
         category.getCategoryDescription()->getNegativeChromaModel(),
         category.getCategoryDescription()->getPositiveClassifierDescription(),
         category.getCategoryDescription()->getNegativeClassifierDescription()
         );
     
     if (callback)
         callback->progress(0.05, "calculating new scores...");
     
     //the next block does:
     //for all recordingIDs do
     //    recalculate song-to-category-score and save it to the database
     std::vector<databaseentities::id_datatype> recordingIDs;
     databaseentities::id_datatype minID=0;
     do
     {
         recordingIDs.clear();
         if (!conn->getRecordingIDs(recordingIDs, minID, 20000))
         {
             conn->rollbackTransaction();
             return false;
         }
         
         int i=0;
         for (std::vector<databaseentities::id_datatype>::iterator it = recordingIDs.begin(); it != recordingIDs.end(); ++it)
         {
             if ((i%50==0) && (callback))
                 callback->progress(0.05 + (0.9 * double(i)/double(recordingIDs.size())), "calculating scores...");
             
             databaseentities::Recording recording;
             recording.setID(*it);
             conn->getRecordingByID(recording, true);
             
             if (recording.getRecordingFeatures() == NULL)
             {
                 if (callback)
                     callback->progress(-1.0, std::string("skipping file \"") + recording.getFilename() + "\": no extracted features found");
                 continue;
             }
             
             if (!conn->updateRecordingToCategoryScore(recording.getID(), category.getID(), cat.classifyRecording(recording)))
             {
                 conn->rollbackTransaction();
                 return false;
             }
             
             i++;
             minID = *it;
         }
         minID++;
     } while (!recordingIDs.empty());
     
     conn->endTransaction();
     
     if (callback)
         callback->progress(1.0, "finished");
     
     return true;
 }
Example #26
0
//**************************************************************************
void iwindow_t::squash( pseq_t* the_pseq, int32 last_good, int32 &num_decoded)
{
  #ifdef DEBUG_IWIN
      DEBUG_OUT("iwindow_t:squash lastgood[%d] num_decoded[%d]\n",last_good,num_decoded);
  #endif
  // window index in the m_window
  uint32      windex;

  // check that last good is between the last_retired && the last_fetched
  if ( !rangeOverlap( m_last_retired, m_last_fetched, last_good ) ) {
    DEBUG_OUT( "squash: warning: last_good = %d. last_fetched = %d. last_retired = %d. [%0llx]\n",
               last_good, m_last_fetched, m_last_retired,
               the_pseq->getLocalCycle() );
  }

    #ifdef DEBUG_IWIN
      DEBUG_OUT("\tafter calling rangeOverlap\n",last_good,num_decoded);
  #endif
  if ( ( iwin_increment(last_good) == m_last_retired ) &&
       m_window[last_good] == NULL ) {   
    DEBUG_OUT( "squash: warning: last_good = %d. last_retired = %d. [%0llx]\n",
               last_good, m_last_retired, the_pseq->getLocalCycle() );
  }

  #ifdef DEBUG_IWIN
      DEBUG_OUT("\tbegin setting stage_squash \n",last_good,num_decoded);
  #endif
  uint32 stage_squash[dynamic_inst_t::MAX_INST_STAGE];
  for (uint32 i = 0; i < dynamic_inst_t::MAX_INST_STAGE; i++) {
    stage_squash[i] = 0;
  }
  windex = m_last_fetched;
  // squash all the fetched instructions (in reverse order)
  while (windex != m_last_decoded) {

    if (m_window[windex]) {
      // FetchSquash double checks this is OK to squash
      stage_squash[m_window[windex]->getStage()]++;
      #ifdef DEBUG_IWIN
          DEBUG_OUT("\tbefore calling FetchSquash\n",last_good,num_decoded);
       #endif
      m_window[windex]->FetchSquash();
        #ifdef DEBUG_IWIN
              DEBUG_OUT("\tafter calling FetchSquash\n",last_good,num_decoded);
       #endif
      delete m_window[windex];
        #ifdef DEBUG_IWIN
             DEBUG_OUT("\tsetting m_window[windex]=NULL\n",last_good,num_decoded);
        #endif
      m_window[windex] = NULL;
    } else {
      ERROR_OUT("error: iwindow: fetchsquash(): index %d is NULL\n", windex);
      SIM_HALT;
    }
    windex = iwin_decrement(windex);
  }

  // we squash instructions in the opposite order they were fetched,
  // the process of squashing restores the decode register map.
  windex = m_last_decoded;
  // squash all the decoded instructions (in reverse order)
  while (windex != (uint32) last_good) {
    
    // squash modifies the decode map to restore the original mapping
    if (m_window[windex]) {
      // if last_good is last_retired, windex may point to NULL entry
      stage_squash[m_window[windex]->getStage()]++;
        #ifdef DEBUG_IWIN
            DEBUG_OUT("\tbefore calling Squash\n",last_good,num_decoded);
        #endif
            assert(m_window[windex] != NULL);
          
      m_window[windex]->Squash();

        #ifdef DEBUG_IWIN
            DEBUG_OUT("\tafter calling Squash\n",last_good,num_decoded);
       #endif
      delete m_window[windex];
        #ifdef DEBUG_IWIN
           DEBUG_OUT("\tsetting m_window[windex]=NULL\n",last_good,num_decoded);
         #endif
      m_window[windex] = NULL;
    } else {
      ERROR_OUT("error: iwindow: squash(): index %d is NULL\n", windex);
      SIM_HALT;
    }
    windex = iwin_decrement(windex);
  }
  
  // assess stage-based statistics on what was squashed
  for (uint32 i = 0; i < dynamic_inst_t::MAX_INST_STAGE; i++) {
    if (stage_squash[i] >= (uint32) IWINDOW_ROB_SIZE) {
      ERROR_OUT("lots of instructions (%d) squashed from stage: %s\n",
                stage_squash[i],
                dynamic_inst_t::printStage( (dynamic_inst_t::stage_t) i ));
      stage_squash[i] = IWINDOW_ROB_SIZE - 1;
    }
    STAT_INC( the_pseq->m_hist_squash_stage[i][stage_squash[i]] );
  }
  
  // look back through the in-flight instructions,
  // restoring the most recent "good" branch predictors state
  windex = last_good;
  while (windex != m_last_retired) {
    if (m_window[windex] == NULL) {
      ERROR_OUT("error: iwindow: inflight: index %d is NULL\n", windex);
      SIM_HALT;
    } else {
      if (m_window[windex]->getStaticInst()->getType() == DYN_CONTROL) {
        predictor_state_t good_spec_state = (static_cast<control_inst_t*> (m_window[windex]))->getPredictorState();
         #ifdef DEBUG_IWIN
               DEBUG_OUT("\tbefore calling setSpecBPS\n",last_good,num_decoded);
         #endif
               the_pseq->setSpecBPS(good_spec_state);  
          #ifdef DEBUG_IWIN
               DEBUG_OUT("\tafter calling setSpecBPS\n",last_good,num_decoded);
           #endif
        break;
      }
    }
    windex = iwin_decrement(windex);
  }
  if (windex == m_last_retired) {
    /* no inflight branch, restore from retired "architectural" state */
    #ifdef DEBUG_IWIN
      DEBUG_OUT("\tbefore calling setSpecBPS (2)\n",last_good,num_decoded);
    #endif
    the_pseq->setSpecBPS(*(the_pseq->getArchBPS()) );
    #ifdef DEBUG_IWIN
      DEBUG_OUT("\tafter calling setSpecBPS (2)\n",last_good,num_decoded);
    #endif
  }

  m_last_fetched   = last_good;
  m_last_decoded   = last_good;

  // if we squash in execute, we can flush the decode pipeline, with no trouble
  // check if logically (m_last_scheduled > last_good)
 #ifdef DEBUG_IWIN
      DEBUG_OUT("\tbefore rangeOverlap\n",last_good,num_decoded);
  #endif
  if ( rangeOverlap( m_last_retired, m_last_scheduled, last_good ) ) {

    m_last_scheduled = last_good;
    num_decoded = 0;
    ASSERT( rangeSubtract( m_last_decoded, m_last_scheduled ) <= 0 );

  } else {

   #ifdef DEBUG_IWIN
      DEBUG_OUT("\tbefore calling rangeSubtract\n",last_good,num_decoded);
  #endif
    // else, last_good instruction is in decode ... so we need to pass
    // the number of currently decoded instructions back...
    num_decoded = (uint32) rangeSubtract( m_last_decoded, m_last_scheduled );
   #ifdef DEBUG_IWIN
      DEBUG_OUT("\tafter calling rangeSubtract\n",last_good,num_decoded);
  #endif
    
  }

  if (num_decoded > 8) {
    SIM_HALT;
  }
    #ifdef DEBUG_IWIN
      DEBUG_OUT("iwindow_t::squash END\n",last_good,num_decoded);
  #endif
}
//-------------------------------------------------------------------------------
// @ ::InvertMatrix()
//-------------------------------------------------------------------------------
// Invert matrix using Gaussian elimination
//-------------------------------------------------------------------------------
bool
InvertMatrix( float* A, unsigned int n )
{
    unsigned int* swap;       // which row have we swapped with the current one?
    swap = new unsigned int[n];

    // do one pass for each diagonal element
    for ( unsigned int pivot = 0; pivot < n; ++pivot )
    {
        unsigned int row, col;  // counters

        // find the largest magnitude element in the current column
        unsigned int maxrow = pivot;
        float maxelem = IvAbs( A[ maxrow + n*pivot ] );
        for ( row = pivot+1; row < n; ++row )
        {
            float elem = IvAbs( A[ row + n*pivot ] );
            if ( elem > maxelem )
            {
                maxelem = elem;
                maxrow = row;
            }
        }

        // if max is zero, stop!
        if ( IvIsZero( maxelem ) )
        {
            ERROR_OUT( "::Inverse() -- singular matrix\n" );
            delete [] swap;
            return false;
        }

        // if not in the current row, swap rows
        swap[pivot] = maxrow;
        if ( maxrow != pivot )
        {
            // swap the row
            for ( col = 0; col < n; ++col )
            {
                float temp = A[ maxrow + n*col ];
                A[ maxrow + n*col ] = A[ pivot + n*col ];
                A[ pivot + n*col ] = temp;
            }
        }
       
        // multiply current row by 1/pivot to "set" pivot to 1
        float pivotRecip = 1.0f/A[ n*pivot + pivot ];
        for ( col = 0; col < n; ++col )
        {
            A[ pivot + n*col ] *= pivotRecip;
        }

        // copy 1/pivot to pivot point (doing inverse in place)
        A[pivot + n*pivot] = pivotRecip;

        // now zero out pivot column in other rows 
        for ( row = 0; row < n; ++row )
        {
            // don't subtract from pivot row
            if ( row == pivot )
                continue;
               
            // subtract multiple of pivot row from current row,
            // such that pivot column element becomes 0
            float factor = A[ row + n*pivot ];

            // clear pivot column element (doing inverse in place)
            // will end up setting this element to -factor*pivotInverse
            A[ row + n*pivot ] = 0.0f;
            
            // subtract multiple of row
            for ( col = 0; col < n; ++col )
            {
                A[ row + n*col ] -= factor*A[ pivot + n*col ];   
            }
        }
    }

    // done, undo swaps in column direction, in reverse order
    unsigned int p = n;
    do
    {
        --p;
        // if row has been swapped
        if (swap[p] != p)
        {
            // swap the corresponding column
            for ( unsigned int row = 0; row < n; ++row )
            {
                float temp = A[ row + n*swap[p] ];
                A[ row + n*swap[p] ] = A[ row + n*p ];
                A[ row + n*p ] = temp;
            }
        }
    }
    while (p > 0);

    delete [] swap;

    return true;

}   // End of IvMatrix33::Inverse()
//-------------------------------------------------------------------------------
// @ ::Solve()
//-------------------------------------------------------------------------------
// Perform Gaussian elimination to solve linear system
// Will destroy original values of A and b
// Result is returned in b
//-------------------------------------------------------------------------------
bool 
Solve( float* b, float* A, unsigned int n )
{
    // do one pass for each diagonal element
    for ( unsigned int pivot = 0; pivot < n; ++pivot )
    {
        unsigned int row, col;  // counters

        // find the largest magnitude element in the current column
        unsigned int maxrow = pivot;
        float maxelem = ::IvAbs( A[ maxrow + n*pivot ] );
        for ( row = pivot+1; row < n; ++row )
        {
            float elem = ::IvAbs( A[ row + n*pivot ] );
            if ( elem > maxelem )
            {
                maxelem = elem;
                maxrow = row;
            }
        }

        // if max is zero, stop!
        if ( IvIsZero( maxelem ) )
        {
            ERROR_OUT( "::Solve() -- singular matrix\n" );
            return false;
        }

        // if not in the current row, swap rows
        if ( maxrow != pivot )
        {
            float temp;
            // swap the row
            for ( col = 0; col < n; ++col )
            {
                temp = A[ maxrow + n*col ];
                A[ maxrow + n*col ] = A[ pivot + n*col ];
                A[ pivot + n*col ] = temp;
            }
            // swap elements in solution vector
            temp = b[ maxrow ];
            b[ maxrow ] = b[ pivot ];
            b[ pivot ] = temp;
        }
       
        // multiply current row by 1/pivot to "set" pivot to 1
        float pivotRecip = 1.0f/A[ n*pivot + pivot ];
        for ( col = 0; col < n; ++col )
        {
            A[ pivot + n*col ] *= pivotRecip;
        }
        b[ pivot ] *= pivotRecip;

        // Set pivot to exactly 1, to be sure
        A[pivot + n*pivot] = 1.0f;

        // now zero out pivot column in other rows 
        for ( row = pivot+1; row < n; ++row )
        {
            // subtract multiple of pivot row from current row,
            // such that pivot column element becomes 0
            float factor = A[ row + n*pivot ];

            // subtract multiple of row
            for ( col = 0; col < n; ++col )
            {
                A[ row + n*col ] -= factor*A[ pivot + n*col ];   
            }
            b[ row ] -= factor*b[ pivot ];
        }
    }

    // done, do backwards substitution 
    unsigned int p = n-1;
    do
    {
        --p;
        // subtract multiples of other known entities
        for ( unsigned int col = p+1; col < n; ++col )
        {
            b[p] -= A[ p + n*col ]*b[col];
        }
    }
    while (p > 0); 

    return true;
}
Example #29
0
//**************************************************************************
void
control_inst_t::Retire( abstract_pc_t *a )
{
  #ifdef DEBUG_DYNAMIC_RET
  DEBUG_OUT("control_inst_t:Retire BEGIN, proc[%d]\n",m_proc);
  #endif

  #ifdef DEBUG_DYNAMIC
  char buf[128];
  s->printDisassemble(buf);
  DEBUG_OUT("\tcontrol_inst_t::Retire BEGIN %s seq_num[ %lld ] cycle[ %lld ] fetchPC[ 0x%llx ] fetchNPC[ 0x%llx ] PredictedPC[ 0x%llx ] PredictedNPC[ 0x%llx ]\n", buf, seq_num, m_pseq->getLocalCycle(), m_actual.pc, m_actual.npc, m_predicted.pc, m_predicted.npc);
     for(int i=0; i < SI_MAX_DEST; ++i){
       reg_id_t & dest = getDestReg(i);
       reg_id_t & tofree = getToFreeReg(i);
       if( !dest.isZero() ){
         DEBUG_OUT("\tDest[ %d ] Vanilla[ %d ] Physical[ %d ] Arf[ %s ] ToFree: Vanilla[ %d ] physical[ %d ] Arf[ %s ]\n", i, dest.getVanilla(), dest.getPhysical(), dest.rid_type_menomic( dest.getRtype() ), tofree.getVanilla(), tofree.getPhysical(), tofree.rid_type_menomic( tofree.getRtype() ) );
       }
     }
  #endif

  ASSERT( !getEvent( EVENT_FINALIZED ) );
  STAT_INC( m_pseq->m_stat_control_retired[m_proc] );
  
  // Need this bc we place fetch barrier on retry instead of stxa:
  if ( (s->getOpcode() == i_retry) || (s->getFlag( SI_FETCH_BARRIER)) ) {
    // if we have a branch misprediction, we already unstalled the fetch in partialSquash():
    if(getEvent(EVENT_BRANCH_MISPREDICT) == false){
      m_pseq->unstallFetch(m_proc);   
    }
  }

  STAT_INC( m_pseq->m_branch_seen_stat[s->getBranchType()][2] );
  STAT_INC( m_pseq->m_branch_seen_stat[s->getBranchType()][m_priv? 1:0] );

  // record when execution takes place
  m_event_times[EVENT_TIME_RETIRE] = m_pseq->getLocalCycle() - m_fetch_cycle;
  
  // update dynamic branch prediction (predicated) instruction statistics
  static_inst_t *s_instr = getStaticInst();
  if (s_instr->getType() == DYN_CONTROL) {
    uint32 inst;
    int    op2;
    int    pred;
    switch (s_instr->getBranchType()) {
    case BRANCH_COND:
      // conditional branch
      STAT_INC( m_pseq->m_nonpred_retire_count_stat[m_proc] );
      break;
      
    case BRANCH_PCOND:
      // predictated conditional
      inst = s_instr->getInst();
      op2  = maskBits32( inst, 22, 24 );
      pred = maskBits32( inst, 19, 19 );
      if ( op2 == 3 ) {
        // integer register w/ predication
        STAT_INC( m_pseq->m_pred_reg_retire_count_stat[m_proc] );
        if (pred) {
          STAT_INC( m_pseq->m_pred_reg_retire_taken_stat[m_proc] );
        } else {
          STAT_INC( m_pseq->m_pred_reg_retire_nottaken_stat[m_proc] );
        }
      } else {
        STAT_INC( m_pseq->m_pred_retire_count_stat[m_proc] );
        if (pred) {
          STAT_INC( m_pseq->m_pred_retire_count_taken_stat[m_proc] );
        } else {
          STAT_INC( m_pseq->m_pred_retire_count_nottaken_stat[m_proc] );
        }
      }
      if (pred == true && m_isTaken == false ||
          pred == false && m_isTaken == true) {
        STAT_INC( m_pseq->m_branch_wrong_static_stat );
      }
      break;
      
    default:
      ;      // ignore non-predictated branches
    }
  }

#ifdef DEBUG_RETIRE
  m_pseq->out_info("## Control Retire Stage\n");
  printDetail();
  m_pseq->printPC( &m_actual );
#endif


  bool mispredict = (m_events & EVENT_BRANCH_MISPREDICT);
  if (mispredict) {

    // incorrect branch prediction
    STAT_INC( m_pseq->m_branch_wrong_stat[s->getBranchType()][2] );
    STAT_INC( m_pseq->m_branch_wrong_stat[s->getBranchType()][m_priv? 1:0] );

    //train BRANCH_PRIV predictor
    if( (s->getBranchType() == BRANCH_PRIV) ){
      if (m_predicted.cwp != m_actual.cwp) {
        m_pseq->getRegstatePred()->update(getVPC(), CONTROL_CWP, m_actual.cwp, m_predicted.cwp);
      }
      if (m_predicted.tl != m_actual.tl) {
        m_pseq->getRegstatePred()->update(getVPC(), CONTROL_TL, m_actual.tl, m_predicted.tl);
      }
      if (m_predicted.pstate != m_actual.pstate) {
        m_pseq->getRegstatePred()->update(getVPC(), CONTROL_PSTATE, m_actual.pstate, m_predicted.pstate);
      }
    }

    //****************************** print out mispredicted inst *****************
    if(s->getBranchType() == BRANCH_PRIV){
      char buf[128];
      s->printDisassemble( buf );
      bool imm = s->getFlag(SI_ISIMMEDIATE); 
      #if 0
        if(m_predicted.pc != m_actual.pc){
          m_pseq->out_info("CONTROLOP: PC mispredict: predicted[ 0x%llx ] actual[ 0x%llx ] type=%s seqnum[ %lld ]  VPC[ 0x%llx ] PC[ 0x%llx ] fetched[ %lld ] executed[ %lld ] correctPC[ 0x%llx ] imm[ %d ] %s\n",
                           m_predicted.pc, m_actual.pc, pstate_t::branch_type_menomic[s->getBranchType()], seq_num, getVPC(), getPC(), m_fetch_cycle, m_event_times[EVENT_TIME_EXECUTE] + m_fetch_cycle, m_actual.pc, imm, buf);
        }
      #endif
      #if 0
        if(m_predicted.npc != m_actual.npc){
          m_pseq->out_info("CONTROLOP: NPC mispredict: predicted[ 0x%llx ] actual[ 0x%llx ] type=%s seqnum[ %lld ]  VPC[ 0x%llx ] PC[ 0x%llx ] fetched[ %lld ] executed[ %lld ] correctPC[ 0x%llx ] imm[ %d ] %s\n",
                           m_predicted.npc, m_actual.npc, pstate_t::branch_type_menomic[s->getBranchType()], seq_num, getVPC(), getPC(), m_fetch_cycle, m_event_times[EVENT_TIME_EXECUTE] + m_fetch_cycle, m_actual.pc, imm, buf);
        }
      #endif
      #if 0
        if (m_predicted.cwp != m_actual.cwp) {
          m_pseq->out_info("CONTROLOP: CWP mispredict: predicted[ %d ] actual[ %d ] type=%s seqnum[ %lld ]  VPC[ 0x%llx ] PC[ 0x%llx ] fetched[ %lld ] executed[ %lld ] correctPC[ 0x%llx ] imm[ %d ] %s\n",
                           m_predicted.cwp, m_actual.cwp, pstate_t::branch_type_menomic[s->getBranchType()], seq_num, getVPC(), getPC(), m_fetch_cycle, m_event_times[EVENT_TIME_EXECUTE] + m_fetch_cycle, m_actual.pc, imm, buf);
        }
      #endif
      #if 0
        if (m_predicted.tl != m_actual.tl) {
          m_pseq->out_info("CONTROLOP: TL mispredict: predicted[ %d ] actual[ %d ] type=%s seqnum[ %lld ] VPC[ 0x%llx ] PC[ 0x%llx ] fetched[ %lld ] executed[ %lld ] correctPC[ 0x%llx ] imm[ %d ] %s\n",
                           m_predicted.tl, m_actual.tl, pstate_t::branch_type_menomic[s->getBranchType()], seq_num, getVPC(), getPC(), m_fetch_cycle, m_event_times[EVENT_TIME_EXECUTE] + m_fetch_cycle, m_actual.pc, imm, buf);
        }
      #endif
      #if 0
        if (m_predicted.pstate != m_actual.pstate) {
          m_pseq->out_info("CONTROLOP: PSTATE mispredict: predicted[ 0x%0x ] actual[ 0x%0x ] type=%s seqnum[ %lld ] VPC[ 0x%llx ] PC[ 0x%llx ] fetched[ %lld ] executed[ %lld ] correctPC[ 0x%llx ] imm[ %d ] %s\n",
                           m_predicted.pstate, m_actual.pstate, pstate_t::branch_type_menomic[s->getBranchType()], seq_num, getVPC(), getPC(), m_fetch_cycle,  m_event_times[EVENT_TIME_EXECUTE] + m_fetch_cycle, m_actual.pc, imm, buf);
        }
      #endif
    }
    //**************************************************************************

    // train ras's exception table
    if (ras_t::EXCEPTION_TABLE && s->getBranchType() == BRANCH_RETURN) {
      my_addr_t tos;
      ras_t *ras = m_pseq->getRAS(m_proc);    
      ras->getTop(&(m_pred_state.ras_state), &tos);
      if(tos == m_actual.npc) {
        ras->markException(m_predicted.npc);
        // update RAS state
        ras->pop(&(m_pred_state.ras_state));
        m_pseq->setSpecBPS(m_pred_state);
        if (ras_t::DEBUG_RAS) m_pseq->out_info("*********** DEBUG_RAS ***********\n");
      } else {
        ras->unmarkException(m_actual.npc);
      }
    }

    // XU DEBUG
    if (0 && s->getBranchType() == BRANCH_RETURN) {
      m_pseq->out_info("**** %c:mispred 0x%llx, pred 0x%llx target 0x%llx, "
                       "next %d TOS %d\n", m_priv? 'K':'U', getVPC(),
                       m_predicted.npc, m_actual.npc,
                       m_pred_state.ras_state.next_free,
                       m_pred_state.ras_state.TOS);

      // print 5 instr after mis-pred
      generic_address_t addr = m_predicted.npc-8;
      for(uint32 i = 0; i < 5; i++, addr+=4) {
        //get the actual seq number for the pointer to m_state:
        int32 seq_num = m_pseq->getID() / CONFIG_LOGICAL_PER_PHY_PROC;
        assert(seq_num >= 0 && seq_num < system_t::inst->m_numSMTProcs);
             
        tuple_int_string_t *disassemble = SIM_disassemble((processor_t *) system_t::inst->m_state[seq_num]->getSimicsProcessor(m_proc), addr, /* logical */ 1);
        if (disassemble) m_pseq->out_info("     %s\n", disassemble->string);
      }
    }
  } else {
    // correct or no prediction
    STAT_INC( m_pseq->m_branch_right_stat[s->getBranchType()][2] );
    STAT_INC( m_pseq->m_branch_right_stat[s->getBranchType()][m_priv? 1:0] );
  }

  /* update branch predictor tables at retirement */
  if (s->getBranchType() == BRANCH_COND ||
      s->getBranchType() == BRANCH_PCOND) {
    m_pseq->getDirectBP()->Update(getVPC(),
                                  (m_pseq->getArchBPS()->cond_state),
                                  s->getFlag( SI_STATICPRED ),
                                  m_isTaken, m_proc);

  } else if (s->getBranchType() == BRANCH_INDIRECT ||
             (s->getBranchType() == BRANCH_CALL && s->getOpcode() != i_call) ) {
    // m_actual.npc is the indirect target
    m_pseq->getIndirectBP()->Update( getVPC(),
                                     &(m_pseq->getArchBPS()->indirect_state),
                                     m_actual.npc, m_proc );
  }

  m_pseq->setArchBPS(m_pred_state);
  
  // no need to update call&return, since we used checkpointed RAS
  // no update on traps right now
  SetStage(RETIRE_STAGE);

  /* retire any register overwritten by link register */
  retireRegisters(); 

  #if 0
  if(m_actual.pc == (my_addr_t) -1){
    char buf[128];
    s->printDisassemble(buf);
    ERROR_OUT("\tcontrol_inst_t::Retire %s seq_num[ %lld ] cycle[ %lld ] fetchPC[ 0x%llx ] fetchNPC[ 0x%llx ] fetched[ %lld ] executed[ %lld ]\n", buf, seq_num, m_pseq->getLocalCycle(), m_actual.pc, m_actual.npc, m_fetch_cycle, m_fetch_cycle+getEventTime(EVENT_TIME_EXECUTE_DONE));
    //print out writer cycle
    for(int i=0; i < SI_MAX_SOURCE; ++i){
      reg_id_t & source = getSourceReg(i);
      if(!source.isZero()){
        uint64 written_cycle = source.getARF()->getWrittenCycle( source, m_proc );
        uint64 writer_seqnum = source.getARF()->getWriterSeqnum( source, m_proc );
        ERROR_OUT("\tSource[ %d ] Vanilla[ %d ] Physical[ %d ] Arf[ %s ] written_cycle[ %lld ] writer_seqnum[ %lld ]\n", i, source.getVanilla(), source.getPhysical(), source.rid_type_menomic( source.getRtype() ), written_cycle, writer_seqnum);
      }
    }
  }
  #endif

  ASSERT( m_actual.pc != (my_addr_t) -1 );

  /* return pc, npc pair which are the results of execution */
  a->pc  = m_actual.pc;
  a->npc = m_actual.npc;
 
  markEvent( EVENT_FINALIZED );

  #ifdef DEBUG_DYNAMIC_RET
     DEBUG_OUT("control_inst_t:Retire END, proc[%d]\n",m_proc);
  #endif
}