// Divide bounding box B into regular array of triangles.
// Fill in vector of triangles and control points.
//
// Return 0 always (no error).
//
int MeshCreateX(
	vector<triangle>	&tri,
	vector<vertex>		&ctl,
	const vector<Point>	&pts,
	const IBox			&B,
	FILE*				flog )
{
	clock_t	t0 = StartTiming();

	tri.clear();
	ctl.clear();

/* --------------- */
/* Regular spacing */
/* --------------- */

	double	Dx	= GBL.mch.MNL,
			Dy	= GBL.mch.MNL;
	int		Lx	= B.R - B.L,
			Ly	= B.T - B.B,
			Nx,
			Ny;

	if( !Dx || Dx >= Lx ) {
		Nx = 1;
		Dx = Lx;
	}
	else {
		Nx = int(ceil( Lx / Dx ));
		Dx = Lx / Nx;
	}

	if( !Dy || Dy >= Ly ) {
		Ny = 1;
		Dy = Ly;
	}
	else {
		Ny = int(ceil( Ly / Dy ));
		Dy = Ly / Ny;
	}

/* ----------------------------------------- */
/* Reduce tri count while Atri > GBL.mch.MTA */
/* ----------------------------------------- */

	if( GBL.A.z != GBL.B.z ) {

		while( Nx*Ny > 1 && (Lx*Ly) / (Nx*Ny * 2) < GBL.mch.MTA ) {

			if( Nx >= Ny )
				Dx = Lx / --Nx;
			else
				Dy = Ly / --Ny;
		}
	}

/* ----------------------- */
/* Report basic grid specs */
/* ----------------------- */

	fprintf( flog, "Lx Dx Nx: %5d %8.2f %3d\n", Lx, Dx, Nx );
	fprintf( flog, "Ly Dy Ny: %5d %8.2f %3d\n", Ly, Dy, Ny );

/* ---------- */
/* Create ctl */
/* ---------- */

	for( int iy = 0; iy <= Ny; ++iy ) {

		int	y = (iy < Ny ? B.B + int(iy*Dy) : B.T);

		for( int ix = 0; ix <= Nx; ++ix ) {

			int	x = (ix < Nx ? B.L + int(ix*Dx) : B.R);

			ctl.push_back( vertex( x, y ) );
		}
	}

/* ---------- */
/* Create tri */
/* ---------- */

	int	w = Nx + 1;

	for( int iy = 0; iy < Ny; ++iy ) {

		for( int ix = 0; ix < Nx; ++ix ) {

			triangle	t;

			t.v[0] = ix + w * iy;
			t.v[1] = t.v[0] + 1;
			t.v[2] = t.v[0] + w;
			tri.push_back( t );

			t.v[0] = t.v[2];
			t.v[2] = t.v[0] + 1;
			tri.push_back( t );
		}
	}

/* ---------------- */
/* Remove empty tri */
/* ---------------- */

	const double	occ = 0.75;

	int	ntri = tri.size(),
		npnt = pts.size();

// map pts into their triangles

	vector<int>	in( ntri, 0 );

	for( int i = 0; i < npnt; ++i ) {

		vertex	v( int(pts[i].x), int(pts[i].y) );

		for( int j = 0; j < ntri; ++j ) {

			const triangle& T = tri[j];

			if( InTriangle(
				ctl[T.v[0]], ctl[T.v[1]], ctl[T.v[2]], v ) ) {

				++in[j];
				break;
			}
		}
	}

// remove tri with low occupancy

	for( int i = ntri - 1; i >= 0; --i ) {

		const triangle&	T = tri[i];

		if( !in[i] ||
			in[i] <= occ * AreaOfTriangle(
			ctl[T.v[0]], ctl[T.v[1]], ctl[T.v[2]] ) ) {

			tri.erase( tri.begin() + i );
			--ntri;
		}
	}

/* ----------------------- */
/* Remove unreferenced ctl */
/* ----------------------- */

	if( ntri < in.size() ) {

		fprintf( flog,
		"\nOf %ld triangles, %d were above %3d%% occupancy.\n",
		in.size(), ntri, int(occ*100.0) );

		for( int i = ctl.size() - 1; i >= 0; --i ) {

			for( int j = 0; j < ntri; ++j ) {

				const triangle&	T = tri[j];

				if( T.v[0] == i || T.v[1] == i || T.v[2] == i )
					goto next_i;
			}

			// not ref'd

			ctl.erase( ctl.begin() + i );

			for( int j = 0; j < ntri; ++j ) {

				triangle&	T = tri[j];

				if( T.v[0] > i ) --T.v[0];
				if( T.v[1] > i ) --T.v[1];
				if( T.v[2] > i ) --T.v[2];
			}
next_i:;
		}
	}

/* ------------ */
/* Final report */
/* ------------ */

	fprintf( flog,
	"\nSTAT: From %ld pts, got %ld triangles, %ld control points.\n",
	pts.size(), tri.size(), ctl.size() );

	StopTiming( flog, "MeshCreate", t0 );

	return 0;
}
Example #2
0
static bool sGatherMergeConstraints(const ZTuplePropName& iPropName,
	vector<const ZTBSpec::Criterion*>& ioCriteria,
	const ZTupleValue*& oValueEqual,
	const ZTupleValue*& oBestValueLess, const ZTupleValue*& oBestValueLessEqual,
	const ZTupleValue*& oBestValueGreater, const ZTupleValue*& oBestValueGreaterEqual)
	{
	oBestValueLess = nil;
	oBestValueLessEqual = nil;
	oBestValueGreater = nil;
	oBestValueGreaterEqual = nil;
	oValueEqual = nil;

	for (vector<const ZTBSpec::Criterion*>::iterator critIter = ioCriteria.begin();
		critIter != ioCriteria.end();
		/*no increment*/)
		{
		if (0 != (*critIter)->GetComparator().fStrength
			|| !(*critIter)->GetPropName().Equals(iPropName))
			{
			++critIter;
			continue;
			}

		const ZTupleValue* currentValue = &(*critIter)->GetTupleValue();
		switch ((*critIter)->GetComparator().fRel)
			{
			case ZTBSpec::eRel_Equal:
				{
				if (oValueEqual && *oValueEqual != *currentValue)
					{
					// We've got two equals constraints with different values, so nothing
					// can satisfy them both and we return an indication of contradiction.
					return false;
					}
				oValueEqual = currentValue;
				break;
				}
			case ZTBSpec::eRel_Less:
				{
				if (oBestValueLessEqual)
					{
					ZAssert(!oBestValueLess);
					if (*currentValue <= *oBestValueLessEqual)
						{
						oBestValueLessEqual = nil;
						oBestValueLess = currentValue;
						}
					}
				else if (!oBestValueLess || *currentValue < *oBestValueLess)
					{
					oBestValueLess = currentValue;
					}
				break;
				}
			case ZTBSpec::eRel_LessEqual:
				{
				if (oBestValueLess)
					{
					ZAssert(!oBestValueLessEqual);
					if (*currentValue < *oBestValueLess)
						{
						oBestValueLess = nil;
						oBestValueLessEqual = currentValue;
						}
					}
				else if (!oBestValueLessEqual || *currentValue < *oBestValueLessEqual)
					{
					oBestValueLessEqual = currentValue;
					}
				break;
				}
			case ZTBSpec::eRel_Greater:
				{
				if (oBestValueGreaterEqual)
					{
					ZAssert(!oBestValueGreater);
					if (*currentValue >= *oBestValueGreater)
						{
						oBestValueGreaterEqual = nil;
						oBestValueGreater = currentValue;
						}
					}
				else if (!oBestValueGreater || *currentValue > *oBestValueGreater)
					{
					oBestValueGreater = currentValue;
					}
				break;
				}
			case ZTBSpec::eRel_GreaterEqual:
				{
				if (oBestValueGreater)
					{
					ZAssert(!oBestValueGreaterEqual);
					if (*currentValue > *oBestValueGreater)
						{
						oBestValueGreater = nil;
						oBestValueGreaterEqual = currentValue;
						}
					}
				else if (!oBestValueGreaterEqual || *currentValue > *oBestValueGreaterEqual)
					{
					oBestValueGreaterEqual = currentValue;
					}
				break;
				}
			default:
				{
				// It's some other kind of relationship, so move on to the next criteria.
				++critIter;
				continue;
				}
			}
		critIter = ioCriteria.erase(critIter);
		}

	// Now ensure we don't have a contradiction between the equals,
	// less and greater constraints (if any).
	if (oValueEqual)
		{
		if (oBestValueLess)
			{
			ZAssert(!oBestValueLessEqual);
			if (*oBestValueLess <= *oValueEqual)
				return false;
			oBestValueLess = nil;
			}
		else if (oBestValueLessEqual)
			{
			if (*oBestValueLessEqual < *oValueEqual)
				return false;
			oBestValueLessEqual = nil;
			}

		if (oBestValueGreater)
			{
			ZAssert(!oBestValueGreaterEqual);
			if (*oBestValueGreater >= *oValueEqual)
				return false;
			oBestValueGreater = nil;
			}
		else if (oBestValueGreaterEqual)
			{
			if (*oBestValueGreaterEqual > *oValueEqual)
				return false;
			oBestValueGreaterEqual = nil;
			}
		}
	else
		{
		if (oBestValueLess)
			{
			ZAssert(!oBestValueLessEqual);
			if (oBestValueGreater)
				{
				ZAssert(!oBestValueGreaterEqual);
				if (*oBestValueGreater >= *oBestValueLess)
					return false;
				}
			else if (oBestValueGreaterEqual)
				{
				if (*oBestValueGreaterEqual >= *oBestValueLess)
					return false;
				}
			}
		else if (oBestValueLessEqual)
			{
			if (oBestValueGreater)
				{
				ZAssert(!oBestValueGreaterEqual);
				if (*oBestValueLessEqual <= *oBestValueGreater)
					return false;
				}
			else if (oBestValueGreaterEqual)
				{
				if (*oBestValueLessEqual < *oBestValueGreaterEqual)
					return false;
				}
			}

		// Convert a lessEqual/greaterEqual pair into an equals,
		// if the boundary value is the same for both.
		if (oBestValueLessEqual
			&& oBestValueGreaterEqual
			&& *oBestValueLessEqual == *oBestValueGreaterEqual)
			{
			oValueEqual = oBestValueLessEqual;
			oBestValueLessEqual = nil;
			oBestValueGreaterEqual = nil;
			}
		}

	return true;
	}
Example #3
0
void lxunique(vector<T> &v, string who = ""){
    cerr<<who<<" before size = \t"<<v.size()<<"\t";
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());
    cerr<<who<<" after size = \t"<<v.size()<<endl;
}
Example #4
0
void DepSRL::InsertOneArg(const pair<int, int>& pArgPS, 
        const pair<string, double>& pMaxArg, 
        const pair<string, double>& pNextArg,                                    
        vector< pair<int, int> >& vecPairPSBuf, 
        vector< pair<string, double> >& vecPairMaxArgBuf, 
        vector< pair<string, double> >& vecPairNextArgBuf) const
{
    // 2.1. process the collision
    vector<int> vctCol;
    FindCollisionCand(vecPairPSBuf, pArgPS, vctCol);
    if ( !IsInsertNColLabel(vctCol, pMaxArg, vecPairMaxArgBuf, vecPairNextArgBuf, vecPairPSBuf) ) 
    {
        // insert current node
        // vecPairMaxArgBuf.push_back(pMaxArg);
        // vecPairNextArgBuf.push_back(pNextArg);
        // vecPairPSBuf.push_back(pArgPS);

        // process next arg
        return;
    }

    // 2.2. process the same args
    vector<int> vctSame;
    vector<int> vctSameDel;
    FindSameLabelCand(vecPairMaxArgBuf, pMaxArg, vctSame);
    if ( !IsInsertSameLabel(vctSame, pMaxArg, vecPairMaxArgBuf, vecPairNextArgBuf, vecPairPSBuf, vctSameDel) )
    {
        // insert current node
        // vecPairMaxArgBuf.push_back(pMaxArg);
        // vecPairNextArgBuf.push_back(pNextArg);
        // vecPairPSBuf.push_back(pArgPS);

        // process next arg
        return; 
    }

    // 2.3 insert current node
    // remove collisions and same-args
    // BOOST_FOREACH (int id, vctCol) {
    for(int id = 0; id < vctCol.size(); id++) {
        vecPairMaxArgBuf[id].second  = -1;
        vecPairNextArgBuf[id].second = -1;
        vecPairPSBuf[id].second      = -1;
    }
    // BOOST_FOREACH (int id, vctSameDel) {
    for(int id = 0; id < vctSameDel.size(); id++) {
        vecPairMaxArgBuf[id].second  = -1;
        vecPairNextArgBuf[id].second = -1;
        vecPairPSBuf[id].second      = -1;
    }
    vecPairMaxArgBuf.erase(
            remove_if(
                vecPairMaxArgBuf.begin(),
                vecPairMaxArgBuf.end(),
                boost::bind(
                    less<double>(),
                    boost::bind(
                        &pair<string,double>::second,
                        _1
                        ),
                    0
                    )
                ),
            vecPairMaxArgBuf.end()
            );
    vecPairNextArgBuf.erase(
            remove_if(
                vecPairNextArgBuf.begin(),
                vecPairNextArgBuf.end(),
                boost::bind(
                    less<double>(),
                    boost::bind(
                        &pair<string,double>::second,
                        _1
                        ),
                    0
                    )
                ),
            vecPairNextArgBuf.end()
            );
    vecPairPSBuf.erase(
            remove_if(
                vecPairPSBuf.begin(),
                vecPairPSBuf.end(),
                boost::bind(
                    less<int>(),
                    boost::bind(
                        &pair<int,int>::second,
                        _1
                        ),
                    0
                    )
                ),
            vecPairPSBuf.end()
            );
    vecPairMaxArgBuf.push_back(pMaxArg);
    vecPairNextArgBuf.push_back(pNextArg);
    vecPairPSBuf.push_back(pArgPS);
}
int main(int argc, char *argv[])
{
    SDL_Init(SDL_INIT_VIDEO);
    displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
    SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
    SDL_GL_MakeCurrent(displayWindow, context);
#ifdef _WINDOWS
    glewInit();
#endif
    glViewport(0, 0, 640, 360);
    
    SDL_Event event;
    bool done = false;
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    
    program = new ShaderProgram(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
    program->setModelMatrix(modelMatrix);
    program->setProjectionMatrix(projectionMatrix);
    program->setViewMatrix(viewMatrix);
    projectionMatrix.setOrthoProjection(-5.55, 5.55, -3.0f, 3.0f, -1.0f, 1.0f);
    
    Setup(*program);
    Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 4096 );
    Mix_Music *music;
    music = Mix_LoadMUS("War Theme  America the Beautiful.mp3");
    Mix_PlayMusic(music, -1);
    
    
    mapTexture = LoadTexture("RPGpack_sheet.png");
    SheetSprite mapSprite(program, mapTexture, 20, 13, .3);
    unitTexture = LoadTexture("Map_units.png");
    GLuint fire1Texture = LoadTexture("fire.png");
    SheetSprite fire1Sprite(program, fire1Texture, 1, 1, .3);
    GLuint fire2Texture = LoadTexture("fire2.png");
    SheetSprite fire2Sprite(program, fire2Texture, 1, 1, .3);
    SheetSprite unitSprite(program, unitTexture, 26, 10, .3);
    selectionWindow=new Entity(0, 0, NotType, None, mapSprite);
    selectionWindow->index = 15;
    moveWindow=new Entity(0, 0, NotType, None, mapSprite);
    moveWindow->index = 17;
    warWindow=new Entity(0, 0, NotType, None, mapSprite);
    warWindow->index = 16;
    Entity *unitSelected = new Entity(0, 0, NotType, None, mapSprite);
    
    //Add Units
    Entity unit(0, 0, Inf, Red, unitSprite);
    Entity unit2(1, 1, APC, Blue, unitSprite);
    allUnits.push_back(unit);
    allUnits.push_back(unit2);
    int playerTurn = 1;
    while (!done) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
                done = true;
            }
            else if (event.type == SDL_KEYDOWN) {
                //Allow Player to Select Own Units and then 2nd time is movement
                if (keys[SDL_SCANCODE_X]){
                    if ( moveWindowOn == true){
                        if (selectionWindow->checkOccupation(allUnits) && unitSelected->distance(selectionWindow) <= unitSelected->baseMovement) {
                            unitSelected->baseMovement -= unitSelected->distance(selectionWindow);
                            unitSelected->x = selectionWindow->x;
                            unitSelected->y = selectionWindow->y;
                            moveWindowOn = false;
                        }
                    }
                    else {
                        for(int i = 0; i < allUnits.size(); i++) {
                            if (allUnits[i].x == selectionWindow->x && allUnits[i].y == selectionWindow->y && allUnits[i].fraction == playerTurn && allUnits[i].baseMovement > 0) {
                                moveWindowOn = true;
                                unitSelected = &allUnits[i];
                                cout << unitSelected->baseMovement;
                                moveWindow->x = unitSelected->x;
                                moveWindow->y = unitSelected->y;
                            }
                        }
                    }
                }
                //Shadow Box Movement Controls
                if (keys[SDL_SCANCODE_W] && selectionWindow->y > 0) {
                    selectionWindow->y -= 1;
                }
                if (keys[SDL_SCANCODE_S] && selectionWindow->y < level.mapHeight - 1) {
                    selectionWindow->y += 1;
                }
                if (keys[SDL_SCANCODE_D] && selectionWindow->x < level.mapWidth - 1) {
                    selectionWindow->x += 1;
                }
                if (keys[SDL_SCANCODE_A] && selectionWindow->x > 0) {
                    selectionWindow->x -= 1;
                }
                if (keys[SDL_SCANCODE_RETURN]) {
                    cout << "Enter";
                    //Alternate Players
                    playerTurn += 1;
                    if (playerTurn > 2) {
                        playerTurn = 1;
                    }
                    //Recharge all Movement
                    for(int i = 0; i < allUnits.size(); i++) {
                        if (playerTurn == allUnits[i].fraction) {
                            allUnits[i].rechargeMovement();
                        }
                    }
                }
                
                //Enter Attack Mode
                if(keys[SDL_SCANCODE_Z]) {
                    if(warWindowOn == true) {
                        if(unitSelected->distance(selectionWindow) == 1) {
                            for(int i = 0;i<allUnits.size(); i++) {
                                if(allUnits[i].x == selectionWindow->x && allUnits[i].y == selectionWindow->y && allUnits[i].fraction != playerTurn) {
                                    
                                    allUnits[i].playAttackMusic(allUnits[i].unitType);
                                    unitSelected->attack(&allUnits[i]);
                                }
                            }
                            warWindowOn = false;
                        }
                    }
                    else {
                        for(int i = 0; i < allUnits.size(); i++) {
                            if(allUnits[i].x == selectionWindow->x && allUnits[i].y == selectionWindow->y && allUnits[i].fraction == playerTurn) {
                                warWindowOn = true;
                                unitSelected = &allUnits[i];
                                warWindow->x = unitSelected->x;
                                warWindow->y = unitSelected->y;
                            }
                        }
                    }
                }
            }
        }
        for(int i = 0;i<allUnits.size(); i++) {
            if(allUnits[i].baseHealth <= 0) {
                if(death % 4 == 0){
                    allUnits[i].sprite = &fire1Sprite;
                    death++;
                }

                else if(death % 4 == 1){
                    allUnits[i].sprite = &fire2Sprite;
                    death++;
                }
                else{
                    allUnits.erase(allUnits.begin() + i);
                }
            }
        }
        float ticks = (float)SDL_GetTicks()/1000.0f;
        float elapsed = ticks - lastFrameTicks;
        lastFrameTicks = ticks;
        float fixedElapsed = elapsed;
        if(fixedElapsed > FIXED_TIMESTEP * MAX_TIMESTEPS) {
            fixedElapsed = FIXED_TIMESTEP * MAX_TIMESTEPS;
        }
        while (fixedElapsed >= FIXED_TIMESTEP ) {
            fixedElapsed -= FIXED_TIMESTEP;
        }
        //Background color
        glClearColor(0.53f, 0.808f, 0.98f, 0.1f);
        glClear(GL_COLOR_BUFFER_BIT);
        
        UpdateGameLevel(*program);
        RenderGameLevel(*program, ticks);
        
        SDL_GL_SwapWindow(displayWindow);
        
    }
    
    SDL_Quit();
    return 0;
}
Example #6
0
File: E.cpp Project: Fengdalu/ICPC
void normalize(vector <int> & v) {
  sort(v.begin(), v.end());
  v.erase(unique(v.begin(), v.end()), v.end());
}
Example #7
0
inline vector<T> erase(vector<T> table,int ind)
{
	assert(ind<table.size());
	table.erase(table.begin()+ind);
	return table;
}
//! Remove file names specified in filenameList from argv, except for 'exceptFilename'
void
CommandlineProcessing::removeAllFileNamesExcept ( vector<string> & argv, Rose_STL_Container<std::string> filenameList, std::string exceptFilename )
   {
#if 0
     printf ("In CommandlineProcessing::removeAllFileNamesExcept exceptFilename = %s \n",exceptFilename.c_str());
     printf ("In removeAllFileNamesExcept (at top): argv         = \n%s \n",StringUtility::listToString(argv).c_str());
     printf ("In removeAllFileNamesExcept (at top): filenameList = \n%s \n",StringUtility::listToString(filenameList).c_str());
#endif

#if 0 // Liao 11/15/2012. this code is confusing. 
     for (unsigned int i=0; i < argv.size(); i++)
        {
          string argString = argv[i];
#if 0
          printf ("i = %u argString = %s \n",i,argString.c_str());
#endif
          Rose_STL_Container<std::string>::iterator filenameIterator = filenameList.begin();
          while (filenameIterator != filenameList.end())
             {
#if 0
               printf ("filenameIterator = %s \n",filenameIterator->c_str());
#endif
            // DQ (1/17/2009): This is a match with filenameIterator = a.out and argString = a.out.new!
            // I think we only want to do anything about exact matches.
            // if ( argString.substr(0,filenameIterator->size()) == *filenameIterator )
               if ( argString == *filenameIterator )
                  {
#if 0
                    printf ("Found a file name (removeAllFileNamesExcept): %s \n",argString.c_str());
#endif
                    if (*filenameIterator != exceptFilename)
                       {
#if 0
                         printf ("*filenameIterator != exceptFilename so erase end of argv for i = %u \n",i);
#endif
                      // This is not an iterator invalidation error, but it is strange code!
                         argv.erase(argv.begin() + i);
                         --i; // To counteract the i++ in the loop header
#if 0
                         printf ("After erase: i = %u argv = \n%s \n",i,StringUtility::listToString(argv).c_str());
#endif
                       }
                  }

               filenameIterator++;
             }
        }
#endif
    vector<string>::iterator argv_iter = argv.begin();
    while (argv_iter != argv.end())
    {
      string argString = *(argv_iter);
      bool shouldDelete = false; 

      Rose_STL_Container<std::string>::iterator filenameIterator = filenameList.begin();
      while (filenameIterator != filenameList.end())
      {
        // DQ (1/17/2009): This is a match with filenameIterator = a.out and argString = a.out.new!
        // I think we only want to do anything about exact matches.
        // if ( argString.substr(0,filenameIterator->size()) == *filenameIterator )
        if ( argString == *filenameIterator )
        {
          if (*filenameIterator != exceptFilename)
          {
            shouldDelete = true;
            break;
          }
        }
        filenameIterator++;
      } // end while filename iterator

      if (shouldDelete)
      {
        //vector::erase() return a random access iterator pointing to the new location of the element that followed the last element erased by the function call
        //Essentially, it returns an iterator points to next element. 
        argv_iter = argv.erase (argv_iter);
      }
      else
        argv_iter ++;
    } // end while argv_iter

#if 0
     printf ("Leaving removeAllFileNamesExcept (at bottom): argv         = \n%s \n",StringUtility::listToString(argv).c_str());
#endif
   }
Example #9
0
void MemoryCardDriverThreaded_Linux::GetUSBStorageDevices( vector<UsbStorageDevice>& vDevicesOut )
{
    LOG->Trace( "GetUSBStorageDevices" );

    vDevicesOut.clear();

    {
        vector<RString> asDevices;
        RString sBlockDevicePath = "/sys/block/";
        GetFileList( sBlockDevicePath, asDevices );

        for( unsigned i = 0; i < asDevices.size(); ++i )
        {
            const RString &sDevice = asDevices[i];
            if( sDevice == "." || sDevice == ".." )
                continue;

            UsbStorageDevice usbd;

            RString sPath = sBlockDevicePath + sDevice + "/";
            usbd.sSysPath = sPath;

            /* Ignore non-removable devices. */
            RString sBuf;
            if( !ReadFile( sPath + "removable", sBuf ) )
                continue; // already warned
            if( atoi(sBuf) != 1 )
                continue;

            /*
             * The kernel isn't exposing all of /sys atomically, so we end up missing
             * the partition due to it not being shown yet.  It won't show up until the
             * kernel has scanned the partition table, which can take a variable amount
             * of time, sometimes over a second.  Watch for the "queue" sysfs directory,
             * which is created after this, to tell when partition directories are created.
             */
            RageTimer WaitUntil;
            WaitUntil += 5;
            RString sQueueFilePath = usbd.sSysPath + "queue";
            while(1)
            {
                if( WaitUntil.Ago() >= 0 )
                {
                    LOG->Warn( "Timed out waiting for %s", sQueueFilePath.c_str() );
                    break;
                }

                if( access(usbd.sSysPath, F_OK) == -1 )
                {
                    LOG->Warn( "Block directory %s went away while we were waiting for %s",
                               usbd.sSysPath.c_str(), sQueueFilePath.c_str() );
                    break;
                }

                if( access(sQueueFilePath, F_OK) != -1 )
                    break;

                usleep(10000);
            }

            /* Wait for udev to finish handling device node creation */
            ExecuteCommand( "udevadm settle" );

            /* If the first partition device exists, eg. /sys/block/uba/uba1, use it. */
            if( access(usbd.sSysPath + sDevice + "1", F_OK) != -1 )
            {
                LOG->Trace("OK");
                usbd.sDevice = "/dev/" + sDevice + "1";
            }
            else
            {
                LOG->Trace("error %s", strerror(errno));
                usbd.sDevice = "/dev/" + sDevice;
            }

            /*
             * sPath/device should be a symlink to the actual device.  For USB
             * devices, it looks like this:
             *
             * device -> ../../devices/pci0000:00/0000:00:02.1/usb2/2-1/2-1:1.0
             *
             * "2-1" is "bus-port".
             */
            char szLink[256];
            int iRet = readlink( sPath + "device", szLink, sizeof(szLink) );
            if( iRet == -1 )
            {
                LOG->Warn( "readlink(\"%s\"): %s", (sPath + "device").c_str(), strerror(errno) );
            }
            else
            {
                /*
                 * The full path looks like
                 *
                 *   ../../devices/pci0000:00/0000:00:02.1/usb2/2-2/2-2.1/2-2.1:1.0
                 *
                 * In newer kernels, it looks like:
                 *
                 * ../../../3-2.1:1.0
                 *
                 * Each path element refers to a new hop in the chain.
                 *  "usb2" = second USB host
                 *  2-            second USB host,
                 *   -2           port 1 on the host,
                 *     .1         port 1 on an attached hub
                 *       .2       ... port 2 on the next hub ...
                 *
                 * We want the bus number and the port of the last hop.  The level is
                 * the number of hops.
                 */
                szLink[iRet] = 0;
                vector<RString> asBits;
                split( szLink, "/", asBits );

                RString sHostPort = asBits[asBits.size()-1];
                if( !sHostPort.empty() )
                {
                    /* Strip off the endpoint information after the colon. */
                    size_t pos = sHostPort.find(':');
                    if( pos != string::npos )
                        sHostPort.erase( pos );

                    /* sHostPort is eg. 2-2.1. */
                    sHostPort.Replace( "-", "." );
                    asBits.clear();
                    split( sHostPort, ".", asBits );
                    if( asBits.size() > 1 )
                    {
                        usbd.iBus = atoi( asBits[0] );
                        usbd.iPort = atoi( asBits[asBits.size()-1] );
                        usbd.iLevel = asBits.size() - 1;
                    }
                }
            }

            if( ReadFile( sPath + "device/../idVendor", sBuf ) )
                sscanf( sBuf, "%x", &usbd.idVendor );

            if( ReadFile( sPath + "device/../idProduct", sBuf ) )
                sscanf( sBuf, "%x", &usbd.idProduct );

            if( ReadFile( sPath + "device/../serial", sBuf ) )
            {
                usbd.sSerial = sBuf;
                TrimRight( usbd.sSerial );
            }
            if( ReadFile( sPath + "device/../product", sBuf ) )
            {
                usbd.sProduct = sBuf;
                TrimRight( usbd.sProduct );
            }
            if( ReadFile( sPath + "device/../manufacturer", sBuf ) )
            {
                usbd.sVendor = sBuf;
                TrimRight( usbd.sVendor );
            }

            vDevicesOut.push_back( usbd );
        }
    }

    {
        // Find where each device is mounted. Output looks like:

        // /dev/sda1               /mnt/flash1             auto    noauto,owner 0 0
        // /dev/sdb1               /mnt/flash2             auto    noauto,owner 0 0
        // /dev/sdc1               /mnt/flash3             auto    noauto,owner 0 0

        RString fn = "/rootfs/etc/fstab";
        RageFile f;
        if( !f.Open(fn) )
        {
            LOG->Warn( "can't open '%s': %s", fn.c_str(), f.GetError().c_str() );
            return;
        }

        RString sLine;
        while( !f.AtEOF() )
        {
            switch( f.GetLine(sLine) )
            {
            case 0:
                continue; /* eof */
            case -1:
                LOG->Warn( "error reading '%s': %s", fn.c_str(), f.GetError().c_str() );
                return;
            }

            char szScsiDevice[1024];
            char szMountPoint[1024];
            int iRet = sscanf( sLine, "%s %s", szScsiDevice, szMountPoint );
            if( iRet != 2 || szScsiDevice[0] == '#')
                continue;	// don't process this line

            /* Get the real kernel device name, which should match
             * the name from /sys/block, by following symlinks in
             * /dev.  This allows us to specify persistent names in
             * /etc/fstab using things like /dev/device/by-path. */
            char szUnderlyingDevice[PATH_MAX];
            if( realpath(szScsiDevice, szUnderlyingDevice) == NULL )
            {
                // "No such file or directory" is understandable
                if (errno != ENOENT)
                    LOG->Warn( "realpath(\"%s\"): %s", szScsiDevice, strerror(errno) );
                continue;
            }

            RString sMountPoint = szMountPoint;
            TrimLeft( sMountPoint );
            TrimRight( sMountPoint );

            // search for the mountpoint corresponding to the device
            for( unsigned i=0; i<vDevicesOut.size(); i++ )
            {
                UsbStorageDevice& usbd = vDevicesOut[i];
                if( usbd.sDevice == szUnderlyingDevice )	// found our match
                {
                    // Use the device entry from fstab so the mount command works
                    usbd.sDevice = szScsiDevice;
                    usbd.sOsMountDir = sMountPoint;
                    break;	// stop looking for a match
                }
            }
        }
    }

    for( unsigned i=0; i<vDevicesOut.size(); i++ )
    {
        UsbStorageDevice& usbd = vDevicesOut[i];
        LOG->Trace( "    sDevice: %s, iBus: %d, iLevel: %d, iPort: %d, id: %04X:%04X, Vendor: '%s', Product: '%s', sSerial: \"%s\", sOsMountDir: %s",
                    usbd.sDevice.c_str(), usbd.iBus, usbd.iLevel, usbd.iPort, usbd.idVendor, usbd.idProduct, usbd.sVendor.c_str(),
                    usbd.sProduct.c_str(), usbd.sSerial.c_str(), usbd.sOsMountDir.c_str() );
    }

    /* Remove any devices that we couldn't find a mountpoint for. */
    for( unsigned i=0; i<vDevicesOut.size(); i++ )
    {
        UsbStorageDevice& usbd = vDevicesOut[i];
        if( usbd.sOsMountDir.empty() )
        {
            LOG->Trace( "Ignoring %s (couldn't find in /etc/fstab)", usbd.sDevice.c_str() );

            vDevicesOut.erase( vDevicesOut.begin()+i );
            --i;
        }
    }

    LOG->Trace( "Done with GetUSBStorageDevices" );
}
Example #10
0
/*
==================================================================
// This is winmain, the main entry point for Windows applications
==================================================================
*/
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
	// Initialize the window
	if ( !initWindow( hInstance ) )
		return false;
	// called after creating the window
	if ( !d3dMgr->initD3DManager(wndHandle) )
		return false;
	if ( !d3dxSRMgr->initD3DXSpriteMgr(d3dMgr->getTheD3DDevice()))
		return false;

	//===============================================================
	//    FRAME/TIMING
	//===============================================================
	// Grab the frequency of the high def timer
	__int64 freq = 0; 				// measured in counts per second;
	QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
	float sPC = 1.0f / (float)freq;			// number of seconds per count

	__int64 currentTime = 0;				// current time measured in counts per second;
	__int64 previousTime = 0;				// previous time measured in counts per second;

	float numFrames   = 0.0f;				// Used to hold the number of frames
	float timeElapsed = 0.0f;				// cumulative elapsed time

	float fpsRate = 1.0f/25.0f;
	//==============================================================
	// SCREEN
	//==============================================================
	GetClientRect(wndHandle,&clientBounds);

	LPDIRECT3DSURFACE9 theBackbuffer = NULL;  // This will hold the back buffer

	LPDIRECT3DSURFACE9 aSurface = d3dMgr->getD3DSurfaceFromFile("Images\\Back.png");	
	LPDIRECT3DSURFACE9 menuScreen = d3dMgr->getD3DSurfaceFromFile("Images\\MENU_1.png");
	LPDIRECT3DSURFACE9 menuScreen1= d3dMgr->getD3DSurfaceFromFile("Images\\MENU_START.png");
	LPDIRECT3DSURFACE9 menuScreen2= d3dMgr->getD3DSurfaceFromFile("Images\\MENU_SCORES.png"); 
	LPDIRECT3DSURFACE9 menuScreen3= d3dMgr->getD3DSurfaceFromFile("Images\\MENU_QUIT.png");
	LPDIRECT3DSURFACE9 highScoreScreen = d3dMgr->getD3DSurfaceFromFile("Images\\HIGHSCORES.png");
	LPDIRECT3DSURFACE9 newHighScoreScreen = d3dMgr->getD3DSurfaceFromFile("Images\\NEWHIGHSCORE.png");
	LPDIRECT3DSURFACE9 levelComplete = d3dMgr->getD3DSurfaceFromFile("Images\\LEVEL_COMPLETE.png");
	LPDIRECT3DSURFACE9 controls = d3dMgr->getD3DSurfaceFromFile("Images\\CONTROLS.png");
	//==============================================================
	//      PLAYER 
	//==============================================================
	Player1 = new cXboxController(1);   //Crate controller instance for player 1

	SetRect(&titlePos, 330, 300, 500, 400);  //Set position for level title

	D3DXVECTOR3 shipPos = D3DXVECTOR3(100,100,0);   //Ship starting position
	theShip = cPlayer(shipPos,d3dMgr->getTheD3DDevice());  //Create cPlayer instance

	//==================================================stage
	stage1 = cStage();    //Create stage instance
	sprintf_s( gScoreStr, 50, "Score: %d", score);    //Update score display

	//============================================background
	//backPos = D3DXVECTOR3(0,0,0);
	//background1 = cBackground(clientBounds, backPos, d3dMgr->getTheD3DDevice());
	//===================================================font
	cD3DXFont* scoreFont = new cD3DXFont(d3dMgr->getTheD3DDevice(),hInstance, "staravenue"); //Create score font

	SetRect(&textPos, 50, 10, 400, 100); //set position for score display


	MSG msg;
	ZeroMemory( &msg, sizeof( msg ) );


	while( msg.message!=WM_QUIT )
	{

		// Check the message queue
		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) )
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		else
		{

			//=============================TIMING
			QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
			float dt = (currentTime - previousTime)*sPC;

			// Accumulate how much time has passed.
			timeElapsed += dt;
			numFrames++;


			if(timeElapsed > fpsRate && numFrames>1)
			{	
				//=================================================================================
				//      XBOX CONTROLS
				//=================================================================================

				if(Player1->IsConnected())   //Test for controller conection
				{ 
					//===========================
					//          A BUTTON
					//===========================
					if(Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_A)
					{

						//=================GAME PLAY
						if(!menu && !hScore && !newHScore && !lvComp){
							//Counter to limit fire rate
							if (fireCounter == 10)
							{
								//PLAY FIRE SOUND
								menuChange.playSound(L"Sounds\\LASER.wav",false);
								//Add new shot to vector
								theShip.fire(gShots, d3dMgr->getTheD3DDevice());
								fireCounter = 0;
							}
							fireCounter++;
						}
						//==================Main menu
						if(menu)
						{
							//Counter to limit menu scroll
							if(fireCounter == 10){
								//Play menu selection soundfx
								menuChange.playSound(L"Sounds\\menuChoice.wav",false);
								if(menu && menuOpt == 1)
								{
									//Load game scene
									stage1.startLevel();
									menu= false;
								}
								else if(menu && menuOpt == 2)
								{
									//Load highscore scene
									menu = false;
									hScore = true;
								}
								else if(menu && menuOpt == 3)
								{
									//Exit game
									exit(0);
								}
								fireCounter++;
							}
						}
						if(lvComp)
						{
							//Counter to limit menu scroll
							if(fireCounter == 10){
								lvComp = false;
								//Check for new highscore
								if(highScores->checkScore(score))
								{
									//If new highscore load name entry scene
									newHScore=true;
								}

								else{
									//if not load main menu
									menu = true;
								}
							}
							fireCounter++;
						}
						if(newHScore)
						{
							//Limit scroll
							if(fireCounter == 10){
								//Update highscores with entered name and current score
								highScores->UpdateScore(name,score);
								newHScore = false;
								hScore = true;       //Load highscore table
							}
							fireCounter++;
						}
						if(controls)
						{
							//Load main menu
							controls = false;
							menu = true;


						}
						fireCounter++;
					}
					else{
						fireCounter =10;
					}
					//================================
					//  B BUTTON
					//================================
					if(Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_B){
						if(hScore)
						{
							//Load main menu
							hScore = false;
							menu = true;
						}

					}
					//================================
					//  LEFT STICK RIGHT
					//================================
					if(Player1->GetState().Gamepad.sThumbLX>10000)
					{
						if(!menu && !hScore && !newHScore && !lvComp){
							
							//Check screen collision
							if( theShip.getSpritePos2D().x < clientBounds.right - 60){
								theShip.moveRight();  
							}
						}
						//Limit menu scroll
						if(menuCounterRight == MENU_SCROLL)
						{
							if(newHScore)
							{
								//Scroll Letter position for name enter
								if(sName==3)
								{
									sName = 1;
								}
								else
								{
									sName++;
								}
							}
						}
						menuCounterRight++;

					}
					else
					{
						menuCounterRight = MENU_SCROLL;
					}
					//================================
					//  LEFT STICK LEFT
					//================================
					if(Player1->GetState().Gamepad.sThumbLX<-10000)
					{	
						
						if(!menu && !hScore && !newHScore && !lvComp){
							//Check screen collision
							if(theShip.getSpritePos2D().x > clientBounds.left + 60)
							{
								theShip.moveLeft();
							}
						}
						if(menuCounterLeft == MENU_SCROLL)
						{
							if(newHScore)
							{
								//Scroll Letter position for name enter
								if(sName==1)
								{
									sName = 3;
								}
								else
								{
									sName--;
								}
							}
						}
						menuCounterLeft++;

					}
					else{
						menuCounterLeft = MENU_SCROLL;
					}
					//================================
					//  LEFT STICK UP
					//================================
					if(Player1->GetState().Gamepad.sThumbLY>10000)
					{
						
						if(!menu && !hScore && !newHScore && !lvComp)
						{
							//Check screen collision
							if(theShip.getSpritePos2D().y >  clientBounds.top + 60)
							{
								theShip.moveUp();
							}
						}
						if(menu)
						{
							if(menuCounterUp == MENU_SCROLL)
							{
								//Play menu selection sound fx
								menuChange.playSound(L"Sounds\\MenuChange.wav",false);

								//Change menu index
								if(menuOpt==1)
								{
									menuOpt = 3;
								}
								else{
									menuOpt--;
								}
								menuCounterUp =0;
							}
							menuCounterUp++;
						}
						if(newHScore)
						{
							if(menuCounterUp == MENU_SCROLL)
							{
								//Scroll through letters on name entry
								switch(sName)
								{
								case 1:
									if(nameI == 25)
										nameI=0;
									else
										nameI++;
									break;
								case 2:
									if(nameJ == 25)
										nameJ=0;
									else
										nameJ++;
									break;
								case 3:
									if(nameK == 25)
										nameK=0;
									else
										nameK++;
									break;
								}
							}
							menuCounterUp++;
						}
					}
					else
					{
						menuCounterUp = MENU_SCROLL;
					}
					//================================
					//  LEFT STICK DOWN
					//================================
					if(Player1->GetState().Gamepad.sThumbLY<-10000)
					{

						if(!menu && !hScore && !newHScore && !lvComp){
							//Check screen collision
							if(theShip.getSpritePos2D().y <  clientBounds.bottom - 60){
								theShip.moveDown();}
						}
						if(menu)
						{
							if(menuCounterDown == MENU_SCROLL){
								menuChange.playSound(L"Sounds\\MenuChange.wav",false);
								if(menuOpt==3)
								{
									menuOpt = 1;
								}
								else{
									menuOpt++;
								}
								menuCounterDown = 0;
							}
							menuCounterDown++;

						}
						if(newHScore){
							if(menuCounterDown == MENU_SCROLL)
							{
								//Scroll through letters on name entry
								switch(sName){
								case 1:
									if(nameI == 0)
										nameI=25;
									else
										nameI--;
									break;
								case 2:
									if(nameJ == 0)
										nameJ=25;
									else
										nameJ--;
									break;
								case 3:
									if(nameK == 0)
										nameK=25;
									else
										nameK--;
									break;
								}

							}
							menuCounterDown++;
						}
					}
					else{
						menuCounterDown = MENU_SCROLL; 
					}
				}
				//=================================================================================
				//         GAME PLAY
				//=================================================================================
				if(!menu && !hScore && !newHScore && !lvComp &&!controls)
				{
					if(!theShip.isActive())
					{
						//counter to stall level end
						deathCounter++;
					}
					if(deathCounter == 20)
					{
						
						stageMusic.stopSound(); //Stop stage music
						lvComp = true;    //Load level complete scene
					}
					
					//========================================================stage title
					if(titleCounter<100)
					{
						//Counter for timed events
						if(titleCounter==5)
						{
							stageMusic.playSound(L"Sounds\\Moon.wav",false);    //Start stage music
						}
						sprintf_s( gStageTitle, 25, "Stage One");       //Display stage title
						titleCounter++;
					}
					else
					{

						showTitle = false;
						//========================================start stage
						if (stage1.isActive()){
							stage1.Update(eShips, clientBounds, d3dMgr->getTheD3DDevice());         //Run enemy scripting
						}
						else{
							
							//Load level complete scene
							lvComp = true;
						}
					}

					theShip.update();       //Update players movement

					//====================================================Background
					background1.update();
					//	background2.update();

					//========================================================================
					//               COLLISIONS                
					//=======================================================================
					list<cEnemy*>::iterator index;
					vector<cShot*>::iterator iter;
					

					//Loop through enemy ships
					for(index = eShips.begin(); index != eShips.end(); ++index)
					{			
						//Loop through shots
						for(iter = gShots.begin(); iter!=gShots.end(); ++iter)
						{
							//If enemy ship is shot
							if((*iter)->collidedWith((*iter)->getBoundingRect(),(*index)->getBoundingRect()) && (*iter)->getShooter() == 0)
							{

								score++;       //update score
								sprintf_s( gScoreStr, 50, "Score: %d", score);
								(*iter)->setActive(false);      //Remove shot
								(*index)->setActive(false);     //Remover enemy ship
								OutputDebugString("Collision!!");
							}
							//If player is shot
							if((*iter)->collidedWith((*iter)->getBoundingRect(),theShip.getBoundingRect()) && (*iter)->getShooter() == 1)
							{
								//PLAYER DEATH
								(*iter)->setActive(false);   //Remove shot
								theShip.Death();             //Kill player
								OutputDebugString("Death");
							}
							//If shot leaves screen bounds
							if((*iter)->getSpritePos2D().x < clientBounds.left || (*iter)->getSpritePos2D().x > clientBounds.right)
							{
								(*iter)->setActive(false);   //Remove shot
							}
						}
						//If enemy ship leaves screen bounds
						if((*index)->getSpritePos().x < 30
							|| 
							(*index)->getSpritePos().y > clientBounds.bottom+300 || 
							(*index)->getSpritePos().y < clientBounds.top-300)
						{
							(*index)->setActive(false);   //Remove enemy ship
						}
					}


					
					d3dMgr->beginRender();
					theBackbuffer = d3dMgr->getTheBackBuffer();
					d3dMgr->updateTheSurface(aSurface, theBackbuffer);
					d3dMgr->releaseTheBackbuffer(theBackbuffer);

					d3dxSRMgr->beginDraw();

					//	d3dxSRMgr->setTheTransform(background1.getSpriteTransformMatrix());	
					//		d3dxSRMgr->drawSprite(background1.getTexture(),&background1.getRect(),NULL,NULL,0xFFFFFFFF);


					//=====================================================ship
					//If player is alive update and draw
					if(theShip.isActive()){
						d3dxSRMgr->setTheTransform(theShip.getSpriteTransformMatrix());
						d3dxSRMgr->drawSprite(theShip.getTexture(),NULL,NULL,NULL,0xFFFFFFFF);
					}
					//========================================================================Updates


					//Delete inactive shots and enemy ships
					iter = gShots.begin();
					index = eShips.begin();
					while(iter != gShots.end())
					{
						if((*iter)->isActive() == false)
						{
							iter = gShots.erase(iter);
						}
						else
						{
							//If active update and draw
							(*iter)->update();
							d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix());  
							d3dxSRMgr->drawSprite((*iter)->getTexture(),NULL,NULL,NULL,0xFFFFFFFF);
							iter++;
						}
					}
					while(index != eShips.end())
					{
						if((*index)->isActive() == false)
						{
							index = eShips.erase(index);
						}
						else
						{	
							(*index)->update(d3dMgr->getTheD3DDevice(),gShots);
							d3dxSRMgr->setTheTransform((*index)->getSpriteTransformMatrix());
							d3dxSRMgr->drawSprite((*index)->getTexture(),NULL,NULL,NULL,0xFFFFFFFF);
							index++;
						}
					}


					d3dxSRMgr->endDraw();
					scoreFont->printText(gScoreStr,textPos);
					//Display stage title
					if(showTitle)
						scoreFont->printText(gStageTitle,titlePos);
					d3dMgr->endRender();
					OutputDebugString("timeElapsed > fpsRate");
					timeElapsed = 0.0f;
				}
				//================================================================================================
				//                       MAIN MENU
				//================================================================================================
				else if(menu)
				{
					//Display specific screen based on menu index
					switch(menuOpt){
					case 1:
						menuScreen = menuScreen1;
						break;
					case 2:
						menuScreen = menuScreen2;
						break;
					case 3:
						menuScreen = menuScreen3;
						break;
					default:
						menuScreen = menuScreen;
						break;}
					//===============================
					//  RESET FOR NEW GAME
					//===============================
					score = 0;
					sprintf_s( gScoreStr, 50, "Score: %d", score);
					theShip.setSpritePos2D(D3DXVECTOR3(100,100,0));
					showTitle = true;
					titleCounter = 0;
					theShip.Respawn();

					//===============================

					//menuScreen1 = d3dMgr->getD3DSurfaceFromFile("Images\\MENU_1.png");
					d3dMgr->beginRender();
					theBackbuffer = d3dMgr->getTheBackBuffer();
					d3dMgr->updateTheSurface(menuScreen, theBackbuffer);
					d3dMgr->releaseTheBackbuffer(theBackbuffer);
					d3dMgr->endRender();
				}
				//================================================================================================
				//                      HIGH SCORE TABLE
				//================================================================================================
				else if(hScore)
				{
					//Set location for Score display
					RECT scorePos;
					SetRect(&scorePos, 50, 10, 700, 500);
					d3dMgr->beginRender();
					theBackbuffer = d3dMgr->getTheBackBuffer();
					d3dMgr->updateTheSurface(highScoreScreen, theBackbuffer);
					d3dMgr->releaseTheBackbuffer(theBackbuffer);
					highScores->openfile();               //Load highscores from file
					highScores->getHighScores(scoreTable);   //Load into scoreTable for display
					scoreFont->printText(scoreTable,scorePos);  //Display scores
					d3dMgr->endRender();
				}
				//================================================================================================
				//                     NEW HIGH SCORE
				//================================================================================================
				else if(newHScore)
				{

					//Update current name
					highScores->enterName(name, nameI, nameJ, nameK);
					//Set name psoition
					RECT scorePos;
					SetRect(&scorePos, 330, 300, 450, 400);
					d3dMgr->beginRender();
					theBackbuffer = d3dMgr->getTheBackBuffer();
					d3dMgr->updateTheSurface(newHighScoreScreen, theBackbuffer);
					d3dMgr->releaseTheBackbuffer(theBackbuffer);
					//Display current name
					scoreFont->printText(name,scorePos);
					d3dMgr->endRender();
				}
				//================================================================================================
				//                      LEVEL COMPLETE
				//================================================================================================
				else if(lvComp)
				{
					//Update score string
					sprintf_s( gScoreStr, 50, "%d", score);
					RECT scorePos;
					SetRect(&scorePos, 330, 300, 450, 400);
					d3dMgr->beginRender();
					theBackbuffer = d3dMgr->getTheBackBuffer();
					d3dMgr->updateTheSurface(levelComplete, theBackbuffer);
					d3dMgr->releaseTheBackbuffer(theBackbuffer);
					scoreFont->printText(gScoreStr,scorePos);   //Display Score
					d3dMgr->endRender();

				}
				else if(controls){
					d3dMgr->beginRender();
					theBackbuffer = d3dMgr->getTheBackBuffer();
					d3dMgr->updateTheSurface(controls, theBackbuffer);
					d3dMgr->releaseTheBackbuffer(theBackbuffer);
					d3dMgr->endRender();
				}
			}

			//menu
			previousTime = currentTime;
			//==================================
			StringCchPrintf(szTempOutput, 30, TEXT("dt=%f\n"), dt);
			OutputDebugString(szTempOutput);
			StringCchPrintf(szTempOutput, 30, TEXT("timeElapsed=%f\n"), timeElapsed);
			OutputDebugString(szTempOutput);
			StringCchPrintf(szTempOutput, 30, TEXT("previousTime=%u\n"), previousTime);
			OutputDebugString(szTempOutput);
			StringCchPrintf(szTempOutput, 30, TEXT("fpsRate=%f\n"), fpsRate);
			OutputDebugString(szTempOutput);
			//====================================
		}
	}
	d3dxSRMgr->cleanUp();
	d3dMgr->clean();
	return (int) msg.wParam;
}
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
{
    static const CScriptNum bnZero(0);
    static const CScriptNum bnOne(1);
    static const CScriptNum bnFalse(0);
    static const CScriptNum bnTrue(1);
    static const valtype vchFalse(0);
    static const valtype vchZero(0);
    static const valtype vchTrue(1, 1);

    CScript::const_iterator pc = script.begin();
    CScript::const_iterator pend = script.end();
    CScript::const_iterator pbegincodehash = script.begin();
    opcodetype opcode;
    valtype vchPushValue;
    vector<bool> vfExec;
    vector<valtype> altstack;
    set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
    if (script.size() > 10000)
        return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
    int nOpCount = 0;
    bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;

    try
    {
        while (pc < pend)
        {
            bool fExec = !count(vfExec.begin(), vfExec.end(), false);

            //
            // Read instruction
            //
            if (!script.GetOp(pc, opcode, vchPushValue))
                return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
            if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
                return set_error(serror, SCRIPT_ERR_PUSH_SIZE);

            // Note how OP_RESERVED does not count towards the opcode limit.
            if (opcode > OP_16 && ++nOpCount > 201)
                return set_error(serror, SCRIPT_ERR_OP_COUNT);

            if (opcode == OP_CAT ||
                opcode == OP_SUBSTR ||
                opcode == OP_LEFT ||
                opcode == OP_RIGHT ||
                opcode == OP_INVERT ||
                opcode == OP_AND ||
                opcode == OP_OR ||
                opcode == OP_XOR ||
                opcode == OP_2MUL ||
                opcode == OP_2DIV ||
                opcode == OP_MUL ||
                opcode == OP_DIV ||
                opcode == OP_MOD ||
                opcode == OP_LSHIFT ||
                opcode == OP_RSHIFT)
                return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.

            if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
                if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
                    return set_error(serror, SCRIPT_ERR_MINIMALDATA);
                }
                stack.push_back(vchPushValue);
            } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
            switch (opcode)
            {
                //
                // Push value
                //
                case OP_1NEGATE:
                case OP_1:
                case OP_2:
                case OP_3:
                case OP_4:
                case OP_5:
                case OP_6:
                case OP_7:
                case OP_8:
                case OP_9:
                case OP_10:
                case OP_11:
                case OP_12:
                case OP_13:
                case OP_14:
                case OP_15:
                case OP_16:
                {
                    // ( -- value)
                    CScriptNum bn((int)opcode - (int)(OP_1 - 1));
                    stack.push_back(bn.getvch());
                    // The result of these opcodes should always be the minimal way to push the data
                    // they push, so no need for a CheckMinimalPush here.
                }
                break;


                //
                // Control
                //
                case OP_NOP:
                    break;

                case OP_CHECKLOCKTIMEVERIFY:
                {
                    if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
                        // not enabled; treat as a NOP2
                        if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
                            return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
                        }
                        break;
                    }

                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);

                    // Note that elsewhere numeric opcodes are limited to
                    // operands in the range -2**31+1 to 2**31-1, however it is
                    // legal for opcodes to produce results exceeding that
                    // range. This limitation is implemented by CScriptNum's
                    // default 4-byte limit.
                    //
                    // If we kept to that limit we'd have a year 2038 problem,
                    // even though the nLockTime field in transactions
                    // themselves is uint32 which only becomes meaningless
                    // after the year 2106.
                    //
                    // Thus as a special case we tell CScriptNum to accept up
                    // to 5-byte bignums, which are good until 2**39-1, well
                    // beyond the 2**32-1 limit of the nLockTime field itself.
                    const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);

                    // In the rare event that the argument may be < 0 due to
                    // some arithmetic being done first, you can always use
                    // 0 MAX CHECKLOCKTIMEVERIFY.
                    if (nLockTime < 0)
                        return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);

                    // Actually compare the specified lock time with the transaction.
                    if (!checker.CheckLockTime(nLockTime))
                        return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);

                    break;
                }

                case OP_NOP1: case OP_NOP3: case OP_NOP4: case OP_NOP5:
                case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
                {
                    if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
                        return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
                }
                break;

                case OP_IF:
                case OP_NOTIF:
                {
                    // <expression> if [statements] [else [statements]] endif
                    bool fValue = false;
                    if (fExec)
                    {
                        if (stack.size() < 1)
                            return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
                        valtype& vch = stacktop(-1);
                        fValue = CastToBool(vch);
                        if (opcode == OP_NOTIF)
                            fValue = !fValue;
                        popstack(stack);
                    }
                    vfExec.push_back(fValue);
                }
                break;

                case OP_ELSE:
                {
                    if (vfExec.empty())
                        return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
                    vfExec.back() = !vfExec.back();
                }
                break;

                case OP_ENDIF:
                {
                    if (vfExec.empty())
                        return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
                    vfExec.pop_back();
                }
                break;

                case OP_VERIFY:
                {
                    // (true -- ) or
                    // (false -- false) and return
                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    bool fValue = CastToBool(stacktop(-1));
                    if (fValue)
                        popstack(stack);
                    else
                        return set_error(serror, SCRIPT_ERR_VERIFY);
                }
                break;

                case OP_RETURN:
                {
                    return set_error(serror, SCRIPT_ERR_OP_RETURN);
                }
                break;


                //
                // Stack ops
                //
                case OP_TOALTSTACK:
                {
                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    altstack.push_back(stacktop(-1));
                    popstack(stack);
                }
                break;

                case OP_FROMALTSTACK:
                {
                    if (altstack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
                    stack.push_back(altstacktop(-1));
                    popstack(altstack);
                }
                break;

                case OP_2DROP:
                {
                    // (x1 x2 -- )
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    popstack(stack);
                    popstack(stack);
                }
                break;

                case OP_2DUP:
                {
                    // (x1 x2 -- x1 x2 x1 x2)
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype vch1 = stacktop(-2);
                    valtype vch2 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_3DUP:
                {
                    // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
                    if (stack.size() < 3)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype vch1 = stacktop(-3);
                    valtype vch2 = stacktop(-2);
                    valtype vch3 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                    stack.push_back(vch3);
                }
                break;

                case OP_2OVER:
                {
                    // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype vch1 = stacktop(-4);
                    valtype vch2 = stacktop(-3);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2ROT:
                {
                    // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
                    if (stack.size() < 6)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype vch1 = stacktop(-6);
                    valtype vch2 = stacktop(-5);
                    stack.erase(stack.end()-6, stack.end()-4);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2SWAP:
                {
                    // (x1 x2 x3 x4 -- x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    swap(stacktop(-4), stacktop(-2));
                    swap(stacktop(-3), stacktop(-1));
                }
                break;

                case OP_IFDUP:
                {
                    // (x - 0 | x x)
                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype vch = stacktop(-1);
                    if (CastToBool(vch))
                        stack.push_back(vch);
                }
                break;

                case OP_DEPTH:
                {
                    // -- stacksize
                    CScriptNum bn(stack.size());
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_DROP:
                {
                    // (x -- )
                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    popstack(stack);
                }
                break;

                case OP_DUP:
                {
                    // (x -- x x)
                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype vch = stacktop(-1);
                    stack.push_back(vch);
                }
                break;

                case OP_NIP:
                {
                    // (x1 x2 -- x2)
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    stack.erase(stack.end() - 2);
                }
                break;

                case OP_OVER:
                {
                    // (x1 x2 -- x1 x2 x1)
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype vch = stacktop(-2);
                    stack.push_back(vch);
                }
                break;

                case OP_PICK:
                case OP_ROLL:
                {
                    // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
                    // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
                    popstack(stack);
                    if (n < 0 || n >= (int)stack.size())
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype vch = stacktop(-n-1);
                    if (opcode == OP_ROLL)
                        stack.erase(stack.end()-n-1);
                    stack.push_back(vch);
                }
                break;

                case OP_ROT:
                {
                    // (x1 x2 x3 -- x2 x3 x1)
                    //  x2 x1 x3  after first swap
                    //  x2 x3 x1  after second swap
                    if (stack.size() < 3)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    swap(stacktop(-3), stacktop(-2));
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_SWAP:
                {
                    // (x1 x2 -- x2 x1)
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_TUCK:
                {
                    // (x1 x2 -- x2 x1 x2)
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype vch = stacktop(-1);
                    stack.insert(stack.end()-2, vch);
                }
                break;


                case OP_SIZE:
                {
                    // (in -- in size)
                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    CScriptNum bn(stacktop(-1).size());
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Bitwise logic
                //
                case OP_EQUAL:
                case OP_EQUALVERIFY:
                //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
                {
                    // (x1 x2 - bool)
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    bool fEqual = (vch1 == vch2);
                    // OP_NOTEQUAL is disabled because it would be too easy to say
                    // something like n != 1 and have some wiseguy pass in 1 with extra
                    // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
                    //if (opcode == OP_NOTEQUAL)
                    //    fEqual = !fEqual;
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fEqual ? vchTrue : vchFalse);
                    if (opcode == OP_EQUALVERIFY)
                    {
                        if (fEqual)
                            popstack(stack);
                        else
                            return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
                    }
                }
                break;


                //
                // Numeric
                //
                case OP_1ADD:
                case OP_1SUB:
                case OP_NEGATE:
                case OP_ABS:
                case OP_NOT:
                case OP_0NOTEQUAL:
                {
                    // (in -- out)
                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    CScriptNum bn(stacktop(-1), fRequireMinimal);
                    switch (opcode)
                    {
                    case OP_1ADD:       bn += bnOne; break;
                    case OP_1SUB:       bn -= bnOne; break;
                    case OP_NEGATE:     bn = -bn; break;
                    case OP_ABS:        if (bn < bnZero) bn = -bn; break;
                    case OP_NOT:        bn = (bn == bnZero); break;
                    case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
                    default:            assert(!"invalid opcode"); break;
                    }
                    popstack(stack);
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_ADD:
                case OP_SUB:
                case OP_BOOLAND:
                case OP_BOOLOR:
                case OP_NUMEQUAL:
                case OP_NUMEQUALVERIFY:
                case OP_NUMNOTEQUAL:
                case OP_LESSTHAN:
                case OP_GREATERTHAN:
                case OP_LESSTHANOREQUAL:
                case OP_GREATERTHANOREQUAL:
                case OP_MIN:
                case OP_MAX:
                {
                    // (x1 x2 -- out)
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    CScriptNum bn1(stacktop(-2), fRequireMinimal);
                    CScriptNum bn2(stacktop(-1), fRequireMinimal);
                    CScriptNum bn(0);
                    switch (opcode)
                    {
                    case OP_ADD:
                        bn = bn1 + bn2;
                        break;

                    case OP_SUB:
                        bn = bn1 - bn2;
                        break;

                    case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
                    case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
                    case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
                    case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
                    case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
                    case OP_LESSTHAN:            bn = (bn1 < bn2); break;
                    case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
                    case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
                    case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
                    case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
                    case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
                    default:                     assert(!"invalid opcode"); break;
                    }
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(bn.getvch());

                    if (opcode == OP_NUMEQUALVERIFY)
                    {
                        if (CastToBool(stacktop(-1)))
                            popstack(stack);
                        else
                            return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
                    }
                }
                break;

                case OP_WITHIN:
                {
                    // (x min max -- out)
                    if (stack.size() < 3)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    CScriptNum bn1(stacktop(-3), fRequireMinimal);
                    CScriptNum bn2(stacktop(-2), fRequireMinimal);
                    CScriptNum bn3(stacktop(-1), fRequireMinimal);
                    bool fValue = (bn2 <= bn1 && bn1 < bn3);
                    popstack(stack);
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fValue ? vchTrue : vchFalse);
                }
                break;


                //
                // Crypto
                //
                case OP_RIPEMD160:
                case OP_SHA1:
                case OP_SHA256:
                case OP_HASH160:
                case OP_HASH256:
                {
                    // (in -- hash)
                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    valtype& vch = stacktop(-1);
                    valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
                    if (opcode == OP_RIPEMD160)
                        CRIPEMD160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
                    else if (opcode == OP_SHA1)
                        CSHA1().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
                    else if (opcode == OP_SHA256)
                        CSHA256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
                    else if (opcode == OP_HASH160)
                        CHash160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
                    else if (opcode == OP_HASH256)
                        CHash256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
                    popstack(stack);
                    stack.push_back(vchHash);
                }
                break;                                   

                case OP_CODESEPARATOR:
                {
                    // Hash starts after the code separator
                    pbegincodehash = pc;
                }
                break;

                case OP_CHECKSIG:
                case OP_CHECKSIGVERIFY:
                {
                    // (sig pubkey -- bool)
                    if (stack.size() < 2)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);

                    valtype& vchSig    = stacktop(-2);
                    valtype& vchPubKey = stacktop(-1);

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signature, since there's no way for a signature to sign itself
                    scriptCode.FindAndDelete(CScript(vchSig));

                    if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
                        //serror is set
                        return false;
                    }
                    bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode);

                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fSuccess ? vchTrue : vchFalse);
                    if (opcode == OP_CHECKSIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
                    }
                }
                break;

                case OP_CHECKMULTISIG:
                case OP_CHECKMULTISIGVERIFY:
                {
                    // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)

                    int i = 1;
                    if ((int)stack.size() < i)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);

                    int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
                    if (nKeysCount < 0 || nKeysCount > 20)
                        return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
                    nOpCount += nKeysCount;
                    if (nOpCount > 201)
                        return set_error(serror, SCRIPT_ERR_OP_COUNT);
                    int ikey = ++i;
                    i += nKeysCount;
                    if ((int)stack.size() < i)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);

                    int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
                    if (nSigsCount < 0 || nSigsCount > nKeysCount)
                        return set_error(serror, SCRIPT_ERR_SIG_COUNT);
                    int isig = ++i;
                    i += nSigsCount;
                    if ((int)stack.size() < i)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signatures, since there's no way for a signature to sign itself
                    for (int k = 0; k < nSigsCount; k++)
                    {
                        valtype& vchSig = stacktop(-isig-k);
                        scriptCode.FindAndDelete(CScript(vchSig));
                    }

                    bool fSuccess = true;
                    while (fSuccess && nSigsCount > 0)
                    {
                        valtype& vchSig    = stacktop(-isig);
                        valtype& vchPubKey = stacktop(-ikey);

                        // Note how this makes the exact order of pubkey/signature evaluation
                        // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
                        // See the script_(in)valid tests for details.
                        if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
                            // serror is set
                            return false;
                        }

                        // Check signature
                        bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode);

                        if (fOk) {
                            isig++;
                            nSigsCount--;
                        }
                        ikey++;
                        nKeysCount--;

                        // If there are more signatures left than keys left,
                        // then too many signatures have failed. Exit early,
                        // without checking any further signatures.
                        if (nSigsCount > nKeysCount)
                            fSuccess = false;
                    }

                    // Clean up stack of actual arguments
                    while (i-- > 1)
                        popstack(stack);

                    // A bug causes CHECKMULTISIG to consume one extra argument
                    // whose contents were not checked in any way.
                    //
                    // Unfortunately this is a potential source of mutability,
                    // so optionally verify it is exactly equal to zero prior
                    // to removing it from the stack.
                    if (stack.size() < 1)
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                    if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
                        return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
                    popstack(stack);

                    stack.push_back(fSuccess ? vchTrue : vchFalse);

                    if (opcode == OP_CHECKMULTISIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
                    }
                }
                break;

                default:
                    return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
            }

            // Size limits
            if (stack.size() + altstack.size() > 1000)
                return set_error(serror, SCRIPT_ERR_STACK_SIZE);
        }
    }
    catch (...)
    {
        return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
    }

    if (!vfExec.empty())
        return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);

    return set_success(serror);
}
Example #12
0
static bool ParseCommandArguments(
    vector<string> args,
    StringLoaderStartParams &params,
    string &error)
{
    if (args.size() < 2) {
        error = usage;

        return false;
    }

    // get rid of first element, the program name
    args.erase(args.begin());

    for (size_t i = 0; i < args.size();) {
        if (args[i] == "--stdout") {
            params.output_stream = &::std::cout;
            i++;
            continue;
        }
        else if (args[i] == "--store") {
            string value;
            if (!GetArgumentValueAndPop(args, i, value)) {
                error = "--store argument requires a value. None found";
                return false;
            }
            params.store_path = value;
            continue;
        }
        else if (args[i] == "--default-bucket") {
            string value;
            if (!GetArgumentValueAndPop(args, i, value)) {
                error = "--default-bucket argument requires a value";
                return false;
            }
            params.default_bucket = value;
            continue;
        }
        else if (args[i] == "--default-stream-set") {
            string value;
            if (!GetArgumentValueAndPop(args, i, value)) {
                error = "--default-stream-set argument requires a value";
                return false;
            }
            params.default_set = value;
            continue;
        }
        else if (args[i] == "--lua-file") {
            string value;
            if (!GetArgumentValueAndPop(args, i, value)) {
                error = "--lua-file argument requires a value";
                return false;
            }
            params.lua_file = value;
            continue;
        }

        i++;
    }

    if (params.store_path.length() > 0) {
        if (params.default_bucket.length() < 1) {
            error = "--default-bucket required when --store is defined";
            return false;
        }

        if (params.default_set.length() < 1) {
            error = "--default-stream-set required when --store is defined";
            return false;
        }
    }

    return true;
}
Example #13
0
static void OSCrx_free(t_OSCrx *x)
{
	// Here, we need to free methods from the liblo server if one Pd object
	// is destroyed but others still exist. When no other remaining instances
	// require the liblo server, then we can destroy it as well.
	//
	// Unfortunately, the liblo library doesn't provide the hooks to do this;
	// A method can only be removed like this:
	// lo_server_del_method(lo_server s, const char *path, const char *typespec)
	//
	// For us, path and typespec are both NULL, so ALL methods will be deleted!
	//
	// Thus, we've copied the lo_server struct (and named it internal_lo_server)
	// so that we can remove methods if their user_data matches

	internal_lo_server s = (internal_lo_server) (x->serv->lo_serv);
	
#ifdef OSC_DEBUG
	post("OSCrx_free for %s", lo_server_get_url(x->serv->lo_serv));
#endif
	
    if (!s->first)
    {
		post("OSCrx error: Could not free method! The server has no registered callbacks.");   	
    	return;
    }

    internal_lo_method it, prev, next;
    it = (internal_lo_method) s->first;
    prev = it;

    while (it)
    {
    	// in case we free it:
    	next = it->next;

    	
    	// if the user_data points to this Pd instance:
    	if (it->user_data == (char*)x)
    	{
    		
    		// Take care when removing the head:
    		if (it == s->first) {
    			s->first = it->next;
    		} else {
    			prev->next = it->next;
    		}
    		next = it->next;
    		free((char *)it->path);
    		free((char *)it->typespec);
    		free(it);
    		it = prev;
    	   	
    	}
    	prev = it;
	    if (it) it = next;
	    
    }
    
    
	// if no other OSCrx_server objects need this liblo server, destroy it:
    if (!s->first)
    {
    	
    	for (g_iter = g_OSCrx_servers.begin(); g_iter != g_OSCrx_servers.end(); g_iter++)
    	{
        	// find the correct lo_server in the g_libloVector, and remove it:
    		if ((*g_iter) == x->serv)
    		{
 	    		g_OSCrx_servers.erase(g_iter);
	    		break;
    		}
       	}

    	//sys_rmpollfn(lo_server_get_socket_fd(x->serv->lo_serv));
        delete x->serv;
    	
#ifdef OSC_DEBUG
    	post("OSCrx: No more listeners need port %d, so destroyed the server.", x->serv->port);
#endif
    	
    }

}
Example #14
0
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
{
    CScript::const_iterator pc = script.begin();
    CScript::const_iterator pend = script.end();
    CScript::const_iterator pbegincodehash = script.begin();
    opcodetype opcode;
    valtype vchPushValue;
    vector<bool> vfExec;
    vector<valtype> altstack;
    if (script.size() > 10000)
        return false;
    int nOpCount = 0;

    try
    {
        while (pc < pend)
        {
            bool fExec = !count(vfExec.begin(), vfExec.end(), false);

            //
            // Read instruction
            //
            if (!script.GetOp(pc, opcode, vchPushValue))
                return false;
            if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
                return false;

            // Note how OP_RESERVED does not count towards the opcode limit.
            if (opcode > OP_16 && ++nOpCount > 201)
                return false;

            if (opcode == OP_CAT ||
                opcode == OP_SUBSTR ||
                opcode == OP_LEFT ||
                opcode == OP_RIGHT ||
                opcode == OP_INVERT ||
                opcode == OP_AND ||
                opcode == OP_OR ||
                opcode == OP_XOR ||
                opcode == OP_2MUL ||
                opcode == OP_2DIV ||
                opcode == OP_MUL ||
                opcode == OP_DIV ||
                opcode == OP_MOD ||
                opcode == OP_LSHIFT ||
                opcode == OP_RSHIFT)
                return false; // Disabled opcodes.

            if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
                stack.push_back(vchPushValue);
            else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
            switch (opcode)
            {
                //
                // Push value
                //
                case OP_1NEGATE:
                case OP_1:
                case OP_2:
                case OP_3:
                case OP_4:
                case OP_5:
                case OP_6:
                case OP_7:
                case OP_8:
                case OP_9:
                case OP_10:
                case OP_11:
                case OP_12:
                case OP_13:
                case OP_14:
                case OP_15:
                case OP_16:
                {
                    // ( -- value)
                    CScriptNum bn((int)opcode - (int)(OP_1 - 1));
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Control
                //
                case OP_NOP:
                case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
                case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
                break;

                case OP_IF:
                case OP_NOTIF:
                {
                    // <expression> if [statements] [else [statements]] endif
                    bool fValue = false;
                    if (fExec)
                    {
                        if (stack.size() < 1)
                            return false;
                        valtype& vch = stacktop(-1);
                        fValue = CastToBool(vch);
                        if (opcode == OP_NOTIF)
                            fValue = !fValue;
                        popstack(stack);
                    }
                    vfExec.push_back(fValue);
                }
                break;

                case OP_ELSE:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.back() = !vfExec.back();
                }
                break;

                case OP_ENDIF:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.pop_back();
                }
                break;

                case OP_VERIFY:
                {
                    // (true -- ) or
                    // (false -- false) and return
                    if (stack.size() < 1)
                        return false;
                    bool fValue = CastToBool(stacktop(-1));
                    if (fValue)
                        popstack(stack);
                    else
                        return false;
                }
                break;

                case OP_RETURN:
                {
                    return false;
                }
                break;


                //
                // Stack ops
                //
                case OP_TOALTSTACK:
                {
                    if (stack.size() < 1)
                        return false;
                    altstack.push_back(stacktop(-1));
                    popstack(stack);
                }
                break;

                case OP_FROMALTSTACK:
                {
                    if (altstack.size() < 1)
                        return false;
                    stack.push_back(altstacktop(-1));
                    popstack(altstack);
                }
                break;

                case OP_2DROP:
                {
                    // (x1 x2 -- )
                    if (stack.size() < 2)
                        return false;
                    popstack(stack);
                    popstack(stack);
                }
                break;

                case OP_2DUP:
                {
                    // (x1 x2 -- x1 x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch1 = stacktop(-2);
                    valtype vch2 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_3DUP:
                {
                    // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
                    if (stack.size() < 3)
                        return false;
                    valtype vch1 = stacktop(-3);
                    valtype vch2 = stacktop(-2);
                    valtype vch3 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                    stack.push_back(vch3);
                }
                break;

                case OP_2OVER:
                {
                    // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    valtype vch1 = stacktop(-4);
                    valtype vch2 = stacktop(-3);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2ROT:
                {
                    // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
                    if (stack.size() < 6)
                        return false;
                    valtype vch1 = stacktop(-6);
                    valtype vch2 = stacktop(-5);
                    stack.erase(stack.end()-6, stack.end()-4);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2SWAP:
                {
                    // (x1 x2 x3 x4 -- x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    swap(stacktop(-4), stacktop(-2));
                    swap(stacktop(-3), stacktop(-1));
                }
                break;

                case OP_IFDUP:
                {
                    // (x - 0 | x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    if (CastToBool(vch))
                        stack.push_back(vch);
                }
                break;

                case OP_DEPTH:
                {
                    // -- stacksize
                    CScriptNum bn(stack.size());
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_DROP:
                {
                    // (x -- )
                    if (stack.size() < 1)
                        return false;
                    popstack(stack);
                }
                break;

                case OP_DUP:
                {
                    // (x -- x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.push_back(vch);
                }
                break;

                case OP_NIP:
                {
                    // (x1 x2 -- x2)
                    if (stack.size() < 2)
                        return false;
                    stack.erase(stack.end() - 2);
                }
                break;

                case OP_OVER:
                {
                    // (x1 x2 -- x1 x2 x1)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-2);
                    stack.push_back(vch);
                }
                break;

                case OP_PICK:
                case OP_ROLL:
                {
                    // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
                    // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
                    if (stack.size() < 2)
                        return false;
                    int n = CScriptNum(stacktop(-1)).getint();
                    popstack(stack);
                    if (n < 0 || n >= (int)stack.size())
                        return false;
                    valtype vch = stacktop(-n-1);
                    if (opcode == OP_ROLL)
                        stack.erase(stack.end()-n-1);
                    stack.push_back(vch);
                }
                break;

                case OP_ROT:
                {
                    // (x1 x2 x3 -- x2 x3 x1)
                    //  x2 x1 x3  after first swap
                    //  x2 x3 x1  after second swap
                    if (stack.size() < 3)
                        return false;
                    swap(stacktop(-3), stacktop(-2));
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_SWAP:
                {
                    // (x1 x2 -- x2 x1)
                    if (stack.size() < 2)
                        return false;
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_TUCK:
                {
                    // (x1 x2 -- x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.insert(stack.end()-2, vch);
                }
                break;


                case OP_SIZE:
                {
                    // (in -- in size)
                    if (stack.size() < 1)
                        return false;
                    CScriptNum bn(stacktop(-1).size());
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Bitwise logic
                //
                case OP_EQUAL:
                case OP_EQUALVERIFY:
                //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
                {
                    // (x1 x2 - bool)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    bool fEqual = (vch1 == vch2);
                    // OP_NOTEQUAL is disabled because it would be too easy to say
                    // something like n != 1 and have some wiseguy pass in 1 with extra
                    // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
                    //if (opcode == OP_NOTEQUAL)
                    //    fEqual = !fEqual;
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fEqual ? vchTrue : vchFalse);
                    if (opcode == OP_EQUALVERIFY)
                    {
                        if (fEqual)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;


                //
                // Numeric
                //
                case OP_1ADD:
                case OP_1SUB:
                case OP_NEGATE:
                case OP_ABS:
                case OP_NOT:
                case OP_0NOTEQUAL:
                {
                    // (in -- out)
                    if (stack.size() < 1)
                        return false;
                    CScriptNum bn(stacktop(-1));
                    switch (opcode)
                    {
                    case OP_1ADD:       bn += bnOne; break;
                    case OP_1SUB:       bn -= bnOne; break;
                    case OP_NEGATE:     bn = -bn; break;
                    case OP_ABS:        if (bn < bnZero) bn = -bn; break;
                    case OP_NOT:        bn = (bn == bnZero); break;
                    case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
                    default:            assert(!"invalid opcode"); break;
                    }
                    popstack(stack);
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_ADD:
                case OP_SUB:
                case OP_BOOLAND:
                case OP_BOOLOR:
                case OP_NUMEQUAL:
                case OP_NUMEQUALVERIFY:
                case OP_NUMNOTEQUAL:
                case OP_LESSTHAN:
                case OP_GREATERTHAN:
                case OP_LESSTHANOREQUAL:
                case OP_GREATERTHANOREQUAL:
                case OP_MIN:
                case OP_MAX:
                {
                    // (x1 x2 -- out)
                    if (stack.size() < 2)
                        return false;
                    CScriptNum bn1(stacktop(-2));
                    CScriptNum bn2(stacktop(-1));
                    CScriptNum bn(0);
                    switch (opcode)
                    {
                    case OP_ADD:
                        bn = bn1 + bn2;
                        break;

                    case OP_SUB:
                        bn = bn1 - bn2;
                        break;

                    case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
                    case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
                    case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
                    case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
                    case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
                    case OP_LESSTHAN:            bn = (bn1 < bn2); break;
                    case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
                    case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
                    case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
                    case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
                    case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
                    default:                     assert(!"invalid opcode"); break;
                    }
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(bn.getvch());

                    if (opcode == OP_NUMEQUALVERIFY)
                    {
                        if (CastToBool(stacktop(-1)))
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_WITHIN:
                {
                    // (x min max -- out)
                    if (stack.size() < 3)
                        return false;
                    CScriptNum bn1(stacktop(-3));
                    CScriptNum bn2(stacktop(-2));
                    CScriptNum bn3(stacktop(-1));
                    bool fValue = (bn2 <= bn1 && bn1 < bn3);
                    popstack(stack);
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fValue ? vchTrue : vchFalse);
                }
                break;


                //
                // Crypto
                //
                case OP_RIPEMD160:
                case OP_SHA1:
                case OP_SHA256:
                case OP_HASH160:
                case OP_HASH256:
                {
                    // (in -- hash)
                    if (stack.size() < 1)
                        return false;
                    valtype& vch = stacktop(-1);
                    valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
                    if (opcode == OP_RIPEMD160)
                        CRIPEMD160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    else if (opcode == OP_SHA1)
                        CSHA1().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    else if (opcode == OP_SHA256)
                        CSHA256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    else if (opcode == OP_HASH160)
                        CHash160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    else if (opcode == OP_HASH256)
                        CHash256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    popstack(stack);
                    stack.push_back(vchHash);
                }
                break;

                case OP_CODESEPARATOR:
                {
                    // Hash starts after the code separator
                    pbegincodehash = pc;
                }
                break;

                case OP_CHECKSIG:
                case OP_CHECKSIGVERIFY:
                {
                    // (sig pubkey -- bool)
                    if (stack.size() < 2)
                        return false;

                    valtype& vchSig    = stacktop(-2);
                    valtype& vchPubKey = stacktop(-1);

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signature, since there's no way for a signature to sign itself
                    scriptCode.FindAndDelete(CScript(vchSig));

                    bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
                        CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);

                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fSuccess ? vchTrue : vchFalse);
                    if (opcode == OP_CHECKSIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_CHECKMULTISIG:
                case OP_CHECKMULTISIGVERIFY:
                {
                    // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)

                    int i = 1;
                    if ((int)stack.size() < i)
                        return false;

                    int nKeysCount = CScriptNum(stacktop(-i)).getint();
                    if (nKeysCount < 0 || nKeysCount > 20)
                        return false;
                    nOpCount += nKeysCount;
                    if (nOpCount > 201)
                        return false;
                    int ikey = ++i;
                    i += nKeysCount;
                    if ((int)stack.size() < i)
                        return false;

                    int nSigsCount = CScriptNum(stacktop(-i)).getint();
                    if (nSigsCount < 0 || nSigsCount > nKeysCount)
                        return false;
                    int isig = ++i;
                    i += nSigsCount;
                    if ((int)stack.size() < i)
                        return false;

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signatures, since there's no way for a signature to sign itself
                    for (int k = 0; k < nSigsCount; k++)
                    {
                        valtype& vchSig = stacktop(-isig-k);
                        scriptCode.FindAndDelete(CScript(vchSig));
                    }

                    bool fSuccess = true;
                    while (fSuccess && nSigsCount > 0)
                    {
                        valtype& vchSig    = stacktop(-isig);
                        valtype& vchPubKey = stacktop(-ikey);

                        // Check signature
                        bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
                            CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);

                        if (fOk) {
                            isig++;
                            nSigsCount--;
                        }
                        ikey++;
                        nKeysCount--;

                        // If there are more signatures left than keys left,
                        // then too many signatures have failed
                        if (nSigsCount > nKeysCount)
                            fSuccess = false;
                    }

                    // Clean up stack of actual arguments
                    while (i-- > 1)
                        popstack(stack);

                    // A bug causes CHECKMULTISIG to consume one extra argument
                    // whose contents were not checked in any way.
                    //
                    // Unfortunately this is a potential source of mutability,
                    // so optionally verify it is exactly equal to zero prior
                    // to removing it from the stack.
                    if (stack.size() < 1)
                        return false;
                    if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
                        return error("CHECKMULTISIG dummy argument not null");
                    popstack(stack);

                    stack.push_back(fSuccess ? vchTrue : vchFalse);

                    if (opcode == OP_CHECKMULTISIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                default:
                    return false;
            }

            // Size limits
            if (stack.size() + altstack.size() > 1000)
                return false;
        }
    }
    catch (...)
    {
        return false;
    }

    if (!vfExec.empty())
        return false;

    return true;
}
int LTKStrEncoding::tamilShapeStrToUnicode(const vector<unsigned short>& shapeIDs, vector<unsigned short>& unicodeString)
{
	int errorCode;
	LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << 
	  " Entering: LTKStrEncoding::tamilShapeStrToUnicode()" << endl;

	vector<unsigned short>::const_iterator shapeIDsIter, shapeIDsEnd;
	int charIndex;  //index variable for unicode string
	unsigned short currentChar; //unicode representation of the character 
	bool matraFlag;   //indicates whether a matra is following the current character

	//iterating through the shape IDs
	shapeIDsEnd = shapeIDs.end();
	for(shapeIDsIter = shapeIDs.begin();shapeIDsIter != shapeIDsEnd;++shapeIDsIter)
	{
		if(*shapeIDsIter == SHRT_MAX )
			unicodeString.push_back(L' ');
		else if(*shapeIDsIter < 35)
		{
			if((errorCode = tamilCharToUnicode(*shapeIDsIter,unicodeString)) != SUCCESS)
			{
				return errorCode;
			} 
		}
		else if (*shapeIDsIter < 58 )
		{
			if((errorCode = tamilCharToUnicode((*shapeIDsIter-23),unicodeString)) != SUCCESS)
			{
				return errorCode;
			}
			unicodeString.push_back(0x0bbf); //i mAtra
		}
		else if (*shapeIDsIter < 81 )
		{
			if((errorCode = tamilCharToUnicode((*shapeIDsIter-46),unicodeString)) != SUCCESS)
			{
				return errorCode;
			}
			unicodeString.push_back(0x0bc0); //ii mAtra
		}
		else if (*shapeIDsIter < 99 )
		{
			if((errorCode = tamilCharToUnicode((*shapeIDsIter-69),unicodeString)) != SUCCESS)
			{
				return errorCode;
			}
			unicodeString.push_back(0x0bc1); //u mAtra
		}
		else if (*shapeIDsIter < 117 )
		{
			if((errorCode = tamilCharToUnicode((*shapeIDsIter-87),unicodeString)) != SUCCESS)
			unicodeString.push_back(0x0bc2); //uu mAtra
		}
		else if (*shapeIDsIter < 118 )
		{
			unicodeString.push_back(0x0bbe); //aa mAtra
		}
		else if (*shapeIDsIter < 119 )
		{
			unicodeString.push_back(0x0bc6); //e mAtra
		}
		else if (*shapeIDsIter < 120 )
		{
			unicodeString.push_back(0x0bc7); //E mAtra
		}
		else if (*shapeIDsIter < 121 )
		{
			unicodeString.push_back(0x0bc8); //ai mAtra
		}
		else if(*shapeIDsIter < 122 )
		{
			//letter shri
			unicodeString.push_back(0x0bb8);//ss
			unicodeString.push_back(0x0bcd);//halant
			unicodeString.push_back(0x0bb0);//r
			unicodeString.push_back(0x0bc0);//ii
		}
		else if(*shapeIDsIter < 127 )
		{
			if((errorCode = tamilCharToUnicode((*shapeIDsIter-92),unicodeString)) != SUCCESS)
			{
				return errorCode;
			}
			unicodeString.push_back(0x0bc1); //u mAtra
		}
		else if(*shapeIDsIter < 132 )
		{
			if((errorCode = tamilCharToUnicode((*shapeIDsIter-97),unicodeString)) != SUCCESS)
			{
				return errorCode;
			}
			unicodeString.push_back(0x0bc2); //u mAtra
		}
		else if(*shapeIDsIter < 155 )
		{
			if((errorCode = tamilCharToUnicode((*shapeIDsIter-120),unicodeString)) != SUCCESS)
			{
				return errorCode;
			}
			unicodeString.push_back(0x0bcd); //halant
		}
		else if (*shapeIDsIter < 156 )
		{
			unicodeString.push_back(0x0b94);
		}
		else
		{
			LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                  <<"Error : "<< EINVALID_SHAPEID <<":"<< getErrorMessage(EINVALID_SHAPEID)
                  <<"LTKStrEncoding::tamilShapeStrToUnicode()" <<endl;

			LTKReturnError(EINVALID_SHAPEID);
		}
	}

	//Applying rules for e, E , ai, o, O, and au matras
	charIndex = 0;
	while( charIndex < unicodeString.size() )
	{
		currentChar = unicodeString[charIndex];
		switch(currentChar)
		{
		case 0x0bc6://e
		case 0x0bc7://E
		case 0x0bc8://ai
			if( (charIndex +1) < unicodeString.size() )
			{
				unicodeString[charIndex]   = unicodeString[charIndex+1];
				unicodeString[charIndex+1] = currentChar;
				charIndex += 2;
			}
			else
			{
				++charIndex;
			}
			break;
		case 0x0bbe: //check for `o' or `O'
			if(charIndex>0)//within string bounds
			{
				if(unicodeString[charIndex-1] == 0x0bc6 )
				{
					unicodeString[charIndex-1] = 0x0bca;
					unicodeString.erase(unicodeString.begin()+charIndex);
				}
				else if(unicodeString[charIndex-1] == 0x0bc7 )
				{
					unicodeString[charIndex-1] = 0x0bcb;
					unicodeString.erase(unicodeString.begin()+charIndex);
				}
				else
				{
					++charIndex;
				}
			}
			else
			{
				++charIndex;
			}
			break;
		case 0x0bb3: //check for au
			matraFlag = (charIndex+1<unicodeString.size() && (unicodeString[charIndex+1] > 0x0bbd && unicodeString[charIndex+1] < 0x0bc3 ) );

			//if la is not follwed by a matra and is preceded by an e matra it is an au matra
			if((charIndex >0)&&(unicodeString[charIndex-1] == 0x0bc6) && (!matraFlag))
			{
				unicodeString[charIndex-1] = 0x0bcc;
				unicodeString.erase(unicodeString.begin()+charIndex);
			}
			else
			{
				++charIndex;
			}
			break;
		default:
			++charIndex;
			
		}
		
	}

	LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << 
	  " Exiting: LTKStrEncoding::tamilShapeStrToUnicode()" << endl;

	return SUCCESS;
}
Example #16
0
void PitchContours::trackPitchContour(size_t& index, vector<Real>& contourBins, vector<Real>& contourSaliences) {
  // find the highest salient peak through all frames
  size_t max_i;
  int max_j;
  Real maxSalience = 0;

  for (size_t i=0; i<_numberFrames; i++) {
    if (_salientPeaksValues[i].size() > 0) {
      int j = argmax(_salientPeaksValues[i]);
      if (_salientPeaksValues[i][j] > maxSalience) {
        maxSalience = _salientPeaksValues[i][j];
        max_i = i;
        max_j = j;
      }
    }
  }
  if (maxSalience == 0) {
    // no salient peaks left in the set -> no new contours added
    return;
  }

  vector<pair<size_t,int> > removeNonSalientPeaks;

  // start new contour with this peak
  index = max_i; // the starting index of the contour
  contourBins.push_back(_salientPeaksBins[index][max_j]);
  contourSaliences.push_back(_salientPeaksValues[index][max_j]);
  // remove the peak from salient peaks
  removePeak(_salientPeaksBins, _salientPeaksValues, index, max_j);

  // track forwards in time
  int gap=0, best_peak_j;
  for (size_t i=index+1; i<_numberFrames; i++) {
    // find salient peaks in the next frame
    best_peak_j = findNextPeak(_salientPeaksBins, contourBins, i);
    if (best_peak_j >= 0) {
      // salient peak was found
      contourBins.push_back(_salientPeaksBins[i][best_peak_j]);
      contourSaliences.push_back(_salientPeaksValues[i][best_peak_j]);
      removePeak(_salientPeaksBins, _salientPeaksValues, i, best_peak_j);
      gap = 0;
    }
    else {
      // no peaks were found -> use non-salient ones
      // track using non-salient peaks for up to 100 ms by default
      if (gap+1 > _timeContinuityInFrames) {
        // this frame would already exceed the gap --> stop forward tracking
        break;
      }
      best_peak_j = findNextPeak(_nonSalientPeaksBins, contourBins, i);
      if (best_peak_j >= 0) {
        contourBins.push_back(_nonSalientPeaksBins[i][best_peak_j]);
        contourSaliences.push_back(_nonSalientPeaksValues[i][best_peak_j]);
        removeNonSalientPeaks.push_back(make_pair(i, best_peak_j));
        gap += 1;
      }
      else {
        break; // no salient nor non-salient peaks were found -> end of contour
      }
    }
  }
  // remove all included non-salient peaks from the tail of the contour,
  // as the contour should always finish with a salient peak
  for (int g=0; g<gap; g++) { // FIXME is using erase() faster?
    contourBins.pop_back();
    contourSaliences.pop_back();
  }

  // track backwards in time
  if (index == 0) {
    // we reached the starting frame

    // check if the contour exceeds the allowed minimum length
    if (contourBins.size() < _timeContinuityInFrames) {
      contourBins.clear();
      contourSaliences.clear();
    }
    return;
  }

  gap = 0;
  for (size_t i=index-1;;) {
    // find salient peaks in the previous frame
    best_peak_j = findNextPeak(_salientPeaksBins, contourBins, i, true);
    if (best_peak_j >= 0) {
      // salient peak was found, insert forward contourBins.insert(contourBins.begin(), _salientPeaksBins[i][best_peak_j]);
      contourBins.insert(contourBins.begin(), _salientPeaksBins[i][best_peak_j]);
      contourSaliences.insert(contourSaliences.begin(), _salientPeaksValues[i][best_peak_j]);
      removePeak(_salientPeaksBins, _salientPeaksValues, i, best_peak_j);
      index--;
      gap = 0;
    } else {
      // no salient peaks were found -> use non-salient ones
      if (gap+1 > _timeContinuityInFrames) {
        // this frame would already exceed the gap --> stop backward tracking
        break;
      }
      best_peak_j = findNextPeak(_nonSalientPeaksBins, contourBins, i, true);
      if (best_peak_j >= 0) {
        contourBins.insert(contourBins.begin(), _nonSalientPeaksBins[i][best_peak_j]);
        contourSaliences.insert(contourSaliences.begin(), _nonSalientPeaksValues[i][best_peak_j]);
        removeNonSalientPeaks.push_back(make_pair(i, best_peak_j));
        index--;
        gap += 1;
      }
      else {
        // no salient nor non-salient peaks were found -> end of contour
        break;
      }
    }

    // manual check of loop conditions, as size_t cannot be negative and, therefore, conditions inside "for" cannot be used
    if (i > 0) {
     i--;
    }
    else {
      break;
    }
  }
  // remove non-salient peaks for the beginning of the contour,
  // as the contour should start with a salient peak
  contourBins.erase(contourBins.begin(), contourBins.begin() + gap);
  contourSaliences.erase(contourSaliences.begin(), contourSaliences.begin() + gap);
  index += gap;

  // remove all employed non-salient peaks for the list of available peaks
  for(size_t r=0; r<removeNonSalientPeaks.size(); r++) {
    size_t i_p = removeNonSalientPeaks[r].first;
    if (i_p < index || i_p > index + contourBins.size()) {
      continue;
    }
    int j_p = removeNonSalientPeaks[r].second;
    removePeak(_nonSalientPeaksBins, _nonSalientPeaksValues, i_p, j_p);
  }
}
Example #17
0
/**
- FUNCI? BlobAnalysis
- FUNCIONALITAT: Extreu els blobs d'una imatge d'un sol canal
- PARÀMETRES:
	- inputImage: Imatge d'entrada. Ha de ser d'un sol canal
	- threshold: Nivell de gris per considerar un pixel blanc o negre
	- maskImage: Imatge de màscara fora de la cual no es calculen els blobs. A més,
				 els blobs que toquen els pixels de la màscara a 0, són considerats
				 externs
	- borderColor: Color del marc de la imatge (0=black or 1=white)
	- findmoments: calcula els moments dels blobs o no
	- RegionData: on es desar?el resultat
- RESULTAT:
	- retorna true si tot ha anat b? false si no. Deixa el resultat a blobs.
- RESTRICCIONS:
	- La imatge d'entrada ha de ser d'un sol canal
- AUTOR: [email protected]
- DATA DE CREACI? 25-05-2005.
- MODIFICACI? Data. Autor. Descripci?
	- [email protected], [email protected]: adaptaci?a les OpenCV
*/
bool BlobAnalysis(	IplImage* inputImage,
					int threshold,
				    IplImage* maskImage,
				    bool borderColor,
				    bool findmoments,
					vector<CBlob*> &RegionData )	
{
	
	// dimensions of input image taking in account the ROI
	int Cols, Rows, startCol, startRow;

	if( inputImage->roi )
	{
		CvRect imageRoi = cvGetImageROI( inputImage );
		startCol = imageRoi.x;
		startRow = imageRoi.y;
		Cols = imageRoi.width;
		Rows = imageRoi.height;
	}
	else
	{
		startCol = 0;
		startRow = 0; 
		Cols = inputImage->width;
		Rows = inputImage->height;
	}

	int Trans = Cols;				// MAX trans in any row
	char* pMask;
	char* pImage;

	// Convert image array into transition array. In each row
	// the transition array tells which columns have a color change
	int iCol,iRow,iTran, Tran;				// Data for a given run
	bool ThisCell, LastCell;		// Contents (colors (0 or 1)) within this row
	int TransitionOffset = 0;		// Performance booster to avoid multiplication
	
	// row 0 and row Rows+1 represent the border
	int i;
	int *Transition;				// Transition Matrix

	int nombre_pixels_mascara = 0;
	//! Imatge amb el perimetre extern de cada pixel
	IplImage *imatgePerimetreExtern;

	// input images must have only 1-channel and be an image
	if( !CV_IS_IMAGE( inputImage ) || (inputImage->nChannels != 1) )
	{
		return false;
	}
	if( maskImage != NULL )
	{
		// input image and mask are a valid image?
		if( !CV_IS_IMAGE( inputImage ) || !CV_IS_IMAGE( maskImage )) 
			return false;

		// comprova que la màscara tingui les mateixes dimensions que la imatge
		if( inputImage->width != maskImage->width || inputImage->height !=
maskImage->height ) 

		// comprova que la màscara sigui una imatge d'un sol canal (grayscale)
		if( maskImage->nChannels != 1 )
		{
			return false;
		}
		
	}

	// Initialize Transition array
	Transition=new int[(Rows + 2)*(Cols + 2)];
	memset(Transition,0,(Rows + 2) * (Cols + 2)*sizeof(int));
	Transition[0] = Transition[(Rows + 1) * (Cols + 2)] = Cols + 2;
	
	// Start at the beginning of the image (startCol, startRow)
	pImage = inputImage->imageData + startCol - 1 + startRow * inputImage->widthStep;

/*
	Paral·lelitzaci?del càlcul de la matriu de transicions
	Fem que cada iteraci?del for el faci un thread o l'altre ( tenim 2 possibles threads )	
*/
	if(maskImage == NULL)
	{
		imatgePerimetreExtern = NULL;

		//Fill Transition array
		for(iRow = 1; iRow < Rows + 1; iRow++)		// Choose a row of Bordered image
		{
			TransitionOffset = iRow*(Cols + 2); //per a que sigui paral·litzable
			iTran = 0;					// Index into Transition array
			Tran = 0;					// No transitions at row start
			LastCell = borderColor;

			for(iCol = 0; iCol < Cols + 2; iCol++)	// Scan that row of Bordered image
			{
				if(iCol == 0 || iCol == Cols+1) 
					ThisCell = borderColor;
				else
					ThisCell = ((unsigned char) *(pImage)) > threshold;

				if(ThisCell != LastCell)
				{
					Transition[TransitionOffset + iTran] = Tran;	// Save completed Tran
					iTran++;						// Prepare new index
					LastCell = ThisCell;			// With this color
				}

				Tran++;	// Tran continues
				pImage++;
			}
			
			Transition[TransitionOffset + iTran] = Tran;	// Save completed run
			if ( (TransitionOffset + iTran + 1) < (Rows + 1)*(Cols + 2) )
			{
				Transition[TransitionOffset + iTran + 1] = -1;
			}
			//jump to next row (beginning from (startCol, startRow))
			pImage = inputImage->imageData - 1 + startCol + (iRow+startRow)*inputImage->widthStep;
		}
	}
	else
	{
		//maskImage not NULL: Cal recòrrer la màscara tamb?per calcular la matriu de transicions

		char perimeter;
		char *pPerimetre;
		
		// creem la imatge que contindr?el perimetre extern de cada pixel
		imatgePerimetreExtern = cvCreateImage( cvSize(maskImage->width, maskImage->height), IPL_DEPTH_8U, 1);
		cvSetZero( imatgePerimetreExtern );

		pMask = maskImage->imageData - 1;
		
		//Fill Transition array
		for(iRow = 1; iRow < Rows + 1; iRow++)		// Choose a row of Bordered image
		{
			TransitionOffset = iRow*(Cols + 2);
			iTran = 0;					// Index into Transition array
			Tran = 0;					// No transitions at row start
			LastCell = borderColor;

			pPerimetre = imatgePerimetreExtern->imageData + (iRow - 1) * imatgePerimetreExtern->widthStep;
			//pMask = maskImage->imageData + (iRow-1) * maskImage->widthStep;

			for(iCol = 0; iCol < Cols + 2; iCol++)	// Scan that row of Bordered image
			{
				if(iCol == 0 || iCol == Cols+1 || ((unsigned char) *pMask) == PIXEL_EXTERIOR) 
					ThisCell = borderColor;
				else
					ThisCell = ((unsigned char) *(pImage)) > threshold;

				if(ThisCell != LastCell)
				{
					Transition[TransitionOffset + iTran] = Tran;	// Save completed Tran
					iTran++;						// Prepare new index
					LastCell = ThisCell;			// With this color
				}

				/*////////////////////////////////////////////////////////////////////////
				Calcul de la imatge amb els pixels externs
				////////////////////////////////////////////////////////////////////////*/
				// pels pixels externs no cal calcular res pq no hi accedir-hem
				if( (iCol > 0) && (iCol < Cols) )
				{
					if( *pMask == PIXEL_EXTERIOR )
					{
						*pPerimetre = 0;
					}
					else
					{
						perimeter = 0;
						
						// pixels al nord de l'actual
						if(iRow>1)
						{
							if( *(pMask - maskImage->widthStep ) == PIXEL_EXTERIOR) perimeter++;
						}

						// pixels a l'est i oest de l'actual
						if( iRow < imatgePerimetreExtern->height )
						{
							if( (iCol>0) && (*(pMask-1) == PIXEL_EXTERIOR) ) perimeter++;

							if( ( iCol < imatgePerimetreExtern->width - 1) && (*(pMask+1) == PIXEL_EXTERIOR) ) perimeter++;
						}

						// pixels al sud de l'actual
						if( iRow < imatgePerimetreExtern->height - 1)
						{
							if( (*(pMask+maskImage->widthStep) == PIXEL_EXTERIOR) ) perimeter++;
						}
				
						*pPerimetre = perimeter;
					}
				}

				Tran++;	// Tran continues
				pImage++;
				pMask++;
				pPerimetre++;
			}
			Transition[TransitionOffset + iTran] = Tran;	// Save completed run

			if ( (TransitionOffset + iTran + 1) < (Rows + 1)*(Cols + 2) )
			{
				Transition[TransitionOffset + iTran + 1] = -1;
			}

			
			//jump to next row (beginning from (startCol, startRow))
			pImage = inputImage->imageData - 1 + startCol + (iRow+startRow)*inputImage->widthStep;
			//the mask should be the same size as image Roi, so don't take into account the offset
			pMask = maskImage->imageData - 1 + iRow*maskImage->widthStep;
		}
	}

	// Process transition code depending on Last row and This row
	//
	// Last ---++++++--+++++++++++++++-----+++++++++++++++++++-----++++++-------+++---
	// This -----+++-----++++----+++++++++----+++++++---++------------------++++++++--
	//
	// There are various possibilities:
	//
	// Case     1       2       3       4       5       6       7       8
	// Last |xxx    |xxxxoo |xxxxxxx|xxxxxxx|ooxxxxx|ooxxx  |ooxxxxx|    xxx|
	// This |    yyy|    yyy|  yyyy |  yyyyy|yyyyyyy|yyyyyyy|yyyy   |yyyy   |
	// Here o is optional
	// 
	// Here are the primitive tests to distinguish these 6 cases:
	//   A) Last end < This start - 1 OR NOT		Note: -1
	//   B) This end < Last start OR NOT
	//   C) Last start < This start OR NOT
	//   D) This end < Last end OR NOT
	//   E) This end = Last end OR NOT
	//
	// Here is how to use these tests to determine the case:
	//   Case 1 = A [=> NOT B AND C AND NOT D AND NOT E]
	//   Case 2 = C AND NOT D AND NOT E [AND NOT A AND NOT B]
	//   Case 3 = C AND D [=> NOT E] [AND NOT A AND NOT B]
	//   Case 4 = C AND NOT D AND E [AND NOT A AND NOT B]
	//   Case 5 = NOT C AND E [=> NOT D] [AND NOT A AND NOT B]
	//   Case 6 = NOT C AND NOT D AND NOT E [AND NOT A AND NOT B]
	//   Case 7 = NOT C AND D [=> NOT E] [AND NOT A AND NOT B]
	//   Case 8 = B [=> NOT A AND NOT C AND D AND NOT E]
	//
	// In cases 2,3,4,5,6,7 the following additional test is needed:
	//   Match) This color = Last color OR NOT
	//
	// In cases 5,6,7 the following additional test is needed:
	//   Known) This region was already matched OR NOT
	//
	// Here are the main tests and actions:
	//   Case 1: LastIndex++;
	//   Case 2: if(Match) {y = x;}
	//           LastIndex++;
	//   Case 3: if(Match) {y = x;}
	//           else {y = new}
	//           ThisIndex++;
	//   Case 4: if(Match) {y = x;}
	//           else {y = new}
	//           LastIndex++;
	//           ThisIndex++;
	//   Case 5: if(Match AND NOT Known) {y = x}
	//           else if(Match AND Known) {Subsume(x,y)}
	//           LastIndex++;ThisIndex++
	//   Case 6: if(Match AND NOT Known) {y = x}
	//           else if(Match AND Known) {Subsume(x,y)}
	//           LastIndex++;
	//   Case 7: if(Match AND NOT Known) {y = x}
	//           else if(Match AND Known) {Subsume(x,y)}
	//           ThisIndex++;
	//   Case 8: ThisIndex++;

	int *SubsumedRegion = NULL;			
	
	double ThisParent;	// These data can change when the line is current
	double ThisArea;
	double ThisPerimeter;
	double Thisu10;
	double Thisu01;
	double Thisu20;
	double Thisu02;
	double Thisu11;
	double ThisMinX;
	double ThisMaxX;
	double ThisMinY;
	double ThisMaxY;
	double LastPerimeter;	// This is the only data for retroactive change
	double ThisExternPerimeter;
	
	int HighRegionNum = 0;
	int RegionNum = 0;
	int ErrorFlag = 0;
	
	int LastRow, ThisRow;			// Row number
	int LastStart, ThisStart;		// Starting column of run
	int LastEnd, ThisEnd;			// Ending column of run
	int LastColor, ThisColor;		// Color of run
	
	int LastIndex, ThisIndex;		// Which run are we up to
	int LastIndexCount, ThisIndexCount;	// Out of these runs
	int LastRegionNum, ThisRegionNum;	// Which assignment
	int *LastRegion;				// Row assignment of region number
	int *ThisRegion;		// Row assignment of region number
	
	int LastOffset = -(Trans + 2);	// For performance to avoid multiplication
	int ThisOffset = 0;				// For performance to avoid multiplication
	int ComputeData;

	CvPoint actualedge;
	uchar imagevalue;
	bool CandidatExterior = false;

	// apuntadors als blobs de la regi?actual i last
	CBlob *regionDataThisRegion, *regionDataLastRegion;
	
	LastRegion=new int[Cols+2];
	ThisRegion=new int[Cols+2];

	for(i = 0; i < Cols + 2; i++)	// Initialize result arrays
	{
		LastRegion[i] = -1;
		ThisRegion[i] = -1;
	}

	//create the external blob
	RegionData.push_back( new CBlob() );
	SubsumedRegion = NewSubsume(SubsumedRegion,0);
	RegionData[0]->Parent = -1;
	RegionData[0]->Area = (double) Transition[0];
	RegionData[0]->Perimeter = (double) (2 + 2 * Transition[0]);

	ThisIndexCount = 1;
	ThisRegion[0] = 0;	// Border region

	// beginning of the image 
	// en cada linia, pimage apunta al primer pixel de la fila
	pImage = inputImage->imageData - 1 + startCol + startRow * inputImage->widthStep;
	//the mask should be the same size as image Roi, so don't take into account the offset
	if(maskImage!=NULL) pMask = maskImage->imageData - 1;

	char *pImageAux, *pMaskAux;
	
	// Loop over all rows
	for(ThisRow = 1; ThisRow < Rows + 2; ThisRow++)
	{
		//cout << "========= THIS ROW = " << ThisRow << endl;	// for debugging
		ThisOffset += Trans + 2;
		ThisIndex = 0;
		LastOffset += Trans + 2;;
		LastRow = ThisRow - 1;
		LastIndexCount = ThisIndexCount;
		LastIndex = 0;

		int EndLast = 0;
		int EndThis = 0;

		for(int j = 0; j < Trans + 2; j++)
		{
			int Index = ThisOffset + j;
			int TranVal = Transition[Index];
			if(TranVal > 0) ThisIndexCount = j + 1;	// stop at highest 

			if(ThisRegion[j] == -1)  { EndLast = 1; }
			if(TranVal < 0) { EndThis = 1; }

			if(EndLast > 0 && EndThis > 0) { break; }

			LastRegion[j] = ThisRegion[j];
			ThisRegion[j] = -1;		// Flag indicates region is not initialized
		}

		int MaxIndexCount = LastIndexCount;
		if(ThisIndexCount > MaxIndexCount) MaxIndexCount = ThisIndexCount;

		// Main loop over runs within Last and This rows
		while (LastIndex < LastIndexCount && ThisIndex < ThisIndexCount)
		{
			ComputeData = 0;
		
			if(LastIndex == 0) LastStart = 0;
			else LastStart = Transition[LastOffset + LastIndex - 1];
			LastEnd = Transition[LastOffset + LastIndex] - 1;
			LastColor = LastIndex - 2 * (LastIndex / 2);
			LastRegionNum = LastRegion[LastIndex];

			regionDataLastRegion = RegionData[LastRegionNum];

			
			if(ThisIndex == 0) ThisStart = 0;
			else ThisStart = Transition[ThisOffset + ThisIndex - 1];
			ThisEnd = Transition[ThisOffset + ThisIndex] - 1;
			ThisColor = ThisIndex - 2 * (ThisIndex / 2);
			ThisRegionNum = ThisRegion[ThisIndex];

			if( ThisRegionNum >= 0 )
				regionDataThisRegion = RegionData[ThisRegionNum];
			else
				regionDataThisRegion = NULL;


			// blobs externs
			CandidatExterior = false;
			if( 
#if !IMATGE_CICLICA_VERTICAL
				ThisRow == 1 || ThisRow == Rows ||
#endif
#if !IMATGE_CICLICA_HORITZONTAL
				ThisStart <= 1 || ThisEnd >= Cols || 
#endif				
				GetExternPerimeter( ThisStart, ThisEnd, ThisRow, inputImage->width, inputImage->height, imatgePerimetreExtern )
				)
			{
				CandidatExterior = true;
			}
			
			int TestA = (LastEnd < ThisStart - 1);	// initially false
			int TestB = (ThisEnd < LastStart);		// initially false
			int TestC = (LastStart < ThisStart);	// initially false
			int TestD = (ThisEnd < LastEnd);
			int TestE = (ThisEnd == LastEnd);

			int TestMatch = (ThisColor == LastColor);		// initially true
			int TestKnown = (ThisRegion[ThisIndex] >= 0);	// initially false

			int Case = 0;
			if(TestA) Case = 1;
			else if(TestB) Case = 8;
			else if(TestC)
			{
				if(TestD) Case = 3;
				else if(!TestE) Case = 2;
				else Case = 4;
			}
			else
			{
				if(TestE) Case = 5;
				else if(TestD) Case = 7;
				else Case = 6;
			}

			// Initialize common variables
			ThisArea = (float) 0.0;

			if(findmoments)
			{
				Thisu10 = Thisu01 = (float) 0.0;
				Thisu20 = Thisu02 = Thisu11 = (float) 0.0;
			}
			ThisMinX = ThisMinY = (float) 1000000.0;
			ThisMaxX = ThisMaxY = (float) -1.0;

			LastPerimeter = ThisPerimeter = (float) 0.0;
			ThisParent = (float) -1;
			ThisExternPerimeter = 0.0;

			// Determine necessary action and take it
			switch (Case)
			{ 
				case 1: //|xxx    |
						//|    yyy|
					
					ThisRegion[ThisIndex] = ThisRegionNum;
					LastRegion[LastIndex] = LastRegionNum;
					LastIndex++;
					
					//afegim la cantonada a LastRegion
					actualedge.x = ThisEnd;
					actualedge.y = ThisRow - 1;
					cvSeqPush(regionDataLastRegion->Edges,&actualedge);

					//afegim la cantonada a ThisRegion
					actualedge.x = ThisStart - 1;
					actualedge.y = ThisRow - 1;
					cvSeqPush(regionDataThisRegion->Edges,&actualedge);
					
					break;
					
					
				case 2: //|xxxxoo |
						//|    yyy|

					if(TestMatch)	// Same color
					{
						ThisRegionNum = LastRegionNum;
						regionDataThisRegion = regionDataLastRegion;

						ThisArea = ThisEnd - ThisStart + 1;
						LastPerimeter = LastEnd - ThisStart + 1;	// to subtract
						ThisPerimeter = 2 + 2 * ThisArea - LastPerimeter +
										PERIMETRE_DIAGONAL*2;

						if( CandidatExterior )
						{
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );
							ThisExternPerimeter += PERIMETRE_DIAGONAL*2;
						}
						ComputeData = 1;
					}

					//afegim la cantonada a ThisRegion
					if(ThisRegionNum!=-1)
					{
						// afegim dos vertexs si són diferents, només
						if(ThisStart - 1 != ThisEnd)
						{
							actualedge.x = ThisStart - 1;
							actualedge.y = ThisRow - 1;
							cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						}
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataThisRegion->Edges,&actualedge);
					}
					//afegim la cantonada a ThisRegion
					if(LastRegionNum!=-1 && LastRegionNum != ThisRegionNum )
					{
						// afegim dos vertexs si són diferents, només
						if(ThisStart - 1 != ThisEnd)
						{
							actualedge.x = ThisStart - 1;
							actualedge.y = ThisRow - 1;
							cvSeqPush(regionDataLastRegion->Edges,&actualedge);
						}
					}

					ThisRegion[ThisIndex] = ThisRegionNum;
					LastRegion[LastIndex] = LastRegionNum;
					LastIndex++;
					break;
					
					
				case 3: //|xxxxxxx|
						//|  yyyy |

					if(TestMatch)	// Same color
					{
						ThisRegionNum = LastRegionNum;
						regionDataThisRegion = regionDataLastRegion;

						ThisArea = ThisEnd - ThisStart + 1;
						LastPerimeter = ThisArea;	// to subtract
						ThisPerimeter = 2 + ThisArea + PERIMETRE_DIAGONAL*2;
						if( CandidatExterior )
						{
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );

							ThisExternPerimeter += PERIMETRE_DIAGONAL * 2;
						}
					}
					else		// Different color => New region
					{
						ThisParent = LastRegionNum;
						ThisRegionNum = ++HighRegionNum;
						ThisArea = ThisEnd - ThisStart + 1;
						ThisPerimeter = 2 + 2 * ThisArea;
						RegionData.push_back( new CBlob() );
						regionDataThisRegion = RegionData.back();

						SubsumedRegion = NewSubsume(SubsumedRegion,HighRegionNum);
						if( CandidatExterior )
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );

					}

					if(ThisRegionNum!=-1)
					{
						//afegim la cantonada a la regio
						actualedge.x = ThisStart - 1;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						//afegim la cantonada a la regio
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataThisRegion->Edges,&actualedge);
					}
					// si hem creat un nou blob, afegim tb a l'anterior
					if(!TestMatch && LastRegionNum!=-1 && LastRegionNum != ThisRegionNum )
					{
						//afegim la cantonada a la regio
						actualedge.x = ThisStart - 1;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataLastRegion->Edges,&actualedge);
						//afegim la cantonada a la regio
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataLastRegion->Edges,&actualedge);
					}
					
					ThisRegion[ThisIndex] = ThisRegionNum;
					LastRegion[LastIndex] = LastRegionNum;
					ComputeData = 1;
					ThisIndex++;
					break;
					
					
				case 4:	//|xxxxxxx|
						//|  yyyyy|
					
					if(TestMatch)	// Same color
					{
						ThisRegionNum = LastRegionNum;
						regionDataThisRegion = regionDataLastRegion;
						ThisArea = ThisEnd - ThisStart + 1;
						LastPerimeter = ThisArea;	// to subtract
						ThisPerimeter = 2 + ThisArea + PERIMETRE_DIAGONAL;
						if( CandidatExterior )
						{
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );

							ThisExternPerimeter += PERIMETRE_DIAGONAL;
						}
					}
					else		// Different color => New region
					{
						ThisParent = LastRegionNum;
						ThisRegionNum = ++HighRegionNum;
						ThisArea = ThisEnd - ThisStart + 1;
						ThisPerimeter = 2 + 2 * ThisArea;
						RegionData.push_back( new CBlob() );
						regionDataThisRegion = RegionData.back();
						SubsumedRegion = NewSubsume(SubsumedRegion,HighRegionNum);
						if( CandidatExterior )
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );

					}
					
					if(ThisRegionNum!=-1)
					{
						//afegim la cantonada a la regio
						actualedge.x = ThisStart - 1;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataThisRegion->Edges,&actualedge);
					}
					// si hem creat un nou blob, afegim tb a l'anterior
					if(!TestMatch && LastRegionNum!=-1 && LastRegionNum != ThisRegionNum )
					{
						actualedge.x = ThisStart - 1;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataLastRegion->Edges,&actualedge);
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataLastRegion->Edges,&actualedge);
					}
					
					ThisRegion[ThisIndex] = ThisRegionNum;
					LastRegion[LastIndex] = LastRegionNum;
					ComputeData = 1;
					
#ifdef B_CONNECTIVITAT_8
					if( TestMatch )
					{
						LastIndex++;
						ThisIndex++;
					}
					else
					{
						LastIndex++;	
					}
#else
					LastIndex++;
					ThisIndex++;
#endif					
					break;
					
					
				case 5:	//|ooxxxxx|
						//|yyyyyyy|

					if(!TestMatch && !TestKnown)	// Different color and unknown => new region
					{
						ThisParent = LastRegionNum;
						ThisRegionNum = ++HighRegionNum;
						ThisArea = ThisEnd - ThisStart + 1;
						ThisPerimeter = 2 + 2 * ThisArea;
						RegionData.push_back( new CBlob() );
						regionDataThisRegion = RegionData.back();
						SubsumedRegion = NewSubsume(SubsumedRegion,HighRegionNum);
						if( CandidatExterior )
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );

					}
					else if(TestMatch && !TestKnown)	// Same color and unknown
					{
						ThisRegionNum = LastRegionNum;
						regionDataThisRegion = regionDataLastRegion;
						ThisArea = ThisEnd - ThisStart + 1;
						LastPerimeter = LastEnd - LastStart + 1;	// to subtract
						ThisPerimeter = 2 + 2 * ThisArea - LastPerimeter 
										+ PERIMETRE_DIAGONAL * (LastStart != ThisStart);
						if( CandidatExterior )
						{
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );


							ThisExternPerimeter += PERIMETRE_DIAGONAL * (LastStart != ThisStart);
						}
						ComputeData = 1;
					}
					else if(TestMatch && TestKnown)	// Same color and known
					{
						LastPerimeter = LastEnd - LastStart + 1;	// to subtract
						//ThisPerimeter = - LastPerimeter;
						ThisPerimeter = - 2 * LastPerimeter 
										+ PERIMETRE_DIAGONAL * (LastStart != ThisStart);
						
						if(ThisRegionNum > LastRegionNum)
						{
							Subsume(RegionData, HighRegionNum, SubsumedRegion, regionDataThisRegion, regionDataLastRegion, 
									findmoments, ThisRegionNum, LastRegionNum );
							for(int iOld = 0; iOld < MaxIndexCount; iOld++)
							{
								if(ThisRegion[iOld] == ThisRegionNum) ThisRegion[iOld] = LastRegionNum;
								if(LastRegion[iOld] == ThisRegionNum) LastRegion[iOld] = LastRegionNum;
							}					
							ThisRegionNum = LastRegionNum;
						}
						else if(ThisRegionNum < LastRegionNum)
						{
							Subsume(RegionData, HighRegionNum, SubsumedRegion, regionDataLastRegion, regionDataThisRegion, 
									findmoments, LastRegionNum, ThisRegionNum );

							for(int iOld = 0; iOld < MaxIndexCount; iOld++)
							{
								if(ThisRegion[iOld] == LastRegionNum) ThisRegion[iOld] = ThisRegionNum;
								if(LastRegion[iOld] == LastRegionNum) LastRegion[iOld] = ThisRegionNum;
							}					
							LastRegionNum = ThisRegionNum;
						}
					}

					
					if(ThisRegionNum!=-1)
					{
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataThisRegion->Edges,&actualedge);

						if( ThisStart - 1 != LastEnd )
						{
							//afegim la cantonada a la regio
							actualedge.x = ThisStart - 1;
							actualedge.y = ThisRow - 1;
							cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						}
					}
					// si hem creat un nou blob, afegim tb a l'anterior
					if(!TestMatch && LastRegionNum!=-1 && LastRegionNum != ThisRegionNum )
					{
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataLastRegion->Edges,&actualedge);
					}

					ThisRegion[ThisIndex] = ThisRegionNum;
					LastRegion[LastIndex] = LastRegionNum;
					
#ifdef B_CONNECTIVITAT_8
					if( TestMatch )
					{
						LastIndex++;
						ThisIndex++;
					}
					else
					{
						LastIndex++;	
					}
#else
					LastIndex++;
					ThisIndex++;
#endif	
					break;
					
					
				case 6:	//|ooxxx  |
						//|yyyyyyy|

					if(TestMatch && !TestKnown)
					{
						ThisRegionNum = LastRegionNum;
						regionDataThisRegion = regionDataLastRegion;
						ThisArea = ThisEnd - ThisStart + 1;
						LastPerimeter = LastEnd - LastStart + 1;	// to subtract
						ThisPerimeter = 2 + 2 * ThisArea - LastPerimeter
										+ PERIMETRE_DIAGONAL + PERIMETRE_DIAGONAL * (ThisStart!=LastStart);
						if( CandidatExterior )
						{
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );


							ThisExternPerimeter += PERIMETRE_DIAGONAL + PERIMETRE_DIAGONAL * (ThisStart!=LastStart);
						}
						ComputeData = 1;
					}
					else if(TestMatch && TestKnown)
					{
						LastPerimeter = LastEnd - LastStart + 1;	// to subtract
						//ThisPerimeter = - LastPerimeter;
						ThisPerimeter = - 2 * LastPerimeter
										+ PERIMETRE_DIAGONAL + PERIMETRE_DIAGONAL * (ThisStart!=LastStart);
						
						if(ThisRegionNum > LastRegionNum)
						{
							Subsume(RegionData, HighRegionNum, SubsumedRegion, regionDataThisRegion, regionDataLastRegion, 
									findmoments, ThisRegionNum, LastRegionNum );
							for(int iOld = 0; iOld < MaxIndexCount; iOld++)
							{
								if(ThisRegion[iOld] == ThisRegionNum) ThisRegion[iOld] = LastRegionNum;
								if(LastRegion[iOld] == ThisRegionNum) LastRegion[iOld] = LastRegionNum;
							}					
							ThisRegionNum = LastRegionNum;
						}
						else if(ThisRegionNum < LastRegionNum)
						{
							Subsume(RegionData, HighRegionNum, SubsumedRegion, regionDataLastRegion, regionDataThisRegion, 
									findmoments, LastRegionNum, ThisRegionNum );
							for(int iOld = 0; iOld < MaxIndexCount; iOld++)
							{
								if(ThisRegion[iOld] == LastRegionNum) ThisRegion[iOld] = ThisRegionNum;
								if(LastRegion[iOld] == LastRegionNum) LastRegion[iOld] = ThisRegionNum;
							}					
							LastRegionNum = ThisRegionNum;
						}
					}

					
					if(ThisRegionNum!=-1)
					{
						//afegim la cantonada a la regio
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						if( ThisStart - 1 != LastEnd )
						{
							actualedge.x = ThisStart - 1;
							actualedge.y = ThisRow - 1;
							cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						}
					}
					// si hem creat un nou blob, afegim tb a l'anterior
					if(!TestMatch && LastRegionNum!=-1 && LastRegionNum != ThisRegionNum )
					{
						//afegim la cantonada a la regio
						if( ThisStart - 1 != LastEnd )
						{
							actualedge.x = ThisStart - 1;
							actualedge.y = ThisRow - 1;
							cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						}
					}					

					ThisRegion[ThisIndex] = ThisRegionNum;
					LastRegion[LastIndex] = LastRegionNum;
					LastIndex++;
					break;
					
					
				case 7:	//|ooxxxxx|
						//|yyyy   |

					if(!TestMatch && !TestKnown)	// Different color and unknown => new region
					{
						ThisParent = LastRegionNum;
						ThisRegionNum = ++HighRegionNum;
						ThisArea = ThisEnd - ThisStart + 1;
						ThisPerimeter = 2 + 2 * ThisArea;
						RegionData.push_back( new CBlob() );
						regionDataThisRegion = RegionData.back();
						SubsumedRegion = NewSubsume(SubsumedRegion,HighRegionNum);
						if( CandidatExterior )
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );

					}
					else if(TestMatch && !TestKnown)
					{
						ThisRegionNum = LastRegionNum;
						regionDataThisRegion = regionDataLastRegion;
						ThisArea = ThisEnd - ThisStart + 1;
						ThisPerimeter = 2 + ThisArea;
						LastPerimeter = ThisEnd - LastStart + 1;
						ThisPerimeter = 2 + 2 * ThisArea - LastPerimeter
										+ PERIMETRE_DIAGONAL + PERIMETRE_DIAGONAL * (ThisStart!=LastStart);
						if( CandidatExterior )
						{
							ThisExternPerimeter = GetExternPerimeter( ThisStart, ThisEnd, ThisRow, 
																	  inputImage->width, inputImage->height, 
																	  imatgePerimetreExtern );

							ThisExternPerimeter += PERIMETRE_DIAGONAL + PERIMETRE_DIAGONAL * (ThisStart!=LastStart);
						}
						ComputeData = 1;
					}
					else if(TestMatch && TestKnown)
					{
						LastPerimeter = ThisEnd - LastStart + 1;	// to subtract
						//ThisPerimeter = - LastPerimeter;
						ThisPerimeter = - 2 * LastPerimeter
										+ PERIMETRE_DIAGONAL + PERIMETRE_DIAGONAL * (ThisStart!=LastStart);
						
						if(ThisRegionNum > LastRegionNum)
						{
							Subsume(RegionData, HighRegionNum, SubsumedRegion, regionDataThisRegion, regionDataLastRegion, 
									findmoments, ThisRegionNum, LastRegionNum );
							for(int iOld = 0; iOld < MaxIndexCount; iOld++)
							{
								if(ThisRegion[iOld] == ThisRegionNum) ThisRegion[iOld] = LastRegionNum;
								if(LastRegion[iOld] == ThisRegionNum) LastRegion[iOld] = LastRegionNum;
							}					
							ThisRegionNum = LastRegionNum;
						}
						else if(ThisRegionNum < LastRegionNum)
						{
							Subsume(RegionData, HighRegionNum, SubsumedRegion, regionDataLastRegion, regionDataThisRegion, 
									findmoments, LastRegionNum, ThisRegionNum );
							for(int iOld = 0; iOld < MaxIndexCount; iOld++)
							{
								if(ThisRegion[iOld] == LastRegionNum) ThisRegion[iOld] = ThisRegionNum;
								if(LastRegion[iOld] == LastRegionNum) LastRegion[iOld] = ThisRegionNum;
							}					
							LastRegionNum = ThisRegionNum;
						}
					}

					if(ThisRegionNum!=-1)
					{
						//afegim la cantonada a la regio
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						if( ThisStart - 1 != LastEnd )
						{
							actualedge.x = ThisStart - 1;
							actualedge.y = ThisRow - 1;
							cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						}
					}
					// si hem creat un nou blob, afegim tb a l'anterior
					if(!TestMatch && LastRegionNum!=-1 && LastRegionNum != ThisRegionNum )
					{
						//afegim la cantonada a la regio
						actualedge.x = ThisEnd;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataLastRegion->Edges,&actualedge);
						if( ThisStart - 1 != LastEnd )
						{
							actualedge.x = ThisStart - 1;
							actualedge.y = ThisRow - 1;
							cvSeqPush(regionDataThisRegion->Edges,&actualedge);
						}
					}

					ThisRegion[ThisIndex] = ThisRegionNum;
					LastRegion[LastIndex] = LastRegionNum;
					ThisIndex++;
					break;
					
				case 8:	//|    xxx|
						//|yyyy   |
					
#ifdef B_CONNECTIVITAT_8					
					// fusionem blobs
					if( TestMatch )
					{
						if(ThisRegionNum > LastRegionNum)
						{
							Subsume(RegionData, HighRegionNum, SubsumedRegion, regionDataThisRegion, regionDataLastRegion, 
									findmoments, ThisRegionNum, LastRegionNum );
							for(int iOld = 0; iOld < MaxIndexCount; iOld++)
							{
								if(ThisRegion[iOld] == ThisRegionNum) ThisRegion[iOld] = LastRegionNum;
								if(LastRegion[iOld] == ThisRegionNum) LastRegion[iOld] = LastRegionNum;
							}					
							ThisRegionNum = LastRegionNum;
						}
						else if(ThisRegionNum < LastRegionNum)
						{
							Subsume(RegionData, HighRegionNum, SubsumedRegion, regionDataLastRegion, regionDataThisRegion, 
									findmoments, LastRegionNum, ThisRegionNum );
							for(int iOld = 0; iOld < MaxIndexCount; iOld++)
							{
								if(ThisRegion[iOld] == LastRegionNum) ThisRegion[iOld] = ThisRegionNum;
								if(LastRegion[iOld] == LastRegionNum) LastRegion[iOld] = ThisRegionNum;
							}					
							LastRegionNum = ThisRegionNum;
						}

						regionDataThisRegion->Perimeter = regionDataThisRegion->Perimeter + PERIMETRE_DIAGONAL*2;
					}
#endif

					if(ThisRegionNum!=-1)
					{
						//afegim la cantonada a la regio
						actualedge.x = ThisStart - 1;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataThisRegion->Edges,&actualedge);
					}
#ifdef B_CONNECTIVITAT_8					
					// si hem creat un nou blob, afegim tb a l'anterior
					if(!TestMatch && LastRegionNum!=-1 && LastRegionNum != ThisRegionNum )
					{
#endif					
						//afegim la cantonada a la regio
						actualedge.x = ThisStart - 1;
						actualedge.y = ThisRow - 1;
						cvSeqPush(regionDataLastRegion->Edges,&actualedge);
#ifdef B_CONNECTIVITAT_8
					}
#endif

					ThisRegion[ThisIndex] = ThisRegionNum;
					LastRegion[LastIndex] = LastRegionNum;
					ThisIndex++;
#ifdef B_CONNECTIVITAT_8					
					LastIndex--;
#endif
					break;
					
				default:
					ErrorFlag = -1;
			}	// end switch case

			// calculate the blob moments and mean gray level of the current blob (ThisRegionNum)
			if(ComputeData > 0)
			{
				// compute blob moments if necessary
				if(findmoments)
				{
					float ImageRow = (float) (ThisRow - 1);

					for(int k = ThisStart; k <= ThisEnd; k++)
					{
						Thisu10 += (float) (k - 1);
						Thisu20 += (float) (k - 1) * (k - 1);
					}
					
					Thisu11 = Thisu10 * ImageRow;
					Thisu01 = ThisArea * ImageRow;
					Thisu02 = Thisu01 * ImageRow;
					
				}

				// compute the mean gray level and its std deviation 
				if(ThisRow <= Rows )
				{
					pImageAux = pImage + ThisStart;
					if(maskImage!=NULL) pMaskAux = pMask + ThisStart;
					for(int k = ThisStart; k <= ThisEnd; k++)
					{
						if((k>0) && (k <= Cols))
						{
							if( maskImage!= NULL)
							{
								// només es t?en compte el valor del píxel de la
								// imatge que queda dins de la màscara
								// (de pas, comptem el nombre de píxels de la màscara)
								if( ((unsigned char) *pMaskAux) != PIXEL_EXTERIOR )
								{
									imagevalue = (unsigned char) (*pImageAux);
									regionDataThisRegion->Mean+=imagevalue;
									regionDataThisRegion->StdDev+=imagevalue*imagevalue;
								}
								else
								{
									nombre_pixels_mascara++;
								}
							}
							else
							{
								imagevalue = (unsigned char) (*pImageAux);
								regionDataThisRegion->Mean+=imagevalue;
								regionDataThisRegion->StdDev+=imagevalue*imagevalue;

							}
						}
						pImageAux++;
						if(maskImage!=NULL) pMaskAux++;
					}
				}

				// compute the min and max values of X and Y
				if(ThisStart - 1 < (int) ThisMinX) ThisMinX = (float) (ThisStart - 1);
				if(ThisMinX < (float) 0.0) ThisMinX = (float) 0.0;
				if(ThisEnd > (int) ThisMaxX) ThisMaxX = (float) ThisEnd;

				if(ThisRow - 1 < ThisMinY) ThisMinY = ThisRow - 1;
				if(ThisMinY < (float) 0.0) ThisMinY = (float) 0.0;
				if(ThisRow > ThisMaxY) ThisMaxY = ThisRow;
			}

			// put the current results into RegionData
			if(ThisRegionNum >= 0)
			{
				if(ThisParent >= 0) { regionDataThisRegion->Parent = (int) ThisParent; }
				regionDataThisRegion->Label = ThisRegionNum;
				regionDataThisRegion->Area += ThisArea;
				regionDataThisRegion->Perimeter += ThisPerimeter;
				regionDataThisRegion->ExternPerimeter += ThisExternPerimeter;
				
				if(ComputeData > 0)
				{
					if(findmoments)
					{
						regionDataThisRegion->u10 += Thisu10;
						regionDataThisRegion->u01 += Thisu01;
						regionDataThisRegion->u20 += Thisu20;
						regionDataThisRegion->u02 += Thisu02;
						regionDataThisRegion->u11 += Thisu11;
					}
					regionDataThisRegion->Perimeter -= LastPerimeter;
					regionDataThisRegion->Minx=MIN(regionDataThisRegion->Minx,ThisMinX);
					regionDataThisRegion->Maxx=MAX(regionDataThisRegion->Maxx,ThisMaxX);
					regionDataThisRegion->Miny=MIN(regionDataThisRegion->Miny,ThisMinY);
					regionDataThisRegion->Maxy=MAX(regionDataThisRegion->Maxy,ThisMaxY);
				}
				// blobs externs
				if( CandidatExterior )
				{
					regionDataThisRegion->Exterior = true;
				}
			
			}
		}	// end Main loop

		if(ErrorFlag != 0) return false;
		// ens situem al primer pixel de la seguent fila
		pImage = inputImage->imageData - 1 + startCol + (ThisRow+startRow) * inputImage->widthStep;

		if(maskImage!=NULL)
			pMask = maskImage->imageData - 1 + ThisRow * maskImage->widthStep;
	}	// end Loop over all rows

	// eliminem l'àrea del marc
	// i tamb?els píxels de la màscara
	// ATENCIO: PERFER: el fet de restar el nombre_pixels_mascara del
	// blob 0 només ser?cert si la màscara t?contacte amb el marc.
	// Si no, s'haur?de trobar quin és el blob que cont?més píxels del
	// compte.
	RegionData[0]->Area -= ( Rows + 1 + Cols + 1 )*2 + nombre_pixels_mascara;

	// eliminem el perímetre de més:
	// - sense marc: 2m+2n (perímetre extern)
	// - amb marc:   2(m+2)+2(n+2) = 2m+2n + 8
	// (segurament no és del tot acurat)
	// (i amb les màscares encara menys...)
	RegionData[0]->Perimeter -= 8.0;

	vector<CBlob*>::iterator iti;
	CBlob *blobActual;

	if(findmoments)
	{
		iti = RegionData.begin();
		// Normalize summation fields into moments 
		for(ThisRegionNum = 0; ThisRegionNum <= HighRegionNum; ThisRegionNum++, iti++)
		{
			blobActual = *iti;

			if(!SubsumedRegion[ThisRegionNum])	// is a valid blob?
			{
				// Get averages
				blobActual->u10 /= blobActual->Area;
				blobActual->u01 /= blobActual->Area;
				blobActual->u20 /= blobActual->Area;
				blobActual->u02 /= blobActual->Area;
				blobActual->u11 /= blobActual->Area;

				// Create moments
				blobActual->u20 -= blobActual->u10 * blobActual->u10;
				blobActual->u02 -= blobActual->u01 * blobActual->u01;
				blobActual->u11 -= blobActual->u10 * blobActual->u01;
				if(blobActual->u11 > -1.0E-14 && blobActual->u11 < 1.0E-14)
				{
					blobActual->u11 = (float) 0.0; // Eliminate roundoff error
				}
			}			
		}
	}

	//Get the real mean and std deviation
	iti = RegionData.begin();
	for(ThisRegionNum = 0; ThisRegionNum <= HighRegionNum; ThisRegionNum++, iti++)
	{
		blobActual = *iti;
		if(!SubsumedRegion[ThisRegionNum])	// is a valid blob?
		{
			if(blobActual->Area > 1)
			{
				blobActual->StdDev =
									sqrt(
									(
									blobActual->StdDev * blobActual->Area -
									blobActual->Mean * blobActual->Mean 
									)/
									(blobActual->Area*(blobActual->Area-1))
									);
			}
			else
				blobActual->StdDev=0;
			
			if(blobActual->Area > 0)
				blobActual->Mean/=blobActual->Area;
			else
				blobActual->Mean = 0;
		}
	
	}

	// eliminem els blobs subsumats
	//blob_vector::iterator itBlobs = RegionData.begin() + HighRegionNum + 1;
	vector<CBlob*>::iterator itBlobs = RegionData.begin();

	ThisRegionNum = 0;
	while( itBlobs != RegionData.end() )
	{
		if(SubsumedRegion[ThisRegionNum])	// is not a valid blob?
		{
			delete *itBlobs;
			itBlobs = RegionData.erase( itBlobs );
		}
		else		
			itBlobs++;

		ThisRegionNum++;
	}

	free(SubsumedRegion);
	delete Transition;
	delete ThisRegion;
	delete LastRegion;

	if( imatgePerimetreExtern ) cvReleaseImage(&imatgePerimetreExtern);

	return true;
}
Example #18
0
void X(vector <double> &a)
{
  int i;

  while (!a.empty()) a.erase(a.begin());
}
Example #19
0
void BsVectorIntSet::remove(int item) {
    int ind = insertion_index(item);
    if(item_present(ind, item)) {
        vec.erase(vec.begin() + ind);
    }
}
Example #20
0
/*
==================================================================
// This is winmain, the main entry point for Windows applications
==================================================================
*/
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
	// Initialize the window
	if ( !initWindow( hInstance ) )
		return false;
	// called after creating the window
	if ( !d3dMgr->initD3DManager(wndHandle) )
		return false;
	if ( !d3dxSRMgr->initD3DXSpriteMgr(d3dMgr->getTheD3DDevice()))
		return false;
	//declare variables to measure the time between frames.
	// Grab the frequency of the high def timer
	__int64 freq = 0;				// measured in counts per second;
	QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
	float sPC = 1.0f / (float)freq;			// number of seconds per count

	__int64 currentTime = 0;				// current time measured in counts per second;
	__int64 previousTime = 0;				// previous time measured in counts per second;

	float numFrames   = 0.0f;				// Used to hold the number of frames
	float timeElapsed = 0.0f;				// cumulative elapsed time

	GetClientRect(wndHandle,&clientBounds);
	float fpsRate = 1000.0f/25.0f;
	/* initialize random seed: */
	srand ( (unsigned int)time(NULL) );

	scor=0;
	//Makes an instance of cD3DFont
	cD3DXFont* KnightFont = new cD3DXFont(d3dMgr->getTheD3DDevice(),hInstance, "Bats&Dragons-Abaddon");
	//These two rectangles will hold the text.
	RECT textPos;
	SetRect(&textPos, (clientBounds.right/2-30), (clientBounds.bottom/2), 800, 800);
	RECT buttonPos;
	SetRect(&buttonPos, (clientBounds.right/2-20), (clientBounds.bottom/2-20), 800, 800);
	D3DXVECTOR3 PlatformPos;
	D3DXVECTOR3 BatPos;
	/* generate random number of Platforms */
	int numPlatforms = (50);
	int numBat = (24);
	D3DXVECTOR3 knightPos;
	POINT pknightPos;
	cXAudio gStartSound;
	gStartSound.playSound(L"Sounds\\BarbossaIsHungry.wav",false);
	
	PlatformPos = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0);
	aPlatform.push_back(new cPlatform(PlatformPos,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png"));
	LPDIRECT3DSURFACE9 theBackbuffer = NULL;  // This will hold the back buffer
	SetRect(&buttonPos, (clientBounds.right/2-20), (clientBounds.bottom/2-20), 800, 800);

	MSG msg;
	ZeroMemory( &msg, sizeof( msg ) );

	// Create the background surface
	aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName);

	while( msg.message!=WM_QUIT )
	{
		// Check the message queue
		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) )
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		else
		{
			//Run once per frame until the application closes.
			//if the menu is active
			if (Menu==true && finish==false)
			{
				SetRect(&buttonPos, (clientBounds.right/2-20), (clientBounds.bottom/2-20), 800, 800);
				sprintf_s( gScore, 100, "");
				sprintf_s( gMenu, 100, "Start");
			}
			//if the level is active
			if (Menu==false)
			{
				sprintf_s( gScore, 50, "");
				sprintf_s( gMenu, 50, "");
			}
			//if starting is true
			if (start==true)
			{
				start=false;
				scor=0;
				Health=30;		
				reset the time frame.		
				currentTime = 0;				// current time measured in counts per second;
				previousTime = 0;				// previous time measured in counts per second;
				numFrames   = 0.0f;				// Used to hold the number of frames
				timeElapsed = 0.0f;				// cumulative elapsed time
				PlatformTrans = D3DXVECTOR2(300,300);
				BatTrans = D3DXVECTOR2(300,300);
				knightTrans = D3DXVECTOR2(250,230);
				//Create a knight sprite.
				knightPos = D3DXVECTOR3((float)clientBounds.left/2-200,clientBounds.bottom-360,0);
				gKnight.push_back(new cKnight(knightPos,d3dMgr->getTheD3DDevice(),"Images\\KnightBodytwo.png",1,11));
				//Create all the platforms.
				for(int loop = 0; loop < numPlatforms; loop++)
				{
					PlatformPos = D3DXVECTOR3(clientBounds.right/2-200+(loop*400),(float)clientBounds.bottom-100,0);
					aPlatform.push_back(new cPlatform(PlatformPos,d3dMgr->getTheD3DDevice(),"Images\\Platform.png"));
					aPlatform[loop]->setTranslation(D3DXVECTOR2(0.0f,0.0f));
				}
				//Create all the bats.
				for(int loop = 0; loop < numBat; loop++)
				{
					BatPos = D3DXVECTOR3(clientBounds.right/2+((loop+1)*800),(float)clientBounds.bottom-300,0);
					aBat.push_back(new cBat(BatPos,d3dMgr->getTheD3DDevice(),"Images\\BatFlipped.png"));
					aBat[loop]->setTranslation(D3DXVECTOR2(0.0f,0.0f));
				}
			}
			//if the finish screen is active
			if (Menu==true && finish==true)  
			{
				SetRect(&buttonPos, (clientBounds.right/2-45), (clientBounds.bottom/2-20), 800, 800);
				sprintf_s( gScore, 100, "Your total score was: %d",scor);
				sprintf_s( gMenu, 50, "Re-Play");
			}
			//Loop through all the remaining bats
			iterBat = aBat.begin();
			while(iterBat != aBat.end())
			{
				// update Bat
				list<cKnight*>::iterator bite = gKnight.begin();
				//if the current bat is touching the knight.
				if ((*iterBat)->collidedWith((*iterBat)->getBoundingRect(),(*bite)->getBoundingRect()))
				{
					Health-=10;
					expPos = D3DXVECTOR3((*iterBat)->getSpritePos2D().x+105.0f,(*iterBat)->getSpritePos2D().y+95.0f,0.0f);
					gExplode.push_back(new cExplosion(expPos,d3dMgr->getTheD3DDevice(),"Images\\explosionblood.png"));
					gExplodeSound.playSound(L"Sounds\\Splat.wav",false);
					iterBat = aBat.erase(iterBat);
					if (Health < 1)
					{
						//Deletes all the remaining bats.
						iterBat = aBat.begin();
						while (iterBat != aBat.end())
						{
							iterBat = aBat.erase(iterBat);
						}
						//Deletes all the platforms
						iter = aPlatform.begin();
						while (iter != aPlatform.end())
						{
							iter = aPlatform.erase(iter);
						}
						//Deletes .the Knight
						list<cKnight*>::iterator bite = gKnight.begin();
						bite = gKnight.erase(bite);
						//Places a button.
						PlatformPos = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0);
						aPlatform.push_back(new cPlatform(PlatformPos,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png"));
						//Sets the background to the finish screen.
						backgroundName="Images\\Background.png";
						aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName);
						Menu=true;
						finish=true;
						iterBat = aBat.end();
					}
				}
				if (iterBat!=aBat.end()){++iterBat;}
			}
			for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter)
			{
				(*iter)->update();	//loops through the platforms updating them.
			}
			QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
			dt = (currentTime - previousTime)*sPC;
			// Accumulate how much time has passed.
			timeElapsed = dt+timeElapsed;
			if(timeElapsed > fpsRate)
			{
				d3dMgr->beginRender();
				theBackbuffer = d3dMgr->getTheBackBuffer();
				
				d3dMgr->updateTheSurface(aSurface, theBackbuffer);
				d3dMgr->releaseTheBackbuffer(theBackbuffer);
				d3dxSRMgr->beginDraw();
				for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter)
				{
					//run for every platform.
					d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix());  
					d3dxSRMgr->drawSprite((*iter)->getTexture(),NULL,NULL,NULL,0xFFFFFFFF);
				}
				list<cKnight*>::iterator bite = gKnight.begin();
				int frog=0;
				float gravity=0;
				//work out how far the knight should fall.
				while(bite!=gKnight.end()){
					(*bite)->setSpritePos(knightPos);
					(*bite)->update(dt);
					d3dxSRMgr->setTheTransform((*bite)->getSpriteTransformMatrix());  
					d3dxSRMgr->drawSprite((*bite)->getTexture(),&((*bite)->getSourceRect()),NULL,NULL,0xFFFFFFFF);
					++bite;
					//Creates two ints pointOne and pointTwo these will store the start and end point of each platform.
					int pointOne=0;
					int pointTwo=0;
					float jump=100;
					iter = aPlatform.begin();
					//finds the x coordinate of the first platform
					float center = (*iter)->getSpritePos2D().x;
					pknightPos.x = knightTrans.x;
					pknightPos.y = knightTrans.y;
					for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter)	//run for each platform.
					{
						int king=center+(frog*400);
						//Work out the limits of the platforms
						pointOne=king-50;
						pointTwo=(king+232)-25;
						frog++;
						if (250>pointOne&&250<pointTwo)
						{
							gravity=315;
						}
					}
					if (knightPos.y<(clientBounds.top+jump)){falling=true;}
					if (knightPos.y<(clientBounds.bottom-gravity)){knightTrans.y += 30;}else{falling=false;}
					knightPos = D3DXVECTOR3(knightTrans.x,knightTrans.y,0);
					if(knightPos.y>clientBounds.bottom)
					{
						iterBat = aBat.begin();
						while (iterBat != aBat.end())
						{
							iterBat = aBat.erase(iterBat);
						}
						iter = aPlatform.begin();
						while (iter != aPlatform.end())
						{
							iter = aPlatform.erase(iter);
						}
						list<cKnight*>::iterator bite = gKnight.begin();
						bite = gKnight.erase(bite);

						PlatformPos = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0);
						aPlatform.push_back(new cPlatform(PlatformPos,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png"));
						backgroundName="Images\\Background.png";
						aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName);
						Menu=true;
						finish=true;
					}
					bite=gKnight.end();
				}
				for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat)
				{
					D3DXVECTOR2 show =(*iterBat)->getTranslation();
					(*iterBat)->update(dt);
					knightPos = D3DXVECTOR3(knightTrans.x,knightTrans.y,0);
					d3dxSRMgr->setTheTransform((*iterBat)->getSpriteTransformMatrix());  
					d3dxSRMgr->drawSprite((*iterBat)->getTexture(),&((*iterBat)->getSourceRect()),NULL,NULL,0xFFFFFFFF);
				}
				list<cExplosion*>::iterator iter = gExplode.begin();
				while(iter != gExplode.end())
				{
					if((*iter)->isActive() == false)
					{
						iter = gExplode.erase(iter);
						}
					else
					{
						(*iter)->update(dt);
						d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix());  
						d3dxSRMgr->drawSprite((*iter)->getTexture(),&((*iter)->getSourceRect()),NULL,NULL,0xFFFFFFFF);
						++iter;
					}
				}
				previousTime = currentTime;
				d3dxSRMgr->endDraw();
				KnightFont->printText(gScore,textPos);
				KnightFont->printText(gMenu,buttonPos);
			}
			d3dMgr->endRender();
		}
	}
	d3dxSRMgr->cleanUp();
	d3dMgr->clean();
	return (int) msg.wParam;
}
Example #21
0
// Fill filelist with info retrieved from the playlist
void ParsePLS(string listpath, vector<SPlaylistEntry> &filelist)
{
	char buf[1024] = {0};
	ifstream file(listpath.c_str(), ios_base::in);
	
	if(file.is_open())
	{
		// pls playlist file should start with the string "[playlist]"
		file.getline(buf, sizeof(buf));
		string str = buf;
		if(str.find("[playlist]") == string::npos)
		{
			return;
		}

		string pathroot = listpath.substr(0, listpath.find_last_of("\\") + 1);

		// Find number of entries
		int count = 0;
		while(!file.eof())
		{
			file.getline(buf, sizeof(buf));
			str = buf;
			if(str.find("NumberOfEntries") != string::npos)
			{
				count = atoi(str.substr(str.find_first_of("=") + 1).c_str());
				filelist.resize(count);
				break;
			}
		}

		if(count == 0) return;
		
		// Each entry in the playlist consists of three lines:
		//	File1=E:\Music\James Brown\20 all time greatest hits!\13 - Get On The Good Foot.mp3
		//	Title1=James Brown - Get On The Good Foot
		//	Length1=215
		// Streaming media should have length -1
		file.seekg(0);
		while(!file.eof())
		{
			file.getline(buf, sizeof(buf));
			string str = buf;

			if(str.empty()) continue;

			str = str.erase(str.find_last_of('\r')); // Winamp pls files have extra carriage returns which screw up file_exists()

			if(str.find("File") == 0)
			{
				str = str.substr(4); // Strip "File"
				int index = atoi(str.substr(0, str.find_first_of("=")).c_str()) - 1;

				if(index > -1 && index < count)
				{
					SPlaylistEntry &e = filelist.at(index);
					e.path = str.substr(str.find_first_of("=") + 1);

					// Make path absolute if not already
					if(e.path.find(':') == string::npos)
					{
						e.path.insert(0, pathroot);
					}
				}
			}
			else if(str.find("Title") == 0)
			{
				str = str.substr(5); // Strip "Title"
				int index = atoi(str.substr(0, str.find_first_of("=")).c_str()) - 1;

				if(index > -1 && index < count)
				{
					SPlaylistEntry &e = filelist.at(index);
					e.title = str.substr(str.find_first_of("=") + 1);
				}
			}
			else if(str.find("Length") == 0)
			{
				str = str.substr(6); // Strip "Length"
				int index = atoi(str.substr(0, str.find_first_of("=")).c_str()) - 1;

				if(index > -1 && index < count)
				{
					SPlaylistEntry &e = filelist.at(index);
					e.length = atoi(str.substr(str.find_first_of("=") + 1).c_str());
				}
			}
		}
	}

	// Remove streaming media
	vector<SPlaylistEntry>::iterator it = filelist.begin();
	while(it != filelist.end())
	{
		if(it->length < 0)
		{
			it = filelist.erase(it);
		}
		else
		{
			++it;
		}
	}

	file.close();
}
Example #22
0
/*
==================================================================
* LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
* LPARAM lParam)
* The window procedure
==================================================================
*/
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	// Check any available messages from the queue
	//This part of the code is activated by user inputs.
	switch (message)
	{
		//Used when a key is pressed
		case WM_KEYDOWN:
			{
				//When the level is active
				if(Menu==false){
					//if the escape key is pressed
					if (wParam ==VK_ESCAPE)
					{
						//Deletes all the remaining bats.
						iterBat = aBat.begin();
						while (iterBat != aBat.end())
						{
							iterBat = aBat.erase(iterBat);
						}
						iter = aPlatform.begin();
						//Deletes all of the platforms.
						while (iter != aPlatform.end())
						{
							iter = aPlatform.erase(iter);
						}
						//Deletes the knight.
						list<cKnight*>::iterator bite = gKnight.begin();
						bite = gKnight.erase(bite);
						//adds a button and changes the background.
						D3DXVECTOR3 PlatformPosing = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0);
						aPlatform.push_back(new cPlatform(PlatformPosing,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png"));
						backgroundName="Images\\Background.png";
						aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName);
						Menu=true;
						finish=true;
						return 0;
					}
					// if the left key is pressed
					if (wParam == VK_LEFT)
					{
						//Gives all of the platforms a velocity to the right.
						for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter)
						{
							if ((*iter)->getTranslation().x<10.0f)
							{
								(*iter)->setTranslation(D3DXVECTOR2(20.0f ,0.0f)); 
							}
						}
						//Gives all the remaining bats a velocity to the right.
						for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat)
						{
							if ((*iterBat)->getTranslation().x<10.0f)
							{
								(*iterBat)->setTranslation(D3DXVECTOR2(20.0f ,0.0f)); 
							}
						}
					}
					// if the right key is pressed
					if (wParam == VK_RIGHT)
					{
						//Gives all of the platforms a velocity to the left.
						for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter)
						{
							if ((*iter)->getTranslation().x>-10.0f)
							{
								(*iter)->setTranslation(D3DXVECTOR2(-20.0f ,0.0f)); 
							}
						}
						//Gives all the remaining bats a velocity to the left.
						for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat)
						{
							if ((*iterBat)->getTranslation().x>-10.0f)
							{
								(*iterBat)->setTranslation(D3DXVECTOR2(-20.0f ,0.0f)); 
							}
						}
					}
					 //if the up key is pressed and the knight is not falling
					if (wParam == VK_UP && !falling)
					{
						//Moves the knight up.
						knightTrans.y -= 50.0f;
					}
				}
				return 0;
			}
		//when the level is active.
		if (Menu==false){
			//when a key is released
			case WM_KEYUP:
			{
				//if the left key is lifted
				if (wParam ==VK_LEFT)
				{
						//Stops the platforms.
						for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter)
						{
								(*iter)->setTranslation(D3DXVECTOR2(0.0f ,0.0f)); 
						}
						//Stops the bats.
						for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat)
						{
								(*iterBat)->setTranslation(D3DXVECTOR2(0.0f ,0.0f)); 
						}
				}
				//if the right key is lifted
					if (wParam == VK_RIGHT)
					{
						//Stops the platforms.
						for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter)
						{
							(*iter)->setTranslation(D3DXVECTOR2(0.0f ,0.0f)); 
						}
						//Stops the bats.
						for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat)
						{
							(*iterBat)->setTranslation(D3DXVECTOR2(0.0f ,0.0f)); 
						}
					}
					//if the up key is lifted makes falling true.
					if (wParam == VK_UP){falling=true;}
				return 0;
			}
		}
		//when the left mouse button is clicked.
		case WM_LBUTTONDOWN:
		{
			POINT mousexy;		//The point that the mouse clicked is recorded
			mousexy.x = LOWORD(lParam);
			mousexy.y = HIWORD(lParam);
			//if menu is true and the point is within a defined area.
			if (Menu==true&&mousexy.x>(clientBounds.right/2-100)&&mousexy.x<(clientBounds.right/2+100)&&mousexy.y>(clientBounds.bottom/2-50)&&mousexy.y<(clientBounds.bottom/2+50))
			{
				if(finish==false)
				{
					//Deletes the button.
					iter = aPlatform.begin();
					while (iter != aPlatform.end())
					{
						iter = aPlatform.erase(iter);
					}
					//Applies the game background.
					 backgroundName="Images\\SkyBackgroundSmall.png";
					 aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName);
					 Menu=false;
					 start=true;
					 return 0;
				}
				if(finish==true)
				{
					//places a button.
					D3DXVECTOR3 PlatformPoser = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0);
					aPlatform.push_back(new cPlatform(PlatformPoser,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png"));
					//Sets the background to the menu screen.
					backgroundName="Images\\eulogyPlus.png";
					aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName);
					sprintf_s( gMenu, 50, "Play");
					sprintf_s( gScore, 100, "");
					finish=false;
					return 0;
				}
			}
			if (Menu==false)
			{
				iterBat = aBat.begin();
				while (iterBat != aBat.end())
				{
					//if the point is on a bat
					if ( (*iterBat)->insideRect((*iterBat)->getBoundingRect(),mousexy))
					{
						//Deletes the bat.
						iterBat = aBat.erase(iterBat);
						//make an explosion at the point clicked
						expPos = D3DXVECTOR3((float)mousexy.x-25,(float)mousexy.y-23, 0.0f);
						gExplode.push_back(new cExplosion(expPos,d3dMgr->getTheD3DDevice(),"Images\\explosionblood.png"));
						//Plays a splat sound effect.
						gExplodeSound.playSound(L"Sounds\\Splat.wav",false);
						scor+=10;
						iterBat = aBat.end();
					}
					else
					{

						++iterBat;
					}
				}
			}
			return 0;
		}
		//if the application has been closed.
		case WM_CLOSE:
			{
				// Posts close message
				PostQuitMessage(0);
				 return 0;
			}
		//f the application has been destroyed.
		case WM_DESTROY:
			{
				// Posts close message
				PostQuitMessage(0);
				return 0;
			}
	}
	// Always return the message to the default window
	// procedure for further processing
	return DefWindowProc(hWnd, message, wParam, lParam);
}
Example #23
0
int main(int argc, char** argv){
    int num_objects = 10;
    int num_moving = 5;
    string name;
    int x, y;
    char command;
    int t=1;
	
    Player player("player");
    Player player2("player2");
	
    //If at least one command-line argument was provided, use it as the number of objects to create.
    if (argc > 1) {
        num_objects = atoi(argv[1]);
    }
	
    if (argc > 2) {
        num_moving = atoi(argv[2]);
    }
	
    //Create all the non-moving objects
    for (int i = 0; i < num_objects - num_moving; i++) {
        x = random() % 11;
        y = random() % 11;
        
        name = "random object";
        if (i < 7) {
            name = names[i];
        }
		
        collection.push_back(new Object(name, x, y));
    }
	
    for (int i = 0; i < num_moving; i++) {
        x = random() % 11;
        y = random() % 11;
		
        name = "random moving object";
        if (i < 5) {
            name = moving_names[i];
        }
		
        collection.push_back(new Monster(name,x,y));
    }
		
    //Create weapons.
    for (int i = 0; i < 3; i++) {
        x = random() % 11;
        y = random() % 11;

        name = "weapon";
        if (i < 3) {
            name = weapon_names[i];
        }

        collection.push_back(new Weapon(name,x,y));
    }

    //Create armor.
    for (int i = 0; i < 3; i++) {
        x = random() % 11;
        y = random() % 11;

        name = "armor";
        if (i < 3) {
            name = armor_names[i];
        }

        collection.push_back(new Armor(name,x,y));
    }

    do{ 
		
	
		
	while(t==1){
		cout << "__________________________________________________"<<endl;
		cout << "Player 1" << endl;
		cout << "[" << player.x() << ", " << player.y() << "]" << endl;
		cout << "Your score is: " << player.score() << endl;
		cout << "________________________________________"<<endl;
	        cout << "Enter a command:" << endl;
                cout << "   'i' to move up." << endl;
                cout << "   'm' to move down." << endl;
                cout << "   'j' to move left." << endl;
                cout << "   'k' to move right." << endl;
		cout << "   't' to take an item from this room." << endl;
		cout << "   'a' to attack a monster in this room." << endl;
                cout << "   'q' to quit." << endl;
		cout << "__________________________________________________"<<endl;
		
        //Process command and move player.
        cin >> command;
		
        switch (command) {
            case 'i':
                player.move_up();
                break;
            case 'm':
                player.move_down();
                break;
            case 'j':
                player.move_left();
                break;
            case 'k':
                player.move_right();
                break;
			case 't':
				for (vector<Object*>::iterator i=collection.begin(); i != collection.end(); ) {
					if ((*i)->x() == player.x() && (*i)->y() == player.y()) {
					    Weapon* weap = dynamic_cast<Weapon*>(*i);
					    Armor* arm = dynamic_cast<Armor*>(*i);
					    if (weap){
					        cout << "You inspect the " << weap->name() << "." << endl;
						if (player.get_str() < weap->str()) {
						    player.set_weapon(weap);
						    cout << "You pick up the " << weap->name() << " and equip it." << endl;
						    i = collection.erase(i);
						} else {
						    cout << "You realize the " << weap->name() << " is worse than your " << player.get_weapon() << " so you destory it." << endl;
						    i = collection.erase(i);
						}
                                            }
					    if (arm){
					        cout << "You inspect the " << arm->name() << "." << endl;
						if (player.get_tgh() < arm->tgh()) {
						    player.set_armor(arm);
						    cout << "You pick up the " << arm->name() << " and equip it." << endl;
						    i = collection.erase(i);
						} else {
						    cout << "The " << arm->name() << " is worse than your " << player.get_armor() << " so you destroy it." << endl;
						    i = collection.erase(i);
						  }
                                                }
					    if (player.take_item(*i)) {
					    	cout << "You take a " << (*i)->name() << endl;
						i = collection.erase(i);
					    }
					    else {
						i++;
					    }
					} else {
						i++;
					    
					}
                                        break;
				}
			case 'a':
				for (vector<Object*>::iterator i=collection.begin(); i != collection.end(); ) {
					if ((*i)->x() == player.x() && (*i)->y() == player.y()) {
						Monster* mon = dynamic_cast<Monster*>(*i);
						if (mon){
								cout << "What do you do?" << endl;
								cout << "'a' for a normal attack." << endl;
								cout << "'s' for a special attack." << endl;
								cin >> command;
								switch (command) {
								    case 'a':
								        cout << "You attack " << mon->name() << endl;
								        if (random() % 2 == 0) {
									    cout << mon->name() << " wins!  You lose" << (5 - player.get_tgh()) << "  health." << endl;
									        if (player.hurt_player(5 - player.get_tgh()) == false) {
										    cout << "You have died!" << endl;
										    return 1;
									        }
									    i++;
									
								        }
								        else {
									    cout << "You win!  " << mon->name() << " loses " << (5 + player.get_str()) << " health." << endl;
									    if (mon->hurt_monster(5 + player.get_str()) == false) {
										cout << "You have killed the monster!" << endl;
										i = collection.erase(i);
										player.give_bonus(10);
									    }
								        }
								    case 's':
								        cout << "You use a special attack on " << mon->name() << endl;
								        if (random() % 10 >= 3) {
									    cout << mon->name() << " wins!  You lose " << (5 - player.get_tgh()) << " health." << endl;
									        if (player.hurt_player(5 - player.get_tgh()) == false) {
										    cout << "You have died!" << endl;
										    return 1;
									        }
									    i++;
									
								        }
								        else {
									    cout << "Your special attack hits!  " << mon->name() << " loses " << (10 + player.get_str()) << " health." << endl;
									    if (mon->hurt_monster(10 + player.get_str()) == false) {
										cout << "You have killed the monster!" << endl;
										i = collection.erase(i);
										player.give_bonus(10);
									    }
								        }
								}
							}
						else 
							i++;
						   
											}
					else 
						i++;
					    
						
					
				}
            default:
                break;
		}
Example #24
0
void Unique(vector<T> &v){
  sort(all(v));
  v.erase(all(v),v.end());
}
Example #25
0
File: 0296.cpp Project: nocotan/AOJ
template<typename C> void remove(vector<C>& c, unsigned int index) { c.erase(c.begin()+index); }
Example #26
0
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
    CAutoBN_CTX pctx;
    CScript::const_iterator pc = script.begin();
    CScript::const_iterator pend = script.end();
    CScript::const_iterator pbegincodehash = script.begin();
    opcodetype opcode;
    valtype vchPushValue;
    vector<bool> vfExec;
    vector<valtype> altstack;
    if (script.size() > 10000)
        return false;
    int nOpCount = 0;


    try
    {
        while (pc < pend)
        {
            bool fExec = !count(vfExec.begin(), vfExec.end(), false);

            //
            // Read instruction
            //
            if (!script.GetOp(pc, opcode, vchPushValue))
                return false;
            if (vchPushValue.size() > 520)
                return false;
            if (opcode > OP_16 && ++nOpCount > 201)
                return false;

            if (opcode == OP_CAT ||
                opcode == OP_SUBSTR ||
                opcode == OP_LEFT ||
                opcode == OP_RIGHT ||
                opcode == OP_INVERT ||
                opcode == OP_AND ||
                opcode == OP_OR ||
                opcode == OP_XOR ||
                opcode == OP_2MUL ||
                opcode == OP_2DIV ||
                opcode == OP_MUL ||
                opcode == OP_DIV ||
                opcode == OP_MOD ||
                opcode == OP_LSHIFT ||
                opcode == OP_RSHIFT)
                return false;

            if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
                stack.push_back(vchPushValue);
            else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
            switch (opcode)
            {
                //
                // Push value
                //
                case OP_1NEGATE:
                case OP_1:
                case OP_2:
                case OP_3:
                case OP_4:
                case OP_5:
                case OP_6:
                case OP_7:
                case OP_8:
                case OP_9:
                case OP_10:
                case OP_11:
                case OP_12:
                case OP_13:
                case OP_14:
                case OP_15:
                case OP_16:
                {
                    // ( -- value)
                    CBigNum bn((int)opcode - (int)(OP_1 - 1));
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Control
                //
                case OP_NOP:
                case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
                case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
                break;

                case OP_IF:
                case OP_NOTIF:
                {
                    // <expression> if [statements] [else [statements]] endif
                    bool fValue = false;
                    if (fExec)
                    {
                        if (stack.size() < 1)
                            return false;
                        valtype& vch = stacktop(-1);
                        fValue = CastToBool(vch);
                        if (opcode == OP_NOTIF)
                            fValue = !fValue;
                        popstack(stack);
                    }
                    vfExec.push_back(fValue);
                }
                break;

                case OP_ELSE:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.back() = !vfExec.back();
                }
                break;

                case OP_ENDIF:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.pop_back();
                }
                break;

                case OP_VERIFY:
                {
                    // (true -- ) or
                    // (false -- false) and return
                    if (stack.size() < 1)
                        return false;
                    bool fValue = CastToBool(stacktop(-1));
                    if (fValue)
                        popstack(stack);
                    else
                        return false;
                }
                break;

                case OP_RETURN:
                {
                    return false;
                }
                break;


                //
                // Stack ops
                //
                case OP_TOALTSTACK:
                {
                    if (stack.size() < 1)
                        return false;
                    altstack.push_back(stacktop(-1));
                    popstack(stack);
                }
                break;

                case OP_FROMALTSTACK:
                {
                    if (altstack.size() < 1)
                        return false;
                    stack.push_back(altstacktop(-1));
                    popstack(altstack);
                }
                break;

                case OP_2DROP:
                {
                    // (x1 x2 -- )
                    if (stack.size() < 2)
                        return false;
                    popstack(stack);
                    popstack(stack);
                }
                break;

                case OP_2DUP:
                {
                    // (x1 x2 -- x1 x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch1 = stacktop(-2);
                    valtype vch2 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_3DUP:
                {
                    // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
                    if (stack.size() < 3)
                        return false;
                    valtype vch1 = stacktop(-3);
                    valtype vch2 = stacktop(-2);
                    valtype vch3 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                    stack.push_back(vch3);
                }
                break;

                case OP_2OVER:
                {
                    // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    valtype vch1 = stacktop(-4);
                    valtype vch2 = stacktop(-3);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2ROT:
                {
                    // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
                    if (stack.size() < 6)
                        return false;
                    valtype vch1 = stacktop(-6);
                    valtype vch2 = stacktop(-5);
                    stack.erase(stack.end()-6, stack.end()-4);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2SWAP:
                {
                    // (x1 x2 x3 x4 -- x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    swap(stacktop(-4), stacktop(-2));
                    swap(stacktop(-3), stacktop(-1));
                }
                break;

                case OP_IFDUP:
                {
                    // (x - 0 | x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    if (CastToBool(vch))
                        stack.push_back(vch);
                }
                break;

                case OP_DEPTH:
                {
                    // -- stacksize
                    CBigNum bn(stack.size());
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_DROP:
                {
                    // (x -- )
                    if (stack.size() < 1)
                        return false;
                    popstack(stack);
                }
                break;

                case OP_DUP:
                {
                    // (x -- x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.push_back(vch);
                }
                break;

                case OP_NIP:
                {
                    // (x1 x2 -- x2)
                    if (stack.size() < 2)
                        return false;
                    stack.erase(stack.end() - 2);
                }
                break;

                case OP_OVER:
                {
                    // (x1 x2 -- x1 x2 x1)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-2);
                    stack.push_back(vch);
                }
                break;

                case OP_PICK:
                case OP_ROLL:
                {
                    // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
                    // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
                    if (stack.size() < 2)
                        return false;
                    int n = CastToBigNum(stacktop(-1)).getint();
                    popstack(stack);
                    if (n < 0 || n >= stack.size())
                        return false;
                    valtype vch = stacktop(-n-1);
                    if (opcode == OP_ROLL)
                        stack.erase(stack.end()-n-1);
                    stack.push_back(vch);
                }
                break;

                case OP_ROT:
                {
                    // (x1 x2 x3 -- x2 x3 x1)
                    //  x2 x1 x3  after first swap
                    //  x2 x3 x1  after second swap
                    if (stack.size() < 3)
                        return false;
                    swap(stacktop(-3), stacktop(-2));
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_SWAP:
                {
                    // (x1 x2 -- x2 x1)
                    if (stack.size() < 2)
                        return false;
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_TUCK:
                {
                    // (x1 x2 -- x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.insert(stack.end()-2, vch);
                }
                break;


                //
                // Splice ops
                //
                case OP_CAT:
                {
                    // (x1 x2 -- out)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    vch1.insert(vch1.end(), vch2.begin(), vch2.end());
                    popstack(stack);
                    if (stacktop(-1).size() > 520)
                        return false;
                }
                break;

                case OP_SUBSTR:
                {
                    // (in begin size -- out)
                    if (stack.size() < 3)
                        return false;
                    valtype& vch = stacktop(-3);
                    int nBegin = CastToBigNum(stacktop(-2)).getint();
                    int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
                    if (nBegin < 0 || nEnd < nBegin)
                        return false;
                    if (nBegin > vch.size())
                        nBegin = vch.size();
                    if (nEnd > vch.size())
                        nEnd = vch.size();
                    vch.erase(vch.begin() + nEnd, vch.end());
                    vch.erase(vch.begin(), vch.begin() + nBegin);
                    popstack(stack);
                    popstack(stack);
                }
                break;

                case OP_LEFT:
                case OP_RIGHT:
                {
                    // (in size -- out)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch = stacktop(-2);
                    int nSize = CastToBigNum(stacktop(-1)).getint();
                    if (nSize < 0)
                        return false;
                    if (nSize > vch.size())
                        nSize = vch.size();
                    if (opcode == OP_LEFT)
                        vch.erase(vch.begin() + nSize, vch.end());
                    else
                        vch.erase(vch.begin(), vch.end() - nSize);
                    popstack(stack);
                }
                break;

                case OP_SIZE:
                {
                    // (in -- in size)
                    if (stack.size() < 1)
                        return false;
                    CBigNum bn(stacktop(-1).size());
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Bitwise logic
                //
                case OP_INVERT:
                {
                    // (in - out)
                    if (stack.size() < 1)
                        return false;
                    valtype& vch = stacktop(-1);
                    for (int i = 0; i < vch.size(); i++)
                        vch[i] = ~vch[i];
                }
                break;

                case OP_AND:
                case OP_OR:
                case OP_XOR:
                {
                    // (x1 x2 - out)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    MakeSameSize(vch1, vch2);
                    if (opcode == OP_AND)
                    {
                        for (int i = 0; i < vch1.size(); i++)
                            vch1[i] &= vch2[i];
                    }
                    else if (opcode == OP_OR)
                    {
                        for (int i = 0; i < vch1.size(); i++)
                            vch1[i] |= vch2[i];
                    }
                    else if (opcode == OP_XOR)
                    {
                        for (int i = 0; i < vch1.size(); i++)
                            vch1[i] ^= vch2[i];
                    }
                    popstack(stack);
                }
                break;

                case OP_EQUAL:
                case OP_EQUALVERIFY:
                //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
                {
                    // (x1 x2 - bool)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    bool fEqual = (vch1 == vch2);
                    // OP_NOTEQUAL is disabled because it would be too easy to say
                    // something like n != 1 and have some wiseguy pass in 1 with extra
                    // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
                    //if (opcode == OP_NOTEQUAL)
                    //    fEqual = !fEqual;
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fEqual ? vchTrue : vchFalse);
                    if (opcode == OP_EQUALVERIFY)
                    {
                        if (fEqual)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;


                //
                // Numeric
                //
                case OP_1ADD:
                case OP_1SUB:
                case OP_2MUL:
                case OP_2DIV:
                case OP_NEGATE:
                case OP_ABS:
                case OP_NOT:
                case OP_0NOTEQUAL:
                {
                    // (in -- out)
                    if (stack.size() < 1)
                        return false;
                    CBigNum bn = CastToBigNum(stacktop(-1));
                    switch (opcode)
                    {
                    case OP_1ADD:       bn += bnOne; break;
                    case OP_1SUB:       bn -= bnOne; break;
                    case OP_2MUL:       bn <<= 1; break;
                    case OP_2DIV:       bn >>= 1; break;
                    case OP_NEGATE:     bn = -bn; break;
                    case OP_ABS:        if (bn < bnZero) bn = -bn; break;
                    case OP_NOT:        bn = (bn == bnZero); break;
                    case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
                    }
                    popstack(stack);
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_ADD:
                case OP_SUB:
                case OP_MUL:
                case OP_DIV:
                case OP_MOD:
                case OP_LSHIFT:
                case OP_RSHIFT:
                case OP_BOOLAND:
                case OP_BOOLOR:
                case OP_NUMEQUAL:
                case OP_NUMEQUALVERIFY:
                case OP_NUMNOTEQUAL:
                case OP_LESSTHAN:
                case OP_GREATERTHAN:
                case OP_LESSTHANOREQUAL:
                case OP_GREATERTHANOREQUAL:
                case OP_MIN:
                case OP_MAX:
                {
                    // (x1 x2 -- out)
                    if (stack.size() < 2)
                        return false;
                    CBigNum bn1 = CastToBigNum(stacktop(-2));
                    CBigNum bn2 = CastToBigNum(stacktop(-1));
                    CBigNum bn;
                    switch (opcode)
                    {
                    case OP_ADD:
                        bn = bn1 + bn2;
                        break;

                    case OP_SUB:
                        bn = bn1 - bn2;
                        break;

                    case OP_MUL:
                        if (!BN_mul(&bn, &bn1, &bn2, pctx))
                            return false;
                        break;

                    case OP_DIV:
                        if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
                            return false;
                        break;

                    case OP_MOD:
                        if (!BN_mod(&bn, &bn1, &bn2, pctx))
                            return false;
                        break;

                    case OP_LSHIFT:
                        if (bn2 < bnZero || bn2 > CBigNum(2048))
                            return false;
                        bn = bn1 << bn2.getulong();
                        break;

                    case OP_RSHIFT:
                        if (bn2 < bnZero || bn2 > CBigNum(2048))
                            return false;
                        bn = bn1 >> bn2.getulong();
                        break;

                    case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
                    case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
                    case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
                    case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
                    case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
                    case OP_LESSTHAN:            bn = (bn1 < bn2); break;
                    case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
                    case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
                    case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
                    case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
                    case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
                    }
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(bn.getvch());

                    if (opcode == OP_NUMEQUALVERIFY)
                    {
                        if (CastToBool(stacktop(-1)))
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_WITHIN:
                {
                    // (x min max -- out)
                    if (stack.size() < 3)
                        return false;
                    CBigNum bn1 = CastToBigNum(stacktop(-3));
                    CBigNum bn2 = CastToBigNum(stacktop(-2));
                    CBigNum bn3 = CastToBigNum(stacktop(-1));
                    bool fValue = (bn2 <= bn1 && bn1 < bn3);
                    popstack(stack);
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fValue ? vchTrue : vchFalse);
                }
                break;


                //
                // Crypto
                //
                case OP_RIPEMD160:
                case OP_SHA1:
                case OP_SHA256:
                case OP_HASH160:
                case OP_HASH256:
                {
                    // (in -- hash)
                    if (stack.size() < 1)
                        return false;
                    valtype& vch = stacktop(-1);
                    valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
                    if (opcode == OP_RIPEMD160)
                        RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
                    else if (opcode == OP_SHA1)
                        SHA1(&vch[0], vch.size(), &vchHash[0]);
                    else if (opcode == OP_SHA256)
                        SHA256(&vch[0], vch.size(), &vchHash[0]);
                    else if (opcode == OP_HASH160)
                    {
                        uint160 hash160 = Hash160(vch);
                        memcpy(&vchHash[0], &hash160, sizeof(hash160));
                    }
                    else if (opcode == OP_HASH256)
                    {
                        uint256 hash = Hash(vch.begin(), vch.end());
                        memcpy(&vchHash[0], &hash, sizeof(hash));
                    }
                    popstack(stack);
                    stack.push_back(vchHash);
                }
                break;

                case OP_CODESEPARATOR:
                {
                    // Hash starts after the code separator
                    pbegincodehash = pc;
                }
                break;

                case OP_CHECKSIG:
                case OP_CHECKSIGVERIFY:
                {
                    // (sig pubkey -- bool)
                    if (stack.size() < 2)
                        return false;

                    valtype& vchSig    = stacktop(-2);
                    valtype& vchPubKey = stacktop(-1);

                    ////// debug print
                    //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
                    //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signature, since there's no way for a signature to sign itself
                    scriptCode.FindAndDelete(CScript(vchSig));

                    bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);

                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fSuccess ? vchTrue : vchFalse);
                    if (opcode == OP_CHECKSIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_CHECKMULTISIG:
                case OP_CHECKMULTISIGVERIFY:
                {
                    // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)

                    int i = 1;
                    if (stack.size() < i)
                        return false;

                    int nKeysCount = CastToBigNum(stacktop(-i)).getint();
                    if (nKeysCount < 0 || nKeysCount > 20)
                        return false;
                    nOpCount += nKeysCount;
                    if (nOpCount > 201)
                        return false;
                    int ikey = ++i;
                    i += nKeysCount;
                    if (stack.size() < i)
                        return false;

                    int nSigsCount = CastToBigNum(stacktop(-i)).getint();
                    if (nSigsCount < 0 || nSigsCount > nKeysCount)
                        return false;
                    int isig = ++i;
                    i += nSigsCount;
                    if (stack.size() < i)
                        return false;

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signatures, since there's no way for a signature to sign itself
                    for (int k = 0; k < nSigsCount; k++)
                    {
                        valtype& vchSig = stacktop(-isig-k);
                        scriptCode.FindAndDelete(CScript(vchSig));
                    }

                    bool fSuccess = true;
                    while (fSuccess && nSigsCount > 0)
                    {
                        valtype& vchSig    = stacktop(-isig);
                        valtype& vchPubKey = stacktop(-ikey);

                        // Check signature
                        if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
                        {
                            isig++;
                            nSigsCount--;
                        }
                        ikey++;
                        nKeysCount--;

                        // If there are more signatures left than keys left,
                        // then too many signatures have failed
                        if (nSigsCount > nKeysCount)
                            fSuccess = false;
                    }

                    while (i-- > 0)
                        popstack(stack);
                    stack.push_back(fSuccess ? vchTrue : vchFalse);

                    if (opcode == OP_CHECKMULTISIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                default:
                    return false;
            }

            // Size limits
            if (stack.size() + altstack.size() > 1000)
                return false;
        }
    }
    catch (...)
    {
        return false;
    }


    if (!vfExec.empty())
        return false;

    return true;
}
Example #27
0
void elimDups(vector<string> &words)
{
	sort(words.begin(), words.end());
	auto end_unique = unique(words.begin(), words.end());
	words.erase(end_unique, words.end());
}
Example #28
0
 virtual void rem(FD_EVENT *fd) {
    vector<tty_to_id>::iterator it = std::find(_ids.begin(), _ids.end(), tty_to_id(fd));
    if (it != _ids.end()) {
       _ids.erase(it);
    }
 }
Example #29
0
bool BPlusTree::build(vector<pair<KeyValue, int> > init)
{
    /*
	for (vector<pair<KeyValue, int> >::iterator iter = init.begin(); iter != init.end(); iter++)
	{
		insert(iter->first, iter->second);
	}
     */
	if (init.size() <= max_key_num)
	{
		fetch(0);
		set_pin(0);
        nodes[0]->is_root = true;
        nodes[0]->is_leaf = true;
        nodes[0]->next = -1;
        nodes[0]->prev = -1;
        nodes[0]->child_num = -1;
		for (vector<pair<KeyValue, int> >::iterator iter = init.begin(); iter != init.end(); iter++)
		{
			nodes[0]->keys.push_back(iter->first);
			nodes[0]->offsets.push_back(iter->second);
			nodes[0]->key_num += 1;
		}
		write_back(0); 
		reset_pin(0);
		release(0);
	}
	else
	{
		vector<pair<KeyValue, int> > children;
		int n = init.size();
		int prev = -1;
		for (int i = 0; i < n/max_key_num-1; i++)
		{
			IndexBlock *tmp = bm->getIndexNewBlock(table, attr);
			set_pin(tmp->blockNo);
			blocks[tmp->blockNo] = tmp;
			nodes[tmp->blockNo] = new Node(tmp->blockNo);
			Node *cur_node = nodes[tmp->blockNo];
			cur_node->prev = prev;
			cur_node->block_num = tmp->blockNo;
			cur_node->is_leaf = true;
			cur_node->is_root = false;
			cur_node->key_num = max_key_num;
			cur_node->next = -1;
			if (prev != -1)
				nodes[cur_node->prev]->next = cur_node->block_num;
            prev = cur_node->block_num;
			for (int j = 0; j < max_key_num; j++)
			{
				cur_node->keys.push_back(init.front().first);
				cur_node->offsets.push_back(init.front().second);
				init.erase(init.begin());
			}
			children.push_back(make_pair(cur_node->keys.front(), cur_node->block_num));
			// write_back(tmp->blockNo);
			// reset_pin(tmp->blockNo);
			// release(tmp->blockNo);
		}
		for (int n = init.size()/2; init.size() != 0; n = init.size())
		{
			IndexBlock *tmp = bm->getIndexNewBlock(table, attr);
			set_pin(tmp->blockNo);
			blocks[tmp->blockNo] = tmp;
			nodes[tmp->blockNo] = new Node(tmp->blockNo);
			Node *cur_node = nodes[tmp->blockNo];
			cur_node->prev = prev;
			cur_node->block_num = tmp->blockNo;
			cur_node->is_leaf = true;
			cur_node->is_root = false;
			cur_node->key_num = n;
			cur_node->next = -1;
			if (prev != -1)
				nodes[cur_node->prev]->next = cur_node->block_num;
            prev = cur_node->block_num;
			for (int j = 0; j < n; j++)
			{
				cur_node->keys.push_back(init.front().first);
				cur_node->offsets.push_back(init.front().second);
				init.erase(init.begin());
			}
			children.push_back(make_pair(cur_node->keys.front(), cur_node->block_num));
		}
		recur_build(children);
	}
	return true;
}
Example #30
0
void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    //Drawing and updating each vertex object in <points>
    if (flag1 == true)			//First point selected, but no object created yet
    {
        if (current == Dot)	drawStart(px1, py1, size, c);
        else if (current == Line)
        {
            if (points.size() == 0 || points.size() % 2 == 0) drawStart(px1, py1, size, c);
            else {
                drawPoint(points[points.size() - 1]);
                drawStart(px1, py1, size, c);
            }
        }
        else
        {
            if (lastMarker == 0 && polygonMarkers.size() > 0)
            {
                if (points.size() == 0) drawStart(px1, py1, size, c);
                else drawPoint(points[lastMarker]);
            }
            for (size_t i = lastMarker + 1; i < points.size(); i++) drawPoint(points.at(i));
            drawStart(px1, py1, size, c);
        }
    }
    //Checking for the first point on a line before the second point's initial position
    //is defined (Line Mode Only)
    else if (flag1 == false && current != Dot)
    {
        if (current == Line)
        {
            if (points.size() > 0 && points.size() % 2 != 0) drawPoint(points.at(points.size() - 1));
        }

        else if (current == Polygon)
        {
            if (polygonMarkers.size() > 0)
            {
                if (lastMarker == 0 && points.size() < 1) drawPoint(points.at(0));
                else
                {
                    for (size_t i = lastMarker + 1; i < points.size(); i++) polySet.push_back(points.at(i));
                    drawFilledPolygon(polySet);
                    polySet.erase(polySet.begin(), polySet.begin() + polySet.size());
                }
            }
        }
    }

    //Drawing the animated objects
    if (current == Dot)
    {
        for (size_t i = 0; i < points.size(); i++)
        {
            drawPoint(points.at(i));
            if (pauseflag == false) points.at(i).UpdatePosition();
        }
    }
    else if (current == Line)
    {
        //Making sure that the vector limit passed has an even number of Vertex objects
        if (points.size() % 2 == 0) limit = points.size();
        else limit = points.size() - 1;

        for (int i = 0; i < limit; i = i + 2)
        {
            drawVertexLine(points.at(i), points.at(i + 1));
            if (pauseflag == false) {
                points.at(i).UpdatePosition();
                points.at(i + 1).UpdatePosition();
            }
        }
    }
    else if (current == Polygon)
    {
        if (polygonMarkers.size() > 1)
        {
            //Drawing the first polygon
            for (int k = polygonMarkers.at(0); k < polygonMarkers.at(1); k++)
            {
                polySet.push_back(points.at(k));
                if (pauseflag == false) points.at(k).UpdatePosition();
            }
            polySet.push_back(points.at(polygonMarkers.at(1)));
            drawFilledPolygon(polySet);
            polySet.erase(polySet.begin(), polySet.begin() + polySet.size());

            //Drawing the remaining polygons
            for (size_t i = 1; i < polygonMarkers.size(); i++)
            {
                for (int j = polygonMarkers.at(i - 1) + 1; j < polygonMarkers.at(i); j++)
                {
                    polySet.push_back(points.at(j));
                    if (pauseflag == false) points[j].UpdatePosition();
                }
                polySet.push_back(points.at(polygonMarkers.at(i)));
                drawFilledPolygon(polySet);
                polySet.erase(polySet.begin(), polySet.begin() + polySet.size());
            }
        }
    }

    glFlush();

    //Double Buffering
    glutSwapBuffers();
    glutPostRedisplay();

}