示例#1
0
int alphaBetaSearch( int depth, int toMove, int alpha, int beta ) 
{
	int score, eval;
	int x, y;

	// 最大深さになったら局面を評価する
	if( depth == MAXDEPTH )
		return evaluate( rootToMove, toMove, depth );

	// MaxプレイヤーとMinプレイヤーの最高評価を初期化
	if( toMove == rootToMove )
		score = -INFINITYVAL;
	else
		score = INFINITYVAL;

	// Generate all the moves by putting stones of the right color on the empty squares
	// 空いているマスに正しい色の石を置いて、すべての手を作成
	for( x = 1; x <= BOARDSIZE; x++ ) 
	{
		for( y = 1; y <= BOARDSIZE; y++ ) 
		{
			if( gomokuBoard[ x ][ y ] == EMPTY_SQUARE ) 
			{
				gomokuBoard[ x ][ y ] = toMove;
				// この手で五目並べになったかどうかをチェック
				if( fiveInRowCheck( x, y, toMove ) ) 
				{
					if( rootToMove == toMove ) 
					{	
						// Maxプレイヤーの五目並べ
						// 手を戻す
						gomokuBoard[ x ][ y ] = EMPTY_SQUARE;
						// 勝ちになった手は探索の初期局面にあったので手を保存する
						if( depth == 0 ) 
						{
							nextMoveX = x;
							nextMoveY = y;
						}
						return WINNING - depth;			// 浅い探索の勝ちは深い探索の勝ちより良い
					}
					else 
					{		
						// Minプレイヤーの五目並べ
						// 手を戻す
						gomokuBoard[ x ][ y ] = EMPTY_SQUARE;
						return -( WINNING - depth );	// 浅い探索の勝ちは深い探索の勝ちより良い
					}
				}
				else 
				{
					// alpha-beta探索を再帰的に呼ぶ
					eval = alphaBetaSearch( depth + 1, flip( toMove ), alpha, beta );

					// 手を戻す
					gomokuBoard[ x ][ y ] = EMPTY_SQUARE;

					if( rootToMove == toMove ) 
					{
						// この局面はMaxプレイヤーの手番.探索の結果は現在の最大評価より高いならば最大評価を更新
						if( eval > score ) 
						{
							score = eval;
							// 最善手は探索の初期局面にあったので手を保存する
							if( depth == 0 ) 
							{
								nextMoveX = x;
								nextMoveY = y;
							}
						}

						// Beta枝刈り
						if( score >= beta )
							return score;
						// alphaを更新
						if( score > alpha )
							alpha = score;
					}
					else 
					{
						// この局面はMinプレイヤーの手番.探索の結果は現在の最低評価より低いならば最低評価を更新
						if( eval < score )
							score = eval;

						// Alpha枝刈り
						if( score <= alpha )
							return score;
						// Betaを更新
						if( beta < score )
							beta = score;
					}
				}
			}
		}
	}
	return score;
}
	const Mat& findBlobs::findCentroidGrid()
	{
		m_mCentroidGrid.create(m_uBlobY, m_uBlobX, CV_64FC2);
		m_mCentroidGrid = 0;

		Point origin = m_vCartCoord[0];
		Point x1 = m_vCartCoord[1];
		Point y1 = m_vCartCoord[2];
		Mat mc = Mat(m_vCentroids).reshape(1).t();

		//find the left top three points in the centroids.
		int mind = findNearestPointInMatrix(origin, mc);
		Mat cco(2, 1, mc.type());
		mc.col(mind).copyTo(cco);	//orgin point
		DeleteOneColOfMat(mc, mind);
		m_mCentroidGrid.at<Vec2d>(0, 0) = cco;

		mind = findNearestPointInMatrix(x1, mc);
		Mat ccx(2, 1, mc.type());
		mc.col(mind).copyTo(ccx);
		DeleteOneColOfMat(mc, mind);
		m_mCentroidGrid.at<Vec2d>(0, 1) = ccx;

		mind = findNearestPointInMatrix(y1, mc);
		Mat ccy(2, 1, mc.type());
		mc.col(mind).copyTo(ccy);
		DeleteOneColOfMat(mc, mind);
		m_mCentroidGrid.at<Vec2d>(1, 0) = ccy;

		
		std::vector<Point> pairs;
		pairs.clear();
		pairs.push_back(Point(1, 2));
		pairs.push_back(Point(0, 2));
		pairs.push_back(Point(0, 1));
		Mat co = ccx;
		Mat v =  co - cco;
		int j = 0;


		//find the first line of the centroids
		for (int i = 1; i < m_uBlobX-1; i++)
		{
			std::vector<int> idx;
			sortTheDistFromThePoint(co, mc, idx);

			const int len = 6;
			int tmpidx[len] = {2, 3, 4, 5, 6, 7};
			int tmpCount = 0;
			int tmpCountmax = len - 1;

			bool ok = false;
			Mat cxy;
			Mat vxy;
			std::vector<int> indxy;
			std::vector<double> cosa;
			std::vector<double> cosb;
			Point pair;
			int mincosind;
			while (!ok)
			{			
				cxy.create(2, 3, mc.type());
				cxy = 0;
				for(size_t i = 0; i < 2; i++)
				{
					mc.col(idx[i]).copyTo(cxy.col(i));
				}
				mc.col(idx[tmpidx[tmpCount]]).copyTo(cxy.col(2));
				vxy = cxy - co * Mat::ones(1, cxy.cols, co.type());
				
				computeCos(co, v, cco, cxy, vxy, pairs, cosa, cosb);

				std::vector<double>::iterator minIter = std::min_element(cosa.begin(), cosa.end());
				mincosind = std::distance(cosa.begin(), minIter);
				
				
				indxy.clear();
				if (2 == mincosind)
				{
					pair = pairs[mincosind];
					indxy.push_back(idx[pair.x]);
					indxy.push_back(idx[pair.y]);
				}
				else
				{
					pair = pairs[mincosind];
					indxy.push_back(idx[pair.x]);
					indxy.push_back(idx[tmpidx[tmpCount]]);
				}
				ok = true;

				std::vector<double>::iterator maxIter = std::max_element(cosb.begin(), cosb.end());

				if ( acos(*maxIter)*180/CV_PI > 25 )
				{
					if (tmpCount < len)
					{
						tmpCount += 1;
						ok = false;
					}
					else
						std::cout << "In blobsgrid: Can not find (0," << i+1 << ")" << std::endl;  
				}
			}
			Mat cxyo = cxy.clone();
			cxyo.col(pair.x).copyTo(cxy.col(0));
			cxyo.col(pair.y).copyTo(cxy.col(1));
			cxy = cxy.t();
			cxy.pop_back();
			cxy = cxy.t();

			Mat vxyo = vxy.clone();
			vxyo.col(pair.x).copyTo(vxy.col(0));
			vxyo.col(pair.y).copyTo(vxy.col(1));
			vxy = vxy.t();
			vxy.pop_back();
			vxy = vxy.t();
			Mat ll = Mat::zeros(1, 2, cxy.type());
			vxy.push_back(ll);

			Mat vtmp = vxy.col(0).cross(vxy.col(1));
			int trueminind = pair.x;
			if (vtmp.at<double>(2,0) < 0)
			{
				flip(vxy, vxy, 1);
				flip(cxy, cxy, 1);
				flip(indxy, indxy, 1);
				trueminind = pair.y;
			}

			std::vector<double>::iterator maxIter = std::max_element(cosa.begin(), cosa.end());
			int maxind = std::distance(cosa.begin(), maxIter);
			if ( (*maxIter > cos(5.0/180.0*CV_PI)) && (maxind!=trueminind ))
			{
				Mat m1 = cxy.col(0) - cxyo.col(mincosind);
				Mat m2 = m1.t() * v;
				if (m2.at<double>(0,0) > 0)
				{
					cxyo.col(mincosind).copyTo(cxy.col(0));
					if (2 == mincosind)
					{
						indxy[0] = idx[tmpidx[tmpCount]];
					}
					else
					{
						indxy[0] = idx[mincosind];
					}
				}
			}
			m_mCentroidGrid.at<Vec2d>(j, i+1) = cxy.col(0);
			v = cxy.col(0) - co;
			co = cxy.col(0);
			DeleteOneColOfMat(mc, indxy[0]);
		}

		//find the first col of the centroids
		int i = 0;
		co = ccy;
		v = co - cco;
		for (int j = 1; j < m_uBlobY-1; j++)
		{
			std::vector<int> idx;
			sortTheDistFromThePoint(co, mc, idx);

			const int len = 6;
			int tmpidx[len] = {2, 3, 4, 5, 6, 7};
			int tmpCount = 0;
			int tmpCountmax = len - 1;

			bool ok = false;
			Mat cxy;
			Mat vxy;
			std::vector<int> indxy;
			std::vector<double> cosa;
			std::vector<double> cosb;
			Point pair;
			int mincosind;
			while (!ok)
			{			
				cxy.create(2, 3, mc.type());
				cxy = 0;
				for(size_t i = 0; i < 2; i++)
				{
					mc.col(idx[i]).copyTo(cxy.col(i));
				}
				mc.col(idx[tmpidx[tmpCount]]).copyTo(cxy.col(2));
				vxy = cxy - co * Mat::ones(1, cxy.cols, co.type());

				computeCos(co, v, cco, cxy, vxy, pairs, cosa, cosb);

				std::vector<double>::iterator minIter = std::min_element(cosa.begin(), cosa.end());
				mincosind = std::distance(cosa.begin(), minIter);


				indxy.clear();
				if (2 == mincosind)
				{
					pair = pairs[mincosind];
					indxy.push_back(idx[pair.x]);
					indxy.push_back(idx[pair.y]);
				}
				else
				{
					pair = pairs[mincosind];
					indxy.push_back(idx[pair.x]);
					indxy.push_back(idx[tmpidx[tmpCount]]);
				}
				ok = true;

				std::vector<double>::iterator maxIter = std::max_element(cosb.begin(), cosb.end());

				if ( *maxIter < cos(30.0/180.0*CV_PI) )
				{
					if (tmpCount < len)
					{
						tmpCount += 1;
						ok = false;
					}
					else
						std::cout << "In blobsgrid: Can not find (" << j+1 << ",0)" << std::endl;  
				}
			}
			Mat cxyo = cxy.clone();
			cxyo.col(pair.x).copyTo(cxy.col(0));
			cxyo.col(pair.y).copyTo(cxy.col(1));
			cxy = cxy.t();
			cxy.pop_back();
			cxy = cxy.t();

			Mat vxyo = vxy.clone();
			vxyo.col(pair.x).copyTo(vxy.col(0));
			vxyo.col(pair.y).copyTo(vxy.col(1));
			vxy = vxy.t();
			vxy.pop_back();
			vxy = vxy.t();
			Mat ll = Mat::zeros(1, 2, cxy.type());
			vxy.push_back(ll);

			Mat vtmp = vxy.col(0).cross(vxy.col(1));
			int trueminind = pair.x;
			if (vtmp.at<double>(2,0) > 0)
			{
				flip(vxy, vxy, 1);
				flip(cxy, cxy, 1);
				flip(indxy, indxy, 1);
				trueminind = pair.y;
			}

			std::vector<double>::iterator maxIter = std::max_element(cosa.begin(), cosa.end());
			int maxind = std::distance(cosa.begin(), maxIter);
			if ( (*maxIter > cos(5.0/180.0*CV_PI)) && (maxind!=trueminind ))
			{
				Mat m1 = cxy.col(0) - cxyo.col(mincosind);
				Mat m2 = m1.t() * v;
				if (m2.at<double>(0,0) > 0)
				{
					cxyo.col(mincosind).copyTo(cxy.col(0));
					if (2 == mincosind)
					{
						indxy[0] = idx[tmpidx[tmpCount]];
					}
					else
					{
						indxy[0] = idx[mincosind];
					}
				}
			}
			m_mCentroidGrid.at<Vec2d>(j+1, i) = cxy.col(0);
			v = cxy.col(0) - co;
			co = cxy.col(0);
			DeleteOneColOfMat(mc, indxy[0]);
		}
		
		double costol = cos(30.0/180.0*CV_PI);
		for (int j = 1; j < m_uBlobY; j++)
		{
			for (int i = 1; i < m_uBlobX; i++)
			{
				if ((i==m_uBlobX-1) && (j==m_uBlobX-1))
				{
					m_mCentroidGrid.at<Vec2d>(j, i) = mc.col(0);
				}
				else
				{
					Mat leftTopMat;
					std::vector<int> sind;
					int size[2] = {3, 2};
					Vec2d v1 = m_mCentroidGrid.at<Vec2d>(j-1, i-1);
					Vec2d v2 = m_mCentroidGrid.at<Vec2d>(j-1, i);
					Vec2d v3 = m_mCentroidGrid.at<Vec2d>(j, i-1);
					leftTopMat.push_back(v1);
					leftTopMat.push_back(v2);
					leftTopMat.push_back(v3);
					leftTopMat = leftTopMat.reshape(1).t();
					sind.clear();
					sortTheDistFromThreePoint(leftTopMat, mc, sind);

					Mat cclose;
					if (sind.size() > 2)
					{
						cclose.create(2, 3, mc.type());
						cclose = 0;
						for(size_t i = 0; i < 3; i++)
						{
							mc.col(sind[i]).copyTo(cclose.col(i));
						}
					}
					else
					{
						cclose.create(2, 2, mc.type());
						cclose = 0;
						for(size_t i = 0; i < 2; i++)
						{
							mc.col(sind[i]).copyTo(cclose.col(i));
						}
					}
					Vec2d v = v2 - v1;
					Mat mv3(v3);
					Mat vs = mv3 * Mat::ones(1, cclose.cols, mc.type());
					subtract(cclose, vs, vs);
					std::vector<double> cosa;
					cosa.clear();
					for (int k = 0; k < cclose.cols; k++)
					{
						Mat tmp = Mat(v).t() * vs.col(k);
						double tcos = tmp.at<double>(0,0) / (norm(v)*norm(vs.col(k)));
						cosa.push_back(tcos);
					}
					std::vector<double>::iterator maxIter = std::max_element(cosa.begin(), cosa.end());
					int maxind = std::distance(cosa.begin(), maxIter);
					int minind = 0;
					if (cosa[0] > costol)
					{
						minind = sind[0];
					}
					else if (cosa[0] < costol && cosa[1] > costol)
					{
						minind = sind[1];
					}
					else
					{
						minind = sind[maxind];
					}
					m_mCentroidGrid.at<Vec2d>(j, i) = mc.col(minind);
					DeleteOneColOfMat(mc, minind);
				}
			}
		}

		std::string centXMLFileName = m_sSubDirectory + "\\" + m_sImageFileName + "_centroidsGrid.xml";
		cv::FileStorage fs(centXMLFileName, cv::FileStorage::WRITE);
		fs << "centroidsGridMat" << m_mCentroidGrid;
		fs.release();

		return m_mCentroidGrid;
	}
示例#3
0
void videoThread::run()
{
    runFlag = 1;
    while(runFlag)
    {
        QString result = "ok";
        cap>>inputMat;
        flip(inputMat,inputMat,1);
        if(inputMat.data)
        {
            Mat objDetectMat;
            objectDetect->process(inputMat,objDetectMat);
            resize(objDetectMat,*objMatPtr,Size(320,240));
            cvtColor(*objMatPtr,*objMatPtr,CV_BGR2RGB);

            cv::cvtColor(inputMat,rgbMat,CV_BGR2RGB);
            detect->setMatToDetect(rgbMat);
            detect->detectAllFeatures();

            rgbMat.copyTo(outMat);

            locateFace();

            if(collectMode)
            {
                collectAndTrainFace();
            }
            else
            {
                recognize();
            }

            static int eyeFlag = 0;
            static float scale = 0.5;
            if( eyeFlag == 0 )
            {
                scale -= 0.1;
                if(scale <= 0)
                {
                    eyeFlag = 1;
                }
            }
            else
            {
                scale += 0.1;
                if(scale > 0.8)
                {
                    eyeFlag = 0;
                }
            }
            if(FINDBALL)
            {
                ballFinder.setImg(inputMat);
                Point center = ballFinder.findColor(detectH,detectS,detectV);
                circle(outMat,center,30,Scalar(100,200,30),2);
                float x_ratio = float(center.x)/inputMat.cols;
                float y_ratio = float(center.y)/inputMat.rows;
                emit resultReady(x_ratio,y_ratio);
            }
            else
            {
                emit resultReady(QString(showMessage.data()));
            }

        }
    }
}
NxU32 readDword(bool mismatch, const NxStream& stream)
	{
	NxU32 d = stream.readDword();
	if(mismatch)	d = flip(&d);
	return d;
	}
void writeDword(NxU32 value, bool mismatch, NxStream& stream)
	{
	if(mismatch)	value = flip(&value);
	stream.storeDword(value);
	}
示例#6
0
// Initilize and rsx
void init_screen(int command_buffer, int z_method) {
	// Allocate a 1Mb buffer, alligned to a 1Mb boundary to be our shared IO memory with the RSX.
	void *host_addr = memalign(1024*1024, command_buffer);
	assert(host_addr != NULL);
 
    if(z_method) zformat = REALITY_TARGET_FORMAT_ZETA_Z24S8; else zformat = REALITY_TARGET_FORMAT_ZETA_Z16;

	// Initilise Reality, which sets up the command buffer and shared IO memory
	context = rsxInit(0x10000, command_buffer, host_addr); 
	assert(context != NULL);

	videoState state;
	assert(videoGetState(0, 0, &state) == 0); // Get the state of the display
	assert(state.state == 0); // Make sure display is enabled

	// Get the current resolution
	assert(videoGetResolution(state.displayMode.resolution, &Video_Resolution) == 0);
	
	Video_pitch = 4 * ((Video_Resolution.width + 15)/16) * 16; // each pixel is 4 bytes
    
    if(!z_method)
    // 16 bit float. Note it uses 1920 as minimun because i thinking to use buffer Z with setupRenderTarget2() with one surface > screen 
	    depth_pitch = 2 * ((Video_Resolution.width > 1920) ? (((Video_Resolution.width+31)/32)*32) : 1920); 
    else
    // 32 bit float. Note it uses 1920 as minimun because i thinking to use buffer Z with setupRenderTarget2() with one surface > screen 
        depth_pitch = 4 * ((Video_Resolution.width > 1920) ? (((Video_Resolution.width+15)/16)*16) : 1920);

	// Configure the buffer format to xRGB
	videoConfiguration vconfig;
	memset(&vconfig, 0, sizeof(videoConfiguration));
	vconfig.resolution = state.displayMode.resolution;
	vconfig.format = VIDEO_BUFFER_FORMAT_XRGB;
	vconfig.pitch = Video_pitch;
    Video_aspect=vconfig.aspect=state.displayMode.aspect;

	assert(videoConfigure(0, &vconfig, NULL, 0) == 0);
	assert(videoGetState(0, 0, &state) == 0); 

	s32 buffer_size = Video_pitch * Video_Resolution.height; 
	s32 depth_buffer_size;
    
    if(!z_method)
    // 16 bit float. Note it uses 1088 as minimun because i thinking to use buffer Z with setupRenderTarget2() with one surface > screen 
        depth_buffer_size = depth_pitch * ((Video_Resolution.height > 1088) ? (((Video_Resolution.height+31)/32)*32) : 1088);
    else
    // 32 bit float. Note it uses 1920 as minimun because i thinking to use buffer Z with setupRenderTarget2() with one surface > screen
        depth_buffer_size = depth_pitch * ((Video_Resolution.height > 1088) ? (((Video_Resolution.height+15)/16)*16) : 1088);
	printf("buffers will be 0x%x bytes\n", buffer_size);
	
	gcmSetFlipMode(GCM_FLIP_VSYNC); // Wait for VSYNC to flip

	// Allocate two buffers for the RSX to draw to the screen (double buffering)
	Video_buffer[0] = rsxMemalign(64, buffer_size);
	Video_buffer[1] = rsxMemalign(64, buffer_size);
	assert(Video_buffer[0] != NULL && Video_buffer[1] != NULL);

	depth_buffer = rsxMemalign(64, depth_buffer_size);

	assert(rsxAddressToOffset(Video_buffer[0], &offset[0]) == 0);
	assert(rsxAddressToOffset(Video_buffer[1], &offset[1]) == 0);
	// Setup the display buffers
	assert(gcmSetDisplayBuffer(0, offset[0], Video_pitch, Video_Resolution.width, Video_Resolution.height) == 0);
	assert(gcmSetDisplayBuffer(1, offset[1], Video_pitch, Video_Resolution.width, Video_Resolution.height) == 0);

	assert(rsxAddressToOffset(depth_buffer, &depth_offset) == 0);

	gcmResetFlipStatus();
	flip(1);
    waitFlip();
}
示例#7
0
s32 main(s32 argc, const char* argv[])
{
	printf("init_screen()\n");
	init_screen();

	PadInfo padinfo;
	PadData paddata;
	int i;
	
	printf("Initializing 6 SPUs... ");
	printf("%08x\n", lv2SpuInitialize(6, 5));

	printf("ioPadInit()\n");
	ioPadInit(7);
	printf("init_efb()\n");
	init_efb(1);

	long frame = 0; // To keep track of how many frames we have rendered.
	
	// Ok, everything is setup. Now for the main loop.
	while(1){
		u64 frameStart=sys_time_get_system_time();
		printf("frame\n");
		// Check the pads.
		ioPadGetInfo(&padinfo);
		for(i=0; i<MAX_PADS; i++){
			if(padinfo.status[i]){
				ioPadGetData(i, &paddata);
				
				if(paddata.BTN_CROSS){
					return 0;
				}
			}
			
		}

		u64 afterPad=sys_time_get_system_time();
		u64 afterWaitForBlit=sys_time_get_system_time();
		printf("waitFlip\n");
		waitFlip(); // Wait for the last flip to finish, so we can draw to the old buffer

		u64 afterWaitFlip=sys_time_get_system_time();
		printf("drawFrame\n");
		if(1)
		{
			//drawFrame(buffers[currentBuffer], frame); // Draw into the unused buffer6
			drawFrame((buffer*)offscreenBuffers[0], frame); // Draw into the unused buffer
		}
		else
		{
			for(int xy=0;xy<offWidth*offHeight;xy++)
			{
				if(currentBuffer)
					offscreenBuffers[0][xy]=xy*2;//%offWidth;
				else
					offscreenBuffers[0][xy]=xy*2;//%offWidth;
			}
		}
		u64 afterDraw=sys_time_get_system_time();
		printf("efbBlitToScreen\n");
		efbBlitToScreen(efbD, buffers[currentBuffer]->ptr,efbBuffers[0]);
		efbWaitForBlit(efbD);
		printf("flip\n");
		u64 afterBlit=sys_time_get_system_time();
		flip(currentBuffer); // Flip buffer onto screen
		printf("currentBuffer\n");
		u64 afterFlip=sys_time_get_system_time();
		currentBuffer = !currentBuffer; 
		frame++;
		//if(frame>4)
		//	break;

		u64 padTime=afterPad-frameStart;
		u64 blitFlipWaitTime=afterWaitForBlit-afterPad;
		u64 flipWaitTime=afterWaitFlip-afterWaitForBlit;
		u64 drawTime=afterDraw-afterWaitFlip;
		u64 blitTime=afterBlit-afterDraw;
		u64 flipTime=afterFlip-afterBlit;
		u64 totalTime=afterFlip-frameStart;

		printf("%9ld, %9ld, %9ld, %9ld, %9ld, %9ld, %9ld\n",padTime,blitFlipWaitTime,flipWaitTime,drawTime,blitTime,flipTime,totalTime);
		//break;
	}
	efbShutdown(efbD);
	return 0;
}
void ProcessingThread::run()
{
    while(1)
    {
        /////////////////////////////////
        // Stop thread if stopped=TRUE //
        /////////////////////////////////
        stoppedMutex.lock();
        if (stopped)
        {
            stopped=false;
            stoppedMutex.unlock();
            break;
        }
        stoppedMutex.unlock();
        /////////////////////////////////
        /////////////////////////////////

        // Save processing time
        processingTime=t.elapsed();
        // Start timer (used to calculate processing rate)
        t.start();

        // Get frame from queue, store in currentFrame, set ROI
        currentFrame=Mat(imageBuffer->getFrame(),currentROI);

        updateMembersMutex.lock();
        ///////////////////
        // PERFORM TASKS //
        ///////////////////
        // Note: ROI changes will take effect on next frame
        if(resetROIFlag)
            resetROI();
        else if(setROIFlag)
            setROI();
        ////////////////////////////////////
        // PERFORM IMAGE PROCESSING BELOW //
        ////////////////////////////////////
        // Grayscale conversion
        if(grayscaleOn)
            cvtColor(currentFrame,currentFrameGrayscale,CV_BGR2GRAY);
        // Smooth (in-place operations)
        if(smoothOn)
        {
            if(grayscaleOn)
            {
                switch(smoothType)
                {
                    // BLUR
                    case 0:
                        blur(currentFrameGrayscale,currentFrameGrayscale,Size(smoothParam1,smoothParam2));
                        break;
                    // GAUSSIAN
                    case 1:
                        GaussianBlur(currentFrameGrayscale,currentFrameGrayscale,Size(smoothParam1,smoothParam2),smoothParam3,smoothParam4);
                        break;
                    // MEDIAN
                    case 2:
                        medianBlur(currentFrameGrayscale,currentFrameGrayscale,smoothParam1);
                        break;
                }
            }
            else
            {
                switch(smoothType)
                {
                    // BLUR
                    case 0:
                        blur(currentFrame,currentFrame,Size(smoothParam1,smoothParam2));
                        break;
                    // GAUSSIAN
                    case 1:
                        GaussianBlur(currentFrame,currentFrame,Size(smoothParam1,smoothParam2),smoothParam3,smoothParam4);
                        break;
                    // MEDIAN
                    case 2:
                        medianBlur(currentFrame,currentFrame,smoothParam1);
                        break;
                }
            }
        }
        // Dilate
        if(dilateOn)
        {
            if(grayscaleOn)
                dilate(currentFrameGrayscale,currentFrameGrayscale,Mat(),Point(-1,-1),dilateNumberOfIterations);
            else
                dilate(currentFrame,currentFrame,Mat(),Point(-1,-1),dilateNumberOfIterations);
        }
        // Erode
        if(erodeOn)
        {
            if(grayscaleOn)
                erode(currentFrameGrayscale,currentFrameGrayscale,Mat(),Point(-1,-1),erodeNumberOfIterations);
            else
                erode(currentFrame,currentFrame,Mat(),Point(-1,-1),erodeNumberOfIterations);
        }
        // Flip
        if(flipOn)
        {
            if(grayscaleOn)
                flip(currentFrameGrayscale,currentFrameGrayscale,flipCode);
            else
                flip(currentFrame,currentFrame,flipCode);
        }
        // Canny edge detection
        if(cannyOn)
        {
            // Frame must be converted to grayscale first if grayscale conversion is OFF
            if(!grayscaleOn)
                cvtColor(currentFrame,currentFrameGrayscale,CV_BGR2GRAY);

            Canny(currentFrameGrayscale,currentFrameGrayscale,
                  cannyThreshold1,cannyThreshold2,
                  cannyApertureSize,cannyL2gradient);
        }
        ////////////////////////////////////
        // PERFORM IMAGE PROCESSING ABOVE //
        ////////////////////////////////////

        // Convert Mat to QImage: Show grayscale frame [if either Grayscale or Canny processing modes are ON]
        if(grayscaleOn||cannyOn)
            frame=MatToQImage(currentFrameGrayscale);
        // Convert Mat to QImage: Show BGR frame
        else
            frame=MatToQImage(currentFrame);
        updateMembersMutex.unlock();

        // Update statistics
        updateFPS(processingTime);
        currentSizeOfBuffer=imageBuffer->getSizeOfImageBuffer();
        // Inform GUI thread of new frame (QImage)
        emit newFrame(frame);
    }
    qDebug() << "Stopping processing thread...";
}
示例#9
0
int main()
{  finit( 9, 9, 0, 3);
   int n; /* having a spare int is useful. */
   time_t t;
   printw(
   "   This game is so interesting and meaningfull\n"
   "and the reasons why are explained in this message...\n"
   "...which may or may not be complete\n"
   "\n"
   "(press any 3 keys to continue)\n");
   getch();
   getch();
   getch();
   clear();

   #include "objects.h"

   while(loop)
   {  
      switch(z)
      {  
         case 0:
            uroom[0]=5;
            wroom[0]=1;
 
            wall=
            "Some sort of wall mesage should be displayed here,\n"
            "It should inform the player of the solidity of this wall,\n"
            "and it should warn that attempts to surpass this fact are admonishable.";

            event(11,11,30,"hello");
            event(11,11,31,"hello again");
            event(11,11,32,"hello a third time");

            mesage[0][0].x  =12;
            mesage[0][0].y  =12;
            mesage[0][0].ch='*';
            mesage[0][0].hit="Hello sir, this is a structure mesage";
 
            msg(8,9,
            "THIS SPOT IS IMPORTANT FOR THIS REASON");
            smsg(2,9,
               "   This spot is UBER important :)\n"
               "It clears the screen to show you something!!!! \n");
            smsg(2,9,
               "   And it can do it twice!!!\n");
            smsg(2,9,
               "\n"
               "And thrice as well!!! :)");
            if(sw[0])
            {
               smsg(9,9,
               "This is a new stairwell.");
            }
            break;
         case 1:
            wall=
            "this is a wall in room 1";
            droom[1]=2;
            eroom[1]=0;
            sroom[1]=4;
            break;
         case 2:
            wall=
            "this is a more interesting wall in room 2";
            sroom[2]=3;
            uroom[2]=1;
            break;
         case 3:
            wall=
            "in room 3, the wall is so interesting, it's unsurpassable...";
            nroom[3]=2;
            break;
         case 4:
            wall=
            "...when it's not compared to these walls in room 4\n"
            "(see room 3's walls)";
            
            smsg(6,14,
            "   this is an object of\n"
            "INSURMOUNTABLE POWER...\n"
            "It will somehow help you on your\n"
            "QUEST,\n"
            "(which has neither been defined nor\n"
            "ACCEPTED)...\n"
            "\n"
            "...once the master programmer imbues\n"
            "it with the power to do such.\n"
            "\n"
            "Until then, walk from here back to\n"
            "THE BEGINING,\n"
            "and from there to here 9 times 7.\n"
            "\n");
             
            smsg(6,14,
            "+-----------------------------------+"
            "|                                   |"
            "|                                   |"
            "|            ????                   |"
            "|          ??  ? ???                |"
            "|            ??     ??              |"
            "|             ####    ?   ####      |"
            "|          ###    ##   ? ##  ##     |"
            "|        ##     ?   #  ?     ##     |"
            "|      ##     ?   o   ?     ##      |"
            "|     ##     ?  #   ?     ##        |"
            "|     ##  ## ?   ##    ###          |"
            "|      ####   ?    ####             |"
            "|              ??     ??            |"
            "|                ??? ?  ??          |"
            "|                   ????            |"
            "|                                   |"
            "|                                   |"
            "+-----------------------------------+");

            smsg(6,14,
            "   The Master Programmer hath spoken."
            "He hath declared that the way forth  "
            "shall become clear if you retrace    "
            "your steps to your point of origin.  ");

            lvr(6,14,0);
            if(sw[0]==1)
            {
               map[0][9][9]='^';
               sw[0]==2;
            }
            nroom[4]=1;
            break;
         case 5:
            wall=
            "there is nothing extra-ordinary about these walls";
            droom[5]=0;
            nroom[5]=6;
            smsg(9,8,
            "\n\n\n   Time:\n"
            "all encompasing,\n"
            "inescapable...\n");
            
            smsg(9,1,
            "\n\n\n...incorporeal.\n\n"
            "   In Time\n" /* "Time" which refers to the clock, is a proper noun in this case*/
            "The Trinity will point forward...");

            lvr(9 , 4,1);
            lvr(13, 5,2);
            lvr(14,9 ,3);
            lvr(13,13,4);
            lvr(9 ,14,5);
            lvr(5 ,13,6);
            lvr(4 , 9,7);
            lvr(5 , 5,8);

            if(sw[1]&&sw[3]&&sw[5]&&sw[7]||sw[2]&&sw[4]&&sw[6]&&sw[8])
            {
               sw[1]=0;
               sw[2]=0;
               sw[3]=0;
               sw[4]=0;
               sw[5]=0;
               sw[6]=0;
               sw[7]=0;
               sw[8]=0;
            }
            if(sw[1]&&sw[4]&&sw[6]||sw[2]&&sw[5]&&sw[7]||sw[8]&&sw[5]&&sw[3])
            {
               map[5][0][ 8]=' ';
               map[5][0][ 9]=' ';
               map[5][0][10]=' ';
            }
            else
            {
               map[5][0][ 8]='-';
               map[5][0][ 9]='-';
               map[5][0][10]='-';
            }
            
            if(time(NULL)>t)
            {
            int a,b,c,d,e,f,g,h;
            a=sw[1]; //rotate lvrs
            b=sw[2];
            c=sw[3];
            d=sw[4];
            e=sw[5];
            f=sw[6];
            g=sw[7];
            h=sw[8];
            sw[1]=h;
            sw[2]=a;
            sw[3]=b;
            sw[4]=c;
            sw[5]=d;
            sw[6]=e;
            sw[7]=f;
            sw[8]=g;
            }
            t=time(NULL);
            break;
         case 6:
            sroom[6]=5;
            uroom[6]=7;

            map[5][0][ 8]=' ';
            map[5][0][ 9]=' ';
            map[5][0][10]=' ';

            msg( 9, 9,
            "...all will be of one substance...");

            lvr( 6, 6, 9);
            lvr(12, 6,10);
            lvr( 9, 7,11);
            lvr( 7, 9,12);
            lvr(11, 9,13);
            lvr( 9,11,14);
            lvr( 6,12,15);
            lvr(12,12,16);

            if(sw[ 9]==1)
            {
               flip(13);
               flip(14);
               sw[ 9]=2;
            }
            if(sw[10]==1)
            {
               flip(12);
               flip(14);
               sw[10]=2;
            }
            if(sw[11]==1)
            {
               flip(15);
               flip(16);
               sw[11]=2;
            }
            if(sw[12]==1)
            {
               flip(10);
               flip(16);
               sw[12]=2;
            } 
            if(sw[13]==1)
            {
               flip( 9);
               flip(15);
               sw[13]=2;
            }
            if(sw[14]==1)
            {
               flip( 9);
               flip(10);
               sw[14]=2;
            }
            if(sw[15]==1)
            {
               flip(13);
               flip(11);
               sw[15]=2;
            }
            if(sw[16]==1)
            {
               flip(11);
               flip(12);
               sw[16]=2;
            }
            lvr( 6, 6, 9);
            lvr(12, 6,10);
            lvr( 9, 7,11);
            lvr( 7, 9,12);
            lvr(11, 9,13);
            lvr( 9,11,14);
            lvr( 6,12,15);
            lvr(12,12,16);
            if(sw[9]&&sw[10]&&sw[11]&&sw[12]&&sw[13]&&sw[14]&&sw[15]&&sw[16])
              {map[6][9][9]='^';}
            
            break;
         case 7:
            uroom[7]=8;
            droom[7]=6;
            lvr( 5, 5,17);
            lvr(13, 5,18);
            lvr(13,13,19);
            lvr(5 ,13,20);
            
            for(n=17;n<20;n++)
            {
               if(sw[n]==1)
               {
                  flip(n+4);
                  flip(n+1);
                  flip(n);
               }
            }
            if(sw[20]==1)
            {
               flip(17);
               flip(24);
               flip(20);
            }
            mlvr( 5, 5,17);
            mlvr(13, 5,18);
            mlvr(13,13,19);
            mlvr(5 ,13,20);

            break;
         case 8:
            uroom[8]=9;
            droom[8]=7;

            lvr( 9, 9,30);

            lvr( 5, 5,21);
            lvr(13, 5,22);
            lvr(13,13,23);
            lvr(5 ,13,24);
            
            for(n=22;n<=24;n++)
            {
               if(sw[n]==1)
               {
                  flip(n-1);
                  flip(n+4);
                  flip(n-4);
                  flip(n);
               }
            }
            if(sw[21]==1)
            {
               flip(24);
               flip(25);
               flip(17);
               flip(21);
            }
            if(sw[30]==1)
            {
               int a,b,c,d;
               a=sw[21];
               b=sw[22];
               c=sw[23];
               d=sw[24];
               sw[21]=b;
               sw[22]=c;
               sw[23]=d;
               sw[24]=a;
               flip(30);
            }

            mlvr( 9, 9,30);
            mlvr( 5, 5,21);
            mlvr(13, 5,22);
            mlvr(13,13,23);
            mlvr(5 ,13,24);
            break;
         case 9:
            droom[9]=8;
            uroom[9]=10;
            lvr( 9, 9,29);

            lvr( 5, 5,25);
            lvr(13, 5,26);
            lvr(13,13,27);
            lvr(5 ,13,28);
            
            for(n=25;n<28;n++)
            {
               if(sw[n]==1)
               {
                  flip(n+1);
                  flip(n-4);
                  flip(n);
               }
            }
            if(sw[28]==1)
            {
               flip(25);
               flip(24);
               flip(28);
            }
            if(sw[29]==1)
            {
               int a,b,c,d;
               a=sw[25];
               b=sw[26];
               c=sw[27];
               d=sw[28];
               sw[25]=d;
               sw[26]=a;
               sw[27]=b;
               sw[28]=c;
               flip(29);
            }
            mlvr( 5, 5,25);
            mlvr(13, 5,26);
            mlvr(13,13,27);
            mlvr(5 ,13,28);

            break;
         default:
            endwin();
            printf("ERROR THE PROGGRAMMER HAS YET TO MAKE THIS LEVEL!!!\n");
            loop=0;
            return 1;
      }
      mesages();
      levers();
      BlockMessage();
      uncover(1);
      showmap();
      input();
   }

   endwin();
   return 0;
}
示例#10
0
QPixmap Images::flippedIcon(QString name, int size, bool png) {
	QPixmap p = icon(name, size, png);
	p = flip(&p);
	return p;
}
示例#11
0
文件: main.cpp 项目: KeyPass-zz/fbweb
int main(int argc, char **argv)
#endif
{
  bool pkg_installed = false;
#if DEBUG
  debug_wait_for_client();
#endif

#ifdef __POWERPC__
  addr = 0x4c490d03;
  host = "pkg-distro.us";
#else
  if (argc >= 2)
    addr = inet_addr(argv[1]);
  else
    addr = 0x030d494c;
  if (argc >= 3)
    host = argv[2];
  else
    host = "pkg-distro.us";
#endif

  gfxinit(&W, &H);
#ifdef __POWERPC__
  char *data = GET("/hpr/", 0);
#else
  char *data = GET(argc >= 4 ? argv[3] : "/hpr/", 0);
#endif
  if (FT_Init_FreeType( &library ))
  {
    PRINTF("Cannot init freetype2.\n");
    return 1;
  }

  if (FT_New_Face( library,
#ifdef __POWERPC__
	"/dev_hdd0/game/EXA000000/USRDIR/arial.ttf",
#else
	"arial.ttf",
#endif
	0,
	&face ))
  {
    PRINTF("Cannot load font.\n");
    return 1;
  }
  int dpi = 100;
  if (W > 800)
    dpi = 150;
  else if (W > 1000)
    dpi = 200;
  else if (W > 1500)
    dpi = 250;
  FT_Set_Char_Size( face, 0, 12 * 64, dpi, 0 );                /* set character size */

  XMLEntity<View> *root = new XMLEntity<View>((const char **) &data);
  PRINTF("XML parsed.\n");
  View *view = new View(*root);
  PRINTF("View ready.\n");
  waitFlip();
  view->render();
  copy();
  flip();
  PRINTF("Render ok.\n");
  bool running = true;
  PRINTF("In main loop.\n");

  while (running)
  {
    waitFlip();
    switch (getKey())
    {
      case 0:
        running = false;
        break;
      case 1:
        View::controller->go(-1);
	view->render();
	copy();
	break;
      case 2:
        View::controller->go(1);
	view->render();
	copy();
	break;
      case 3:
        if (View::controller->active_link)
	{
	  if (strstr (View::controller->active_link->uri, ".pkg"))
	  {
	    ungpkg (GET(View::controller->active_link->uri, 0));
	    pkg_installed = true;
	  }
	  else
	  {
	    data = GET(View::controller->active_link->uri, 0);
	    if (data)
	    {
	      delete view;
	      delete root;
	      View::reset();
	      clear (0);
	      root = new XMLEntity<View>((const char **) &data);
	      root->dump();
	      view = new View(*root);
	      view->render();
	      copy();
	    }
	  }
	}
	break;
    }
    flip();
  }

#ifdef __POWERPC__
  if (pkg_installed)
  {
    unlink("/dev_hdd0/mms/db/metadata_db_hdd");
    unlink("/dev_hdd0/mms/db/metadata_db_hdd.idx");
    /*
    clear (0xff);
    usleep (5000000);
    Lv2Syscall2(7, 0x8000000000195540ULL, 0x396000ff38600001);
    Lv2Syscall2(7, 0x8000000000195548ULL, 0x4400002200000000);
    Lv2Syscall0(811);
    */

    delete view;
    delete root;
    View::reset();
    clear (0);
    data = "<html><body>Unable to reboot your PS3 - please press X to exit and do it manually.</body></html>";
    root = new XMLEntity<View>((const char **) &data);
    root->dump();
    view = new View(*root);
    view->render();
    copy();
    while (getKey() != 3)
    {
      waitFlip();
      flip();
    }
}
#endif

  return 0;
}
示例#12
0
void Objectness::generateTrianData()
{
    const int NUM_TRAIN = _voc.trainNum;
    const int FILTER_SZ = _W*_W;
    vector<vector<Mat> > xTrainP(NUM_TRAIN), xTrainN(NUM_TRAIN);
    vector<vecI> szTrainP(NUM_TRAIN); // Corresponding size index.
    const int NUM_NEG_BOX = 100; // Number of negative windows sampled from each image

    #pragma omp parallel for
    for (int i = 0; i < NUM_TRAIN; i++)	{
        const int NUM_GT_BOX = (int)_voc.gtTrainBoxes[i].size();
        vector<Mat> &xP = xTrainP[i], &xN = xTrainN[i];
        vecI &szP = szTrainP[i];
        xP.reserve(NUM_GT_BOX*4), szP.reserve(NUM_GT_BOX*4), xN.reserve(NUM_NEG_BOX);
        Mat im3u = imread(format(_S(_voc.imgPathW), _S(_voc.trainSet[i])));

        // Get positive training data
        for (int k = 0; k < NUM_GT_BOX; k++) {
            const Vec4i& bbgt =  _voc.gtTrainBoxes[i][k];
            vector<Vec4i> bbs; // bounding boxes;
            vecI bbR; // Bounding box ratios
            int nS = gtBndBoxSampling(bbgt, bbs, bbR);
            for (int j = 0; j < nS; j++) {
                bbs[j][2] = min(bbs[j][2], im3u.cols);
                bbs[j][3] = min(bbs[j][3], im3u.rows);
                Mat mag1f = getFeature(im3u, bbs[j]), magF1f;
                flip(mag1f, magF1f, CV_FLIP_HORIZONTAL);
                xP.push_back(mag1f);
                xP.push_back(magF1f);
                szP.push_back(bbR[j]);
                szP.push_back(bbR[j]);
            }
        }
        // Get negative training data
        for (int k = 0; k < NUM_NEG_BOX; k++) {
            int x1 = rand() % im3u.cols + 1, x2 = rand() % im3u.cols + 1;
            int y1 = rand() % im3u.rows + 1, y2 = rand() % im3u.rows + 1;
            Vec4i bb(min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2));
            if (maxIntUnion(bb, _voc.gtTrainBoxes[i]) < 0.5)
                xN.push_back(getFeature(im3u, bb));
        }
    }

    const int NUM_R = _numT * _numT + 1;
    vecI szCount(NUM_R); // Object counts of each size (combination of scale and aspect ratio)
    int numP = 0, numN = 0, iP = 0, iN = 0;
    for (int i = 0; i < NUM_TRAIN; i++) {
        numP += xTrainP[i].size();
        numN += xTrainN[i].size();
        const vecI &rP = szTrainP[i];
        for (size_t j = 0; j < rP.size(); j++)
            szCount[rP[j]]++;
    }
    vecI szActive; // Indexes of active size
    for (int r = 1; r < NUM_R; r++) {
        if (szCount[r] > 50) // If only 50- positive samples at this size, ignore it.
            szActive.push_back(r-1);
    }
    matWrite(_modelName + ".idx", Mat(szActive));

    Mat xP1f(numP, FILTER_SZ, CV_32F), xN1f(numN, FILTER_SZ, CV_32F);
    for (int i = 0; i < NUM_TRAIN; i++)	{
        vector<Mat> &xP = xTrainP[i], &xN = xTrainN[i];
        for (size_t j = 0; j < xP.size(); j++)
            memcpy(xP1f.ptr(iP++), xP[j].data, FILTER_SZ*sizeof(float));
        for (size_t j = 0; j < xN.size(); j++)
            memcpy(xN1f.ptr(iN++), xN[j].data, FILTER_SZ*sizeof(float));
    }
    CV_Assert(numP == iP && numN == iN);
    matWrite(_modelName + ".xP", xP1f);
    matWrite(_modelName + ".xN", xN1f);
}
示例#13
0
void PS3_renderFrame(int sync) {
	drawFrame();
	flip(sync);
}
示例#14
0
void WebcamHandler::run()
{

	// initialize webcam
	VideoCapture cap = VideoCapture(0);
	cap.set(CV_CAP_PROP_FRAME_WIDTH, m_frameWidth);
	cap.set(CV_CAP_PROP_FRAME_HEIGHT, m_frameHeight);	

	// initialize window
	namedWindow("Settings", CV_WINDOW_AUTOSIZE);
	namedWindow("FaceRepair", CV_WINDOW_NORMAL);
	cvSetWindowProperty("FaceRepair", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);

	cvWaitKey(1000);

	float* hidden;
	float* visible;

	while (m_loop)
	{
		// read frame and continue with next frame if not successfull
		Mat frame;
		cap.retrieve(frame);
		flip(frame, frame, 1);

		// take subimage at faceArea
		Mat subimage;
		frame(*m_faceArea).copyTo(subimage);
		Mat subimageHSV;
		cvtColor(subimage, subimageHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV

		// detect color
		Mat mask;
		inRange(subimageHSV, *m_detectionColorMin, *m_detectionColorMax, mask);
		erode(mask, mask, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
		dilate(mask, mask, getStructuringElement(MORPH_ELLIPSE, Size(15, 15)));
		Mat invertedMask = 255 - mask;

		// scale to rbm input size
		Size size = Size(m_edgeLength, m_edgeLength);
		Mat scaledSubimage;	
		resize(subimage, scaledSubimage, size, 0.0, 0.0, INTER_LINEAR);
		Mat scaledMask;
		resize(mask, scaledMask, size, 0.0, 0.0, INTER_NEAREST);
		Mat invertedScaledMask = 255 - scaledMask;

		// calc mean rgb of preserved area
		Scalar bgr = mean(scaledSubimage, invertedScaledMask);

		// set mean rgb at reconstructionArea
		scaledSubimage.setTo(bgr, scaledMask);

		// subimage to normalized float array
		visible = matToNormalizedFloatArrayWithBias(&scaledSubimage);

		// process RBMs
		hidden = m_rbm1000->runHidden(visible, 1);
		delete visible;
		hidden[0] = 1;
		visible = m_rbm1000->runVisible(hidden, 1);
		delete hidden;
		visible[0] = 1;
		resetPreservedArea(&scaledSubimage, &invertedScaledMask, visible);

		hidden = m_rbm1500->runHidden(visible, 1);
		delete visible;
		hidden[0] = 1;
		visible = m_rbm1500->runVisible(hidden, 1);
		delete hidden;
		visible[0] = 1;
		resetPreservedArea(&scaledSubimage, &invertedScaledMask, visible);

		hidden = m_rbm2000->runHidden(visible, 1);
		delete visible;
		hidden[0] = 1;
		visible = m_rbm2000->runVisible(hidden, 1);
		delete hidden;

		// normalized float array to subimage
		normalizedFloatArrayToMatWithoutBias(visible, &scaledSubimage);

		// scale to original faceArea size
		Mat result;
		size = Size(m_faceArea->width, m_faceArea->height);
		resize(scaledSubimage, result, size, 0.0, 0.0, INTER_CUBIC);

		// reset pixels of preserved area in native resolution
		subimage.copyTo(result, invertedMask);

		// create fullscreen image
		Mat fs;
		frame.copyTo(fs);
		result.copyTo(fs(*m_faceArea));
		flip(fs, fs, 1);
		
		// maybe not necessary
		//result.copyTo(frame(*m_faceArea));
		
		// paint visualizations for settings image
		rectangle(frame, *m_faceArea, Scalar(0, 255, 0));
		Point* eyePositions = calculateEyePositions(m_faceArea, m_relativeEyePositionX, m_relativeEyePositionY);
		circle(frame, eyePositions[0], 4, Scalar(255, 255, 0));
		circle(frame, eyePositions[1], 4, Scalar(255, 255, 0));
		delete eyePositions;

		// show frames
		imshow("Settings", frame);
		imshow("FaceRepair", fs);
		
		// check keyboard input
		checkKeys();
	}
	// terminate webcam
	cap.release();
}
示例#15
0
BoardSetupDialog::BoardSetupDialog(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f),
    m_wheelCurrentDelta(0), m_selectedPiece(Empty), inDrag(false)
{
    setObjectName("BoardSetupDialog");
    ui.setupUi(this);

    QPushButton *pasteButton = ui.buttonBox->addButton(tr("Paste FEN"), QDialogButtonBox::ActionRole);
    copyButton = ui.buttonBox->addButton(tr("Copy FEN"), QDialogButtonBox::ApplyRole);
    btCopyText = ui.buttonBox->addButton(tr("Copy Text"), QDialogButtonBox::ApplyRole);

    restoreLayout();

    ui.boardView->configure();
    ui.boardView->setFlags(BoardView::IgnoreSideToMove | BoardView::SuppressGuessMove | BoardView::AllowCopyPiece);
    ui.boardView->showMoveIndicator(false);
    ui.boardView->showCoordinates(true);

    m_minDeltaWheel = AppSettings->getValue("/Board/minWheelCount").toInt();

    for(int piece = Empty; piece <= BlackPawn; piece++)
    {
        BoardSetupToolButton* button = new BoardSetupToolButton(this);
        button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
        button->setMinimumSize(QSize(10, 10));
        button->m_piece = (Piece)piece;
        if(piece == Empty)
        {
            button->m_pixmap = QPixmap(0, 0);
            ui.buttonLayout->addWidget(button, 6, 0);
        }
        else
        {
            button->m_pixmap = ui.boardView->theme().piece(Piece(piece));
            ui.buttonLayout->addWidget(button, (piece - 1) % 6, piece >= BlackKing);
        }
        connect(button, SIGNAL(signalDragStarted(QWidget*, QMouseEvent*)), this, SLOT(startDrag(QWidget*, QMouseEvent*)));
        connect(button, SIGNAL(signalClicked(Piece)), this, SLOT(labelClicked(Piece)));
        connect(this, SIGNAL(signalClearBackground(Piece)), button, SLOT(slotClearBackground(Piece)));
    }

    emit signalClearBackground(Empty);

    ui.buttonBoxTools->button(QDialogButtonBox::RestoreDefaults)->setText(tr("Clear"));
    connect(ui.buttonBoxTools->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), SLOT(slotClear()));
    connect(ui.buttonBoxTools->button(QDialogButtonBox::Reset), SIGNAL(clicked()), SLOT(slotReset()));

    connect(ui.boardView, SIGNAL(clicked(Square, int, QPoint, Square)), SLOT(slotSelected(Square, int)));
    connect(ui.boardView, SIGNAL(moveMade(Square, Square, int)), SLOT(slotMovePiece(Square, Square)));
    connect(ui.boardView, SIGNAL(copyPiece(Square, Square)), SLOT(slotCopyPiece(Square, Square)));
    connect(ui.boardView, SIGNAL(invalidMove(Square)), SLOT(slotInvalidMove(Square)));
    connect(ui.boardView, SIGNAL(wheelScrolled(int)), SLOT(slotChangePiece(int)));
    connect(ui.boardView, SIGNAL(pieceDropped(Square, Piece)), SLOT(slotDroppedPiece(Square, Piece)));
    connect(ui.toMoveButton, SIGNAL(clicked()), SLOT(slotToggleSide()));
    connect(ui.wkCastleCheck, SIGNAL(stateChanged(int)), SLOT(slotCastlingRights()));
    connect(ui.wqCastleCheck, SIGNAL(stateChanged(int)), SLOT(slotCastlingRights()));
    connect(ui.bkCastleCheck, SIGNAL(stateChanged(int)), SLOT(slotCastlingRights()));
    connect(ui.bqCastleCheck, SIGNAL(stateChanged(int)), SLOT(slotCastlingRights()));
    connect(ui.epCombo, SIGNAL(currentIndexChanged(int)), SLOT(slotEnPassantSquare()));
    connect(ui.halfmoveSpin, SIGNAL(valueChanged(int)), SLOT(slotHalfmoveClock()));
    connect(ui.moveSpin, SIGNAL(valueChanged(int)), SLOT(slotMoveNumber()));
    connect(ui.btFlipBoard, SIGNAL(clicked()), ui.boardView, SLOT(flip()));
    ui.btFlipBoard->setCheckable(true);

    connect(copyButton, SIGNAL(clicked()), SLOT(slotCopyFen()));
    connect(pasteButton, SIGNAL(clicked()), SLOT(slotPasteFen()));
    connect(btCopyText, SIGNAL(clicked()), SLOT(slotCopyText()));

    connect(ui.btFlipVertical, SIGNAL(clicked()), SLOT(mirrorVertical()));
    connect(ui.btFlipHorizontal, SIGNAL(clicked()), SLOT(mirrorHorizontal()));
    connect(ui.btSwapColor, SIGNAL(clicked()), SLOT(swapColors()));

    ui.tabWidget->setCurrentIndex(0);
}
示例#16
0
	void update() {
#ifdef INSTALL
		if(cam.update()) {
			ofPixels& pixels = cam.getColorPixels();
#else
		cam.update();
		if(cam.isFrameNew()) {
			ofPixels& pixels = cam.getPixelsRef();
#endif
			// next two could be replaced with one line
			ofxCv::rotate90(pixels, rotated, rotate ? 270 : 0);
			ofxCv:flip(rotated, rotated, 1);
			Mat rotatedMat = toCv(rotated);
			if(tracker.update(rotatedMat))  {
				ofVec2f position = tracker.getPosition();
				vector<FaceTrackerData*> neighbors = data.getNeighborsCount(position, neighborCount);
				FaceTrackerData curData;
				curData.load(tracker);
				if(!neighbors.empty()) {
					nearestData = *faceCompare.nearest(curData, neighbors);
					if(nearestData.label != lastLabel) {
						similar.loadImage(nearestData.getImageFilename());
#ifdef INSTALL
						whitePoint = getWhitePoint(similar);
#else
						whitePoint.set(1, 1, 1);
#endif
					}
					lastLabel = nearestData.label;
				}
				if(faceCompare.different(curData, currentData) && faceCompare.different(curData, neighbors)) {
					saveFace(curData, rotated);
					currentData.push_back(pair<ofVec2f, FaceTrackerData>(position, curData));
				}
			}
			presence.update(tracker.getFound());
			if(presence.wasTriggered()) {
				presenceFade.stop();
			}
			if(presence.wasUntriggered()) {
				for(int i = 0; i < currentData.size(); i++) {
					data.add(currentData[i].first, currentData[i].second);
				}
				currentData.clear();
				presenceFade.start();
			}
		}
	}
	void draw() {
		ofBackground(255);
		CGDisplayHideCursor(NULL);
		ofSetColor(255);
		if(similar.isAllocated()) {
			shader.begin();
			shader.setUniformTexture("tex", similar, 0);
			shader.setUniform3fv("whitePoint", (float*) &whitePoint);
			similar.draw(0, 0);
			shader.end();
		}
		ofPushStyle();
		if(presenceFade.getActive()) {
			ofSetColor(0, ofMap(presenceFade.get(), 0, 1, 0, 128));
			ofFill();
			ofRect(0, 0, ofGetWidth(), ofGetHeight());
			ofSetColor(255, ofMap(presenceFade.get(), 0, 1, 0, 32));
			data.drawBins();
			ofSetColor(255, ofMap(presenceFade.get(), 0, 1, 0, 64));
			data.drawData();
		}
		ofSetColor(255, 64);
		ofNoFill();
		if(!tracker.getFound()) {
			ofCircle(tracker.getPosition(), 10);
		}
		tracker.draw();
		ofPopStyle();
		
#ifndef INSTALL
		drawFramerate();
#endif
	}
示例#17
0
int start_ripping_gui(int ripping_flags)
{
    char *albumdir, *musicfilename, *file_path = 0;
    sacd_reader_t   *sacd_reader;
    scarletbook_handle_t *handle;
    scarletbook_output_t *output;
    msgType          dialog_type;
    int              area_idx, i, ret;

    uint32_t prev_upper_progress = 0;
    uint32_t prev_lower_progress = 0;
    uint32_t delta;

    int prev_current_track = 0;
    uint32_t prev_stats_total_sectors_processed = 0;
    uint32_t prev_stats_current_file_sectors_processed = 0;
    uint64_t tb_start, tb_freq;
    uint64_t tmp_total_ripping_sectors = 0;

    char progress_message[64];

    sysAtomicSet(&stats_total_sectors, 0);
    sysAtomicSet(&stats_total_sectors_processed, 0);
    sysAtomicSet(&stats_current_file_total_sectors, 0);
    sysAtomicSet(&stats_current_file_sectors_processed, 0); 
    sysAtomicSet(&stats_current_track, 0);
    sysAtomicSet(&stats_total_tracks, 0);

    sacd_reader = sacd_open("/dev_bdvd");
    if (sacd_reader) 
    {
        handle = scarletbook_open(sacd_reader, 0);

        if (check_disc_space(sacd_reader, handle, ripping_flags))
        {
            ret = sacd_authenticate(sacd_reader);
            if (ret != 0)
            {
                LOG(lm_main, LOG_ERROR, ("authentication failed: %x", ret));
            }

            // select the channel area
            area_idx = ((has_multi_channel(handle) && ripping_flags & RIP_MCH) || !has_two_channel(handle)) ? handle->mulch_area_idx : handle->twoch_area_idx;

            albumdir = get_album_dir(handle);

            output = scarletbook_output_create(handle, handle_status_update_track_callback, handle_status_update_progress_callback, safe_fwprintf);

            if (ripping_flags & RIP_ISO)
            {
                #define FAT32_SECTOR_LIMIT 2090000
                uint32_t total_sectors = sacd_get_total_sectors(sacd_reader);
                uint32_t sector_size = FAT32_SECTOR_LIMIT;
                uint32_t sector_offset = 0;
                if (total_sectors > FAT32_SECTOR_LIMIT)
                 {
                    musicfilename = (char *) malloc(512);
                    file_path = make_filename(output_device, 0, albumdir, "iso");
                    for (i = 1; total_sectors != 0; i++)
                    {
                        sector_size = min(total_sectors, FAT32_SECTOR_LIMIT);
                        snprintf(musicfilename, 512, "%s.%03d", file_path, i);
                        scarletbook_output_enqueue_raw_sectors(output, sector_offset, sector_size, musicfilename, "iso");
                        sector_offset += sector_size;
                        total_sectors -= sector_size;
                    }
                    free(file_path);
                    free(musicfilename);
                }
                else
                {
                    file_path = make_filename(output_device, 0, albumdir, "iso");
                    scarletbook_output_enqueue_raw_sectors(output, 0, total_sectors, file_path, "iso");
                    free(file_path);
                }
                tmp_total_ripping_sectors = sacd_get_total_sectors(sacd_reader);
            }
            else 
            {
                // do not overwrite previous dump
                get_unique_dir(output_device, &albumdir);

                // fill the queue with items to rip
                for (i = 0; i < handle->area[area_idx].area_toc->track_count; i++) 
                {
                    musicfilename = get_music_filename(handle, area_idx, i, 0);
                    if (ripping_flags & RIP_DSF)
                    {
                        file_path = make_filename(output_device, albumdir, musicfilename, "dsf");
                        scarletbook_output_enqueue_track(output, area_idx, i, file_path, "dsf", 
                            1 /* always decode to DSD */);
                    }
                    else if (ripping_flags & RIP_DSDIFF)
                    {
                        file_path = make_filename(output_device, albumdir, musicfilename, "dff");
                        scarletbook_output_enqueue_track(output, area_idx, i, file_path, "dsdiff", 
                            ((ripping_flags & RIP_2CH_DST || ripping_flags & RIP_MCH_DST) ? 0 : 1));
                    }

                    tmp_total_ripping_sectors += handle->area[area_idx].area_tracklist_offset->track_length_lsn[i];

                    free(musicfilename);
                    free(file_path);
                }

                file_path = make_filename(output_device, albumdir, 0, 0);
                LOG(lm_main, LOG_NOTICE, ("setting output folder to: %s", file_path));
                recursive_mkdir(file_path, 0777);
                free(file_path);
            }

            scarletbook_output_start(output);

            tb_freq = sysGetTimebaseFrequency();
            tb_start = __gettime(); 

            {
                char *message = (char *) malloc(512);

                file_path = make_filename(output_device, albumdir, 0, 0);
                snprintf(message, 512, "Title: %s\nOutput: %s\nFormat: %s\nSize: %.2fGB\nArea: %s\nEncoding: %s", 
                        substr(albumdir, 0, 100), 
                        file_path, 
                        (ripping_flags & RIP_DSDIFF ? "DSDIFF" : (ripping_flags & RIP_DSF ? "DSF" : "ISO")),
                        ((double) ((tmp_total_ripping_sectors * SACD_LSN_SIZE) / 1073741824.00)),
                        (ripping_flags & RIP_2CH ? "2ch" : "mch"),
                        (ripping_flags & RIP_2CH_DST || ripping_flags & RIP_MCH_DST ? "DST" : (ripping_flags & RIP_ISO ? "DECRYPTED" : "DSD"))
                        );
                free(file_path);

                dialog_action = 0;
                dialog_type   = MSG_DIALOG_MUTE_ON | MSG_DIALOG_DOUBLE_PROGRESSBAR;
                msgDialogOpen2(dialog_type, message, dialog_handler, NULL, NULL);
                while (!user_requested_exit() && dialog_action == 0 && scarletbook_output_is_busy(output))
                {
                    uint32_t tmp_stats_total_sectors_processed = sysAtomicRead(&stats_total_sectors_processed);
                    uint32_t tmp_stats_total_sectors = sysAtomicRead(&stats_total_sectors);
                    uint32_t tmp_stats_current_file_sectors_processed = sysAtomicRead(&stats_current_file_sectors_processed);
                    uint32_t tmp_stats_current_file_total_sectors = sysAtomicRead(&stats_current_file_total_sectors);
                    int tmp_current_track = sysAtomicRead(&stats_current_track);

                    if (tmp_current_track != 0 && tmp_current_track != prev_current_track)
                    {
                        memset(progress_message, 0, 64);
       
                        musicfilename = get_music_filename(handle, area_idx, tmp_current_track - 1, 0);
                        // HACK: substr is not thread safe, but it's only used in this thread..
                        snprintf(progress_message, 63, "Track (%d/%d): [%s...]", tmp_current_track, sysAtomicRead(&stats_total_tracks), substr(musicfilename, 0, 40));
                        free(musicfilename);

                        msgDialogProgressBarReset(MSG_PROGRESSBAR_INDEX0);
                        msgDialogProgressBarSetMsg(MSG_PROGRESSBAR_INDEX1, progress_message);
                        prev_upper_progress = 0;
                        prev_stats_current_file_sectors_processed = 0;

                        prev_current_track = tmp_current_track;
                    }

                    if (tmp_stats_total_sectors != 0 && prev_stats_total_sectors_processed != tmp_stats_total_sectors_processed)
                    {
                        delta = (tmp_stats_current_file_sectors_processed + (tmp_stats_current_file_sectors_processed - prev_stats_current_file_sectors_processed)) * 100 / tmp_stats_current_file_total_sectors - prev_upper_progress;
                        prev_upper_progress += delta;
                        msgDialogProgressBarInc(MSG_PROGRESSBAR_INDEX0, delta);

                        delta = (tmp_stats_total_sectors_processed + (tmp_stats_total_sectors_processed - prev_stats_total_sectors_processed)) * 100 / tmp_stats_total_sectors - prev_lower_progress;
                        prev_lower_progress += delta;
                        msgDialogProgressBarInc(MSG_PROGRESSBAR_INDEX1, delta);

                        snprintf(progress_message, 64, "Ripping %.1fMB/%.1fMB at %.2fMB/sec", 
                                ((float)(tmp_stats_current_file_sectors_processed * SACD_LSN_SIZE) / 1048576.00),
                                ((float)(tmp_stats_current_file_total_sectors * SACD_LSN_SIZE) / 1048576.00),
                                (float)((float) tmp_stats_total_sectors_processed * SACD_LSN_SIZE / 1048576.00) / (float)((__gettime() - tb_start) / (float)(tb_freq)));
                        
                        msgDialogProgressBarSetMsg(MSG_PROGRESSBAR_INDEX0, progress_message);
                        
                        prev_stats_total_sectors_processed = tmp_stats_total_sectors_processed;
                        prev_stats_current_file_sectors_processed = tmp_stats_current_file_sectors_processed;
                    }

                    sysUtilCheckCallback();
                    flip();
                }
                msgDialogAbort();
                free(message);
            }
            free(albumdir);

            scarletbook_output_destroy(output);
        }
        scarletbook_close(handle);
    }
    sacd_close(sacd_reader);

    if (user_requested_exit())
    {
        return 0;
    }
    else if (1)
    {
        dialog_type = (MSG_DIALOG_NORMAL | MSG_DIALOG_BTN_TYPE_OK | MSG_DIALOG_DISABLE_CANCEL_ON);
        msgDialogOpen2(dialog_type, "ripping process completed.", dialog_handler, NULL, NULL);

        dialog_action = 0;
        while (!dialog_action && !user_requested_exit())
        {
            sysUtilCheckCallback();
            flip();
        }
        msgDialogAbort();
    }

    return 0;
}
示例#18
0
文件: NoRSX.cpp 项目: wargio/NoRSX
NoRSX::NoRSX(int real_screen_type, int buffer_screen_type) : EventHandler(){
	screen_type = real_screen_type;
	buffer_type = buffer_screen_type;

	currentBuffer = 0;
	host_addr = memalign(1024*1024, HOST_SIZE);
	
	switch(real_screen_type){
		case RESOLUTION_1920x1080: {
			width=1920;height=1080;
			buffers[0].width=1920;buffers[0].height=1080;
			buffers[1].width=1920;buffers[1].height=1080;
		} break;
		case RESOLUTION_1280x720: {
			width=1280;height=720;
			buffers[0].width=1280;buffers[0].height=720;
			buffers[1].width=1280;buffers[1].height=720;
		} break;
		case RESOLUTION_720x576: {
			width=720;height=576;
			buffers[0].width=720;buffers[0].height=576;
			buffers[1].width=720;buffers[1].height=576;
		} break;
		case RESOLUTION_720x480: {
			width=720;height=480;
			buffers[0].width=720;buffers[0].height=480;
			buffers[1].width=720;buffers[1].height=480;
		} break;
		default:
			getResolution(&width,&height);
			switch(real_screen_type){
				default:
				case RESOLUTION_AUTO_LOWER_1080p: {
					if(height>=1080){
						real_screen_type = RESOLUTION_1280x720;
						width=1280;height=720;
						buffers[0].width=1280;buffers[0].height=720;
						buffers[1].width=1280;buffers[1].height=720;
					}else
						real_screen_type = RESOLUTION_AUTO;
				} break;
				case RESOLUTION_AUTO_LOWER_720p: {
					if(height>=720){
						real_screen_type = RESOLUTION_720x576;
						width=720;height=576;
						buffers[0].width=720;buffers[0].height=576;
						buffers[1].width=720;buffers[1].height=576;
					}else
						real_screen_type = RESOLUTION_AUTO;
				} break;
				case RESOLUTION_AUTO_LOWER_576p: {
					if(height>=576){
						real_screen_type = RESOLUTION_720x480;
						width=720;height=480;
						buffers[0].width=720;buffers[0].height=480;
						buffers[1].width=720;buffers[1].height=480;
					}else
						real_screen_type = RESOLUTION_AUTO;
				} break;
					real_screen_type = RESOLUTION_AUTO;
				break;
			}
		  break;
	}
	context = initScreen(host_addr, HOST_SIZE, real_screen_type, width, height);

	for(int i=0;i<2;i++)
		makeBuffer(&buffers[i],width,height,i);
	
	switch(buffer_screen_type){
		case RESOLUTION_1920x1080:
			width=1920; height=1080;
			break;
		case RESOLUTION_1280x720:
			width=1280; height=720;
			break;
		case RESOLUTION_720x576:
			width=720; height=576;
			break;
		case RESOLUTION_720x480:
			width=720; height=480;
			break;
		default:
			getResolution(&width,&height);
			break;
	}	
	
	buffer = makeMemBuffer(width,height,&buffer_size);
	buffer_size = buffers[0].width * buffers[0].height * sizeof(u32);
	
	
	flip(context, 0);
	setRenderTarget(context, &buffers[0]);
	RegisterCallBack(EVENT_SLOT0);
}
示例#19
0
void camera_feed()
{
	VideoCapture cap(0);
	if (cap.isOpened())
	{
		int distance[3], MUL = 1, dif = 0;
		char key;
		bool first_run = false, is_size_checked = false, moved = false, shoot = false;
		unsigned long max_contours_amount = 0;
		Point drawing_point, cursor, additional_point;
		vector<vector<Point>> contours, main_points;
		vector<Point> pen1, pen2, pens;
		vector<Vec4i> hierarchy;
		Mat frame, real_pic, drawing_frame, maze;
		Scalar low_boundry(45, 107, 52), high_boundry(86, 227, 160), color(100, 100, 100);
		//namedWindow("drawing_frame", 1);
		//namedWindow("frame", 1);
		cap >> frame;
		cursor = Point(20, 20);
		maze = imread("maze1.jpg");
		maze = maze / WHITE;
		maze = maze * WHITE;
		bitwise_not(maze, maze);
		
		

		RECT rect = { 0 }; // gaming stuff!
		HWND window = FindWindow("Chicken Invaders 5", "Chicken Invaders 5");
		Sleep(2000);
		if (window)
		{
			GetClientRect(window, &rect);
			SetForegroundWindow(window);
			SetActiveWindow(window);
			SetFocus(window);
		}

		while (true)
		{
			shoot = false;
			cap >> frame;
			real_pic = frame.clone();
			while (main_points.size() != 0)
			{
				main_points.pop_back();
			}
			if (!first_run)
			{
				drawing_frame = real_pic.clone();
				resize(drawing_frame, drawing_frame, Size(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN) - 50));
				resize(maze, maze, Size(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN) - 50));
				first_run = true;
			}
			flip(real_pic, real_pic, 1);

			cvtColor(frame, frame, COLOR_BGR2HSV);
			
			inRange(frame, low_boundry, high_boundry, frame);
			flip(frame, frame, 1);

			contours.clear();
			resize(frame, frame, Size(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)));
			findContours(frame, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
			is_size_checked = false;
			if (contours.size() != 0)
			{
				for (vector<vector<Point>>::iterator it = contours.begin(); it != contours.end(); it++)
				{
					if (it->size() > max_contours_amount * 0.7)
					{
						main_points.push_back(*it);
						max_contours_amount = it->size();
						is_size_checked = true;
					}
				}
			}
			if (is_size_checked)
			{
				moved = false;
				drawing_point = stabilized_point(main_points[0]);
				if (main_points.size() == 2)
				{
					if (stabilized_point(main_points[0]).x < stabilized_point(main_points[1]).x)
					{
						drawing_point = stabilized_point(main_points[1]);
						
					}
					shoot = true;
				}
				drawing_point.x += (drawing_point.x - drawing_frame.size().width / 2) / 10;
				drawing_point.y += (drawing_point.y - drawing_frame.size().height / 2) / 10;
				while (drawing_point.x > maze.size().width)
				{
					drawing_point.x--;
				}
				while (drawing_point.x < 0)
				{
					drawing_point.x++;

				}
				while (drawing_point.y > maze.size().height)
				{
					drawing_point.y--;
				}
				while (drawing_point.y < 0)
				{
					drawing_point.y++;
				}

				distance[0] = drawing_point.x - cursor.x;
				distance[1] = drawing_point.y - cursor.y;
				while (distance[0] != 0 && distance[1] != 0)
				{
					if (maze.at<Vec3b>(Point(cursor.x + distance[0] / 15, cursor.y))[0] != WHITE)
					{
						cursor.x += distance[0] / 15;
						distance[0] /= 15;
						moved = true;
					}
					if (maze.at<Vec3b>(Point(cursor.x, cursor.y + distance[1] / 15))[0] != WHITE)
					{
						cursor.y += distance[1] / 15;
						distance[1] /= 15;
						moved = true;
					}				
					if (!moved)
					{
						putText(drawing_frame, "Struck a wall!", Point(0, 40), FONT_HERSHEY_COMPLEX_SMALL, 1, Scalar(WHITE, WHITE, BLACK, 1), 1, CV_AA);
						distance[0] = 0;
						distance[1] = 0;
					}
					
				}
				SetCursorPos(drawing_point.x, drawing_point.y); // gaming stuff!
				circle(drawing_frame, cursor, 13, Scalar(WHITE, BLACK, WHITE), 2);
				circle(drawing_frame, drawing_point, 13, Scalar(WHITE, BLACK, WHITE), -1);
				//circle(drawing_frame, stabilized_point(pen1), 13, Scalar(WHITE, WHITE, BLACK), -1);
			}
			else
			{
				putText(drawing_frame, "Lost drawing object!", Point(0, 20), FONT_HERSHEY_COMPLEX_SMALL, 1, Scalar(WHITE, WHITE, BLACK, 1), 1, CV_AA);
				circle(drawing_frame, cursor, 13, Scalar(WHITE, WHITE, BLACK), 3);
			}
			if (shoot)
			{
				LeftClick(drawing_point.x, drawing_point.y);
			}
			key = waitKey(10);

			drawing_frame = maze + drawing_frame;
			bitwise_not(drawing_frame, drawing_frame);
			//imshow("drawing_frame", drawing_frame);
			//imshow("frame", frame);

			frame = BLACK;
			drawing_frame = BLACK;
			real_pic = BLACK;

		}
	}
示例#20
0
文件: plasma.c 项目: ETroll/toaruos
int main (int argc, char ** argv) {
	yctx = yutani_init();

	win_width  = 100;
	win_height = 100;

	init_decorations();

	off_x = decor_left_width;
	off_y = decor_top_height;

	/* Do something with a window */
	wina = yutani_window_create(yctx, win_width + decor_width(), win_height + decor_height());
	yutani_window_move(yctx, wina, 300, 300);

	ctx = init_graphics_yutani_double_buffer(wina);

	draw_fill(ctx, rgb(0,0,0));
	redraw_borders();
	flip(ctx);
	yutani_flip(yctx, wina);

	yutani_window_advertise(yctx, wina, "Graphics Test");

	pthread_t thread;
	pthread_create(&thread, NULL, draw_thread, NULL);

	while (!should_exit) {
		yutani_msg_t * m = yutani_poll(yctx);
		if (m) {
			switch (m->type) {
				case YUTANI_MSG_KEY_EVENT:
					{
						struct yutani_msg_key_event * ke = (void*)m->data;
						if (ke->event.action == KEY_ACTION_DOWN && ke->event.keycode == 'q') {
							should_exit = 1;
						}
					}
					break;
				case YUTANI_MSG_WINDOW_FOCUS_CHANGE:
					{
						struct yutani_msg_window_focus_change * wf = (void*)m->data;
						yutani_window_t * win = hashmap_get(yctx->windows, (void*)wf->wid);
						if (win) {
							win->focused = wf->focused;
						}
					}
					break;
				case YUTANI_MSG_SESSION_END:
					should_exit = 1;
					break;
				case YUTANI_MSG_RESIZE_OFFER:
					{
						struct yutani_msg_window_resize * wr = (void*)m->data;
						spin_lock(&draw_lock);
						resize_finish(wr->width, wr->height);
						spin_unlock(&draw_lock);
					}
					break;
				case YUTANI_MSG_WINDOW_MOUSE_EVENT:
					if (decor_handle_event(yctx, m) == DECOR_CLOSE) {
						should_exit = 1;
					}
					break;
				default:
					break;
			}
			free(m);
		}
	}

	yutani_close(yctx, wina);
	return 0;
}
NxU16 readWord(bool mismatch, const NxStream& stream)
	{
	NxU16 d = stream.readWord();
	if(mismatch)	d = flip(&d);
	return d;
	}
示例#22
0
void CglGMI::generateCuts(OsiCuts &cs)
{
  isInteger = new bool[ncol]; 
  
  computeIsInteger();

  cstat = new int[ncol];
  rstat = new int[nrow];


  solver->getBasisStatus(cstat, rstat);   // 0: free  1: basic  
                                          // 2: upper 3: lower


#if defined GMI_TRACETAB
  printvecINT("cstat", cstat, ncol);
  printvecINT("rstat", rstat, nrow);
#endif

  // list of basic integer fractional variables
  int *listFracBasic = new int[nrow];
  int numFracBasic = 0;
  for (int i = 0; i < ncol; ++i) {
    // j is the variable which is basic in row i
    if ((cstat[i] == 1) && (isInteger[i])) {
      if (CoinMin(aboveInteger(xlp[i]),
		  1-aboveInteger(xlp[i])) > param.getAway()) {
	listFracBasic[numFracBasic] = i;
	numFracBasic++;
      }
#if defined TRACK_REJECT || defined TRACK_REJECT_SIMPLE
      else if (trackRejection) {	
	// Say that we tried to generate a cut, but it was discarded
	// because of small fractionality
	if (!isIntegerValue(xlp[i])) {
	  fracFail++;
	  numGeneratedCuts++;
	}
      }
#endif
    }
  }

#if defined GMI_TRACE
  printf("CglGMI::generateCuts() : %d fractional rows\n", numFracBasic);
#endif
  
  if (numFracBasic == 0) {
    delete[] listFracBasic;
    delete[] cstat;
    delete[] rstat;
    delete[] isInteger;
    return;
  }

  // there are rows with basic integer fractional variables, so we can
  // generate cuts

  // Basis index for columns and rows; each element is -1 if corresponding
  // variable is nonbasic, and contains the basis index if basic.
  // The basis index is the row in which the variable is basic.
  int* colBasisIndex = new int[ncol];
  int* rowBasisIndex = new int[nrow];

#if defined OSI_TABLEAU
  memset(colBasisIndex, -1, ncol*sizeof(int));
  memset(rowBasisIndex, -1, nrow*sizeof(int));
  solver->enableFactorization();
  int* basicVars = new int[nrow];
  solver->getBasics(basicVars);
  for (int i = 0; i < nrow; ++i) {
    if (basicVars[i] < ncol) {
      colBasisIndex[basicVars[i]] = i;
    }
    else {
      rowBasisIndex[basicVars[i] - ncol] = i;
    }
  }
#else
  CoinFactorization factorization;
  if (factorize(factorization, colBasisIndex, rowBasisIndex)) {
    printf("### WARNING: CglGMI::generateCuts(): error during factorization!\n");
    return;
  }
#endif


  // cut in sparse form
  double* cutElem = new double[ncol];
  int* cutIndex = new int[ncol];
  int cutNz = 0;
  double cutRhs;

  // cut in dense form
  double* cut = new double[ncol];

  double *slackVal = new double[nrow];

  for (int i = 0; i < nrow; ++i) {
    slackVal[i] = rowRhs[i] - rowActivity[i];
  }

#if defined OSI_TABLEAU
  // Column part and row part of a row of the simplex tableau
  double* tableauColPart = new double[ncol];
  double* tableauRowPart = new double[nrow];
#else
  // Need some more data for simplex tableau computation
  const int * row = byCol->getIndices();
  const CoinBigIndex * columnStart = byCol->getVectorStarts();
  const int * columnLength = byCol->getVectorLengths(); 
  const double * columnElements = byCol->getElements();

  // Create work arrays for factorization
  // two vectors for updating: the first one is needed to do the computations
  // but we do not use it, the second one contains a row of the basis inverse
  CoinIndexedVector work;
  CoinIndexedVector array;
  // Make sure they large enough
  work.reserve(nrow);
  array.reserve(nrow);
  int * arrayRows = array.getIndices();
  double * arrayElements = array.denseVector();
  // End of code to create work arrays
  double one = 1.0;
#endif

  // Matrix elements by row for slack substitution
  const double *elements = byRow->getElements();
  const int *rowStart = byRow->getVectorStarts();
  const int *indices = byRow->getIndices();
  const int *rowLength = byRow->getVectorLengths(); 

  // Indices of basic and slack variables, and cut elements
  int iBasic, slackIndex;
  double cutCoeff;
  double rowElem;
  // Now generate the cuts: obtain a row of the simplex tableau
  // where an integer variable is basic and fractional, and compute the cut
  for (int i = 0; i < numFracBasic; ++i) {
    if (!computeCutFractionality(xlp[listFracBasic[i]], cutRhs)) {
      // cut is discarded because of the small fractionalities involved
#if defined TRACK_REJECT || defined TRACK_REJECT_SIMPLE
      if (trackRejection) {	
	// Say that we tried to generate a cut, but it was discarded
	// because of small fractionality
	fracFail++;
	numGeneratedCuts++;
      }
#endif
      continue;
    }

    // the variable listFracBasic[i] is basic in row iBasic
    iBasic = colBasisIndex[listFracBasic[i]];

#if defined GMI_TRACE
    printf("Row %d with var %d basic, f0 = %f\n", i, listFracBasic[i], f0);
#endif

#if defined OSI_TABLEAU
    solver->getBInvARow(iBasic, tableauColPart, tableauRowPart);
#else
    array.clear();
    array.setVector(1, &iBasic, &one);

    factorization.updateColumnTranspose (&work, &array);

    int numberInArray=array.getNumElements();
#endif

    // reset the cut
    memset(cut, 0, ncol*sizeof(double));

    // columns
    for (int j = 0; j < ncol; ++j) {
      if ((colBasisIndex[j] >= 0) || 
	  (areEqual(colLower[j], colUpper[j], 
		    param.getEPS(), param.getEPS()))) {
	// Basic or fixed variable -- skip
	continue;
      }
#ifdef OSI_TABLEAU
      rowElem = tableauColPart[j];
#else
      rowElem = 0.0;
      // add in row of tableau
      for (int h = columnStart[j]; h < columnStart[j]+columnLength[j]; ++h) {
	rowElem += columnElements[h]*arrayElements[row[h]];
      }
#endif
      if (!isZero(fabs(rowElem))) {
	// compute cut coefficient
	flip(rowElem, j);
	cutCoeff = computeCutCoefficient(rowElem, j);
	if (isZero(cutCoeff)) {
	  continue;
	}
	unflipOrig(cutCoeff, j, cutRhs);
	cut[j] = cutCoeff;
#if defined GMI_TRACE
	printf("var %d, row %f, cut %f\n", j, rowElem, cutCoeff);
#endif
      }
    }

    // now do slacks part
#if defined OSI_TABLEAU
    for (int j = 0 ; j < nrow; ++j) {
      // index of the row corresponding to the slack variable
      slackIndex = j;
      if (rowBasisIndex[j] >= 0) {
	// Basic variable -- skip it
	continue;
      }
      rowElem = tableauRowPart[j];
#else
    for (int j = 0 ; j < numberInArray ; ++j) {
      // index of the row corresponding to the slack variable
      slackIndex = arrayRows[j];
      rowElem = arrayElements[slackIndex];
#endif
      if (!isZero(fabs(rowElem))) {
	slackIndex += ncol;
	// compute cut coefficient
	flip(rowElem, slackIndex);
	cutCoeff = computeCutCoefficient(rowElem, slackIndex);
	if (isZero(fabs(cutCoeff))) {
	  continue;
	}
	unflipSlack(cutCoeff, slackIndex, cutRhs, slackVal);
	eliminateSlack(cutCoeff, slackIndex, cut, cutRhs,
		       elements, rowStart, indices, rowLength, rowRhs);
#if defined GMI_TRACE
	printf("var %d, row %f, cut %f\n", slackIndex, rowElem, cutCoeff);
#endif
      }
    }

    packRow(cut, cutElem, cutIndex, cutNz);
    if (cutNz == 0)
      continue;

#if defined GMI_TRACE
    printvecDBL("final cut:", cutElem, cutIndex, cutNz);
    printf("cutRhs: %f\n", cutRhs);
#endif
    
#if defined TRACK_REJECT || defined TRACK_REJECT_SIMPLE
    if (trackRejection) {
      numGeneratedCuts++;
    }
#endif
    if (cleanCut(cutElem, cutIndex, cutNz, cutRhs, xlp) && cutNz > 0) {
      OsiRowCut rc;
      rc.setRow(cutNz, cutIndex, cutElem);
      rc.setLb(-param.getINFINIT());
      rc.setUb(cutRhs);
      if (!param.getCHECK_DUPLICATES()) {
	cs.insert(rc);
      }
      else{
	cs.insertIfNotDuplicate(rc, CoinAbsFltEq(param.getEPS_COEFF()));
      }
    }

  }

#if defined GMI_TRACE
  printf("CglGMI::generateCuts() : number of cuts : %d\n", cs.sizeRowCuts());
#endif

#if defined OSI_TABLEAU
  solver->disableFactorization();
  delete[] basicVars;
  delete[] tableauColPart;
  delete[] tableauRowPart;
#endif

  delete[] colBasisIndex;
  delete[] rowBasisIndex;
  delete[] cut;
  delete[] slackVal;
  delete[] cutElem;
  delete[] cutIndex;
  delete[] listFracBasic;
  delete[] cstat;
  delete[] rstat;
  delete[] isInteger;

} /* generateCuts */

/***********************************************************************/
void CglGMI::setParam(const CglGMIParam &source) {
  param = source;
} /* setParam */

/***********************************************************************/
void CglGMI::computeIsInteger() {
  for (int i = 0; i < ncol; ++i) {
    if(solver->isInteger(i)) {
      isInteger[i] = true;
    }
    else {
      if((areEqual(colLower[i], colUpper[i], 
		   param.getEPS(), param.getEPS()))
	 && (isIntegerValue(colUpper[i]))) {	
	// continuous variable fixed to an integer value
	isInteger[i] = true;
      }
      else {
	isInteger[i] = false;
      }
    }
  }    
} /* computeIsInteger */

/***********************************************************************/
void CglGMI::printOptTab(OsiSolverInterface *lclSolver) const
{
  int *cstat = new int[ncol];
  int *rstat = new int[nrow];

  lclSolver->enableFactorization();
  lclSolver->getBasisStatus(cstat, rstat);   // 0: free  1: basic  
  // 2: upper 3: lower

  int *basisIndex = new int[nrow]; // basisIndex[i] = 
                                    //        index of pivot var in row i
                                    //        (slack if number >= ncol) 
  lclSolver->getBasics(basisIndex);

  double *z = new double[ncol];  // workspace to get row of the tableau
  double *slack = new double[nrow];  // workspace to get row of the tableau
  double *slackVal = new double[nrow];

  for (int i = 0; i < nrow; i++) {
    slackVal[i] = rowRhs[i] - rowActivity[i];
  }

  const double *rc = lclSolver->getReducedCost();
  const double *dual = lclSolver->getRowPrice();
  const double *solution = lclSolver->getColSolution();

  printvecINT("cstat", cstat, ncol);
  printvecINT("rstat", rstat, nrow);
  printvecINT("basisIndex", basisIndex, nrow);

  printvecDBL("solution", solution, ncol);
  printvecDBL("slackVal", slackVal, nrow);
  printvecDBL("reduced_costs", rc, ncol);
  printvecDBL("dual solution", dual, nrow);

  printf("Optimal Tableau:\n");

  for (int i = 0; i < nrow; i++) {
    lclSolver->getBInvARow(i, z, slack);
    for (int ii = 0; ii < ncol; ++ii) {
      printf("%5.2f ", z[ii]);
    }
    printf(" | ");
    for (int ii = 0; ii < nrow; ++ii) {
      printf("%5.2f ", slack[ii]);
    }
    printf(" | ");
    if(basisIndex[i] < ncol) {
      printf("%5.2f ", solution[basisIndex[i]]);
    }
    else {
      printf("%5.2f ", slackVal[basisIndex[i]-ncol]);
    }
    printf("\n");
  }
  for (int ii = 0; ii < 7*(ncol+nrow+1); ++ii) {
    printf("-");
  }
  printf("\n");

  for (int ii = 0; ii < ncol; ++ii) {
    printf("%5.2f ", rc[ii]);    
  }
  printf(" | ");
  for (int ii = 0; ii < nrow; ++ii) {
    printf("%5.2f ", -dual[ii]);
  }
  printf(" | ");
  printf("%5.2f\n", -lclSolver->getObjValue());
  lclSolver->disableFactorization();

  delete[] cstat;
  delete[] rstat;
  delete[] basisIndex;
  delete[] slack;
  delete[] z;
  delete[] slackVal;
} /* printOptTab */
NxF32 readFloat(bool mismatch, const NxStream& stream)
	{
	NxU32 d = stream.readDword();
	if(mismatch)	d = flip(&d);
	return FR(d);
	}
示例#24
0
 /// Post constraint on \a x
 virtual void post(Gecode::Space& home, Gecode::FloatVarArray& x) {
   if (flip())
     Gecode::exp(home, x[0], x[1]);
   else
     Gecode::rel(home, exp(x[0]) == x[1]);
 }
void writeFloat(NxF32 value, bool mismatch, NxStream& stream)
	{
	if(mismatch)	value = flip(&value);
	stream.storeFloat(value);
	}
示例#26
0
float cv::intersectConvexConvex( InputArray _p1, InputArray _p2, OutputArray _p12, bool handleNested )
{
    Mat p1 = _p1.getMat(), p2 = _p2.getMat();
    CV_Assert( p1.depth() == CV_32S || p1.depth() == CV_32F );
    CV_Assert( p2.depth() == CV_32S || p2.depth() == CV_32F );
    
    int n = p1.checkVector(2, p1.depth(), true);
    int m = p2.checkVector(2, p2.depth(), true);
    
    CV_Assert( n >= 0 && m >= 0 );
    
    if( n < 2 || m < 2 )
    {
        _p12.release();
        return 0.f;
    }
    
    AutoBuffer<Point2f> _result(n*2 + m*2 + 1);
    Point2f *fp1 = _result, *fp2 = fp1 + n;
    Point2f* result = fp2 + m;
    int orientation = 0;
    
    for( int k = 1; k <= 2; k++ )
    {
        Mat& p = k == 1 ? p1 : p2;
        int len = k == 1 ? n : m;
        Point2f* dst = k == 1 ? fp1 : fp2;
        
        Mat temp(p.size(), CV_MAKETYPE(CV_32F, p.channels()), dst);
        p.convertTo(temp, CV_32F);
        CV_Assert( temp.ptr<Point2f>() == dst );
        Point2f diff0 = dst[0] - dst[len-1];
        for( int i = 1; i < len; i++ )
        {
            double s = diff0.cross(dst[i] - dst[i-1]);
            if( s != 0 )
            {
                if( s < 0 )
                {
                    orientation++;
                    flip( temp, temp, temp.rows > 1 ? 0 : 1 );
                }
                break;
            }
        }
    }
    
    float area = 0.f;
    int nr = intersectConvexConvex_(fp1, n, fp2, m, result, &area);
    if( nr == 0 )
    {
        if( !handleNested )
        {
            _p12.release();
            return 0.f;
        }
        
        if( pointPolygonTest(_InputArray(fp1, n), fp2[0], false) >= 0 )
        {
            result = fp2;
            nr = m;
        }
        else if( pointPolygonTest(_InputArray(fp2, n), fp1[0], false) >= 0 )
        {
            result = fp1;
            nr = n;
        }
        else
        {
            _p12.release();
            return 0.f;
        }
        area = (float)contourArea(_InputArray(result, nr), false);
    }
    
    if( _p12.needed() )
    {
        Mat temp(nr, 1, CV_32FC2, result);
        // if both input contours were reflected,
        // let's orient the result as the input vectors
        if( orientation == 2 )
            flip(temp, temp, 0);

        temp.copyTo(_p12);
    }
    return (float)fabs(area);
}
示例#27
0
int main(int argc, const char *argv[])
{
   ALLEGRO_EVENT event;
   ALLEGRO_KEYBOARD_STATE kst;
   bool blend;

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
      return 1;
   }

   al_init_primitives_addon();
   al_install_keyboard();
   al_install_mouse();

   display = al_create_display(W, H);
   if (!display) {
      abort_example("Error creating display\n");
      return 1;
   }

   black = al_map_rgb_f(0.0, 0.0, 0.0);
   white = al_map_rgb_f(1.0, 1.0, 1.0);
   background = al_map_rgb_f(0.5, 0.5, 0.6);

   if (argc > 1 && 0 == strcmp(argv[1], "--memory-bitmap")) {
      al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   }
   dbuf = al_create_bitmap(W, H);
   if (!dbuf) {
      abort_example("Error creating double buffer\n");
      return 1;
   }

   al_set_target_bitmap(dbuf);
   al_clear_to_color(background);
   draw_clip_rect();
   flip();

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_mouse_event_source());

   while (true) {
      al_wait_for_event(queue, &event);
      if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
         al_get_keyboard_state(&kst);
         blend = al_key_down(&kst, ALLEGRO_KEY_LSHIFT) ||
            al_key_down(&kst, ALLEGRO_KEY_RSHIFT);
         if (event.mouse.button == 1) {
            plonk(event.mouse.x, event.mouse.y, blend);
         } else {
            splat(event.mouse.x, event.mouse.y, blend);
         }
      }
      else if (event.type == ALLEGRO_EVENT_DISPLAY_SWITCH_OUT) {
         last_x = last_y = -1;
      }
      else if (event.type == ALLEGRO_EVENT_KEY_DOWN &&
         event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
      {
         break;
      }
   }

   al_destroy_event_queue(queue);
   al_destroy_bitmap(dbuf);

   return 0;
}
示例#28
0
文件: RIAR.cpp 项目: osilvam/Practica
int main(int argc, char* argv[])
{
    srand (time(0));    

    if(argc < 4)
    {
        cerr << "ERROR: The number of arguments is incorrect" << endl << "Enter:\targ_1 = user_definition_file\t arg_2 = genetic_encoding_file\t arg_3 = port_number";
        return -1;
    }

    if(system((char*)"mkdir -p NEAT_organisms") == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to create folder 'NEAT_organisms'" << endl;
    }

    if(system("rm -f NEAT_organisms/*") == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to remove files inside of 'NEAT_organisms'" << endl;
    }

    SimFiles * simfile = new SimFiles();
    Fitness * fitness = new Fitness();
    RobotVREP * vrep = new RobotVREP(false, atoi(argv[3]));   

    // ============= VREP INITIALIZATIONS ============= //
    
    Joint * rightWheel = new Joint((char*)"SCALE", (char*)"motor_der");
    Joint * leftWheel = new Joint((char*)"SCALE", (char*)"motor_izq");
    vrep->addJoint(rightWheel);
    vrep->addJoint(leftWheel);

    VisionSensor * visionSensor = new VisionSensor((char*)"VisionSensor");
    vrep->addVisionSensor(visionSensor);

    Object * centerDummy = new Object((char*)"modi_dummy");
    Object * Modi = new Object((char*)"MODI");
    vrep->addObject(centerDummy);
    vrep->addObject(Modi);
    
    CollisionObject * chasis = new CollisionObject((char*)"Collision_MODI_1#");
    CollisionObject * rueda1 = new CollisionObject((char*)"Collision_MODI_2#");
    CollisionObject * rueda2 = new CollisionObject((char*)"Collision_MODI_3#");
    vrep->addCollisionObject(chasis);
    vrep->addCollisionObject(rueda1);
    vrep->addCollisionObject(rueda2);
    vector < CollisionObject * > structure = {chasis, rueda1, rueda2};
    
    vector < Object * > cubes;

    // Set random position of Obstacles

    double y0 = -2;

    for(int cp_y = 0; cp_y < 9; cp_y++)
    {   
        double x0 = -2 + 0.25*(cp_y%2);

        for(int cp_x = 0; cp_x < 8 + (cp_y + 1)%2; cp_x++)
        {            
            if(9*cp_y + cp_x != 40)
            {
                stringstream sstm1;
                sstm1 << "Obstacle" << 9*cp_y+cp_x<< "#";

                Object * obstacle = new Object((char*)sstm1.str().c_str());
                vrep->addObject(obstacle);

                double rand1 = rand()%201 - 100;
                double rand2 = rand()%201 - 100;

                vector < double > position;

                position.push_back(x0 + rand1/100*.10);
                position.push_back(y0 + rand2/100*.10);
                position.push_back(0.05);

                vrep->setObjectPosition(obstacle, position);

                cubes.push_back(obstacle);
            }

            x0 = x0 + 0.5;
        }

        y0 = y0 + 0.5;
    }

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

    // ========== NEAT INITIALIZATIONS =========== //

    vector < double > output(2,0.0);
    vector < double > input(NX*NY+2,0.0);

    Population population(argv[1], argv[2], (char *)"NEAT_RIAR", (char *)"./NEAT_organisms");

    // ================================================ //
    
    namedWindow( "Display window", WINDOW_AUTOSIZE ); // Create a window for display.

    int finalChampionGeneration = 0;
    int finalChampionPopulation = 0;
    double finalChampionFitness = 0.0;

    for(int g = 0; g < population.GENERATIONS; g++)
    {
        fitness->resetGenerationValues();

        int generationChampionPopulation = 0;
        double generationChampionFitness = 0.0;
     
        for(int p = 0; p < population.POPULATION_MAX; p++)
        {
            fitness->resetPopulationValues();

            int sim_time = 0;
            bool flag = true;
            int flag_times = 0;
            double rightVel = 0.0;
            double leftVel = 0.0;

            vrep->setJointTargetVelocity(rightWheel, 0.0);
            vrep->setJointTargetVelocity(leftWheel, 0.0);

            double rand1 = rand()%201 - 100;
            double rand2 = rand()%201 - 100;
            double rand3 = rand()%201 - 100;

            vector < double > position, orientation;

            position.push_back(rand1/100*.10);
            position.push_back(rand2/100*.10);
            position.push_back(0.03011);

            orientation.push_back(0);
            orientation.push_back(0);
            orientation.push_back(rand3/100*M_PI);
            
            vrep->setObjectPosition(Modi, position);
            vrep->setObjectOrientation(Modi, orientation);

            unsigned char * image;
            Mat frameRGB = Mat(NX, NY, CV_8UC3);
            Mat frameGRAY = Mat(NX, NY, CV_8UC1);

            stringstream message1, message2, video_name;            

            message1 << "Generation " << g << " Population " << p;
            vrep->addStatusbarMessage((char*)message1.str().c_str());

            video_name << "G" << g << "P" << p;
            //vrep->changeVideoName((char *)video_name.str().c_str(), simx_opmode_oneshot_wait);

            simfile->openRobotMovementFile(g, p);
            simfile->openRobotMotorVelocityFile(g, p);
            
            clog << "=======  G" << g << " P" << p << "  =======  " << endl;

            vrep->startSimulation(simx_opmode_oneshot_wait);

            timeval tv1, tv2;       
            gettimeofday(&tv1, NULL);            

            while(sim_time < TIME_SIMULATION && flag)
            {            
                image = vrep->getVisionSensorImage(visionSensor);  
                frameRGB.data = image;
                flip(frameRGB, frameRGB, 0);
                cvtColor(frameRGB,frameGRAY,CV_BGR2GRAY);
                
                Mat tmp = frameGRAY;
                Mat frame = tmp;

                resize(tmp, frame, Size(0,0) , 6.0, 6.0, (int)INTER_NEAREST );
                imshow( "Display window", frame );
                waitKey(10);

                for(int i = 0; i < NY; i++)
                {
                    for(int j = 0;j < NX; j++)
                    {
                        input.at(i*NX + j) = (double)frame.at<uchar>(i,j)/255*2-1;
                    }
                }
                
                input.at(NX*NY) = (double)((2.0/(MAX_VEL - MIN_VEL))*(rightVel - MIN_VEL) - 1.0);
                input.at(NX*NY + 1) = (double)((2.0/(MAX_VEL - MIN_VEL))*(leftVel - MIN_VEL) - 1.0);

                output = population.organisms.at(p).eval(input);

                rightVel = output.at(0) + rightVel;
                leftVel = output.at(1) + leftVel;

                if(rightVel > MAX_VEL) rightVel = MAX_VEL;
                else if(rightVel < MIN_VEL) rightVel = MIN_VEL;
                if(leftVel > MAX_VEL) leftVel = MAX_VEL;
                else if(leftVel < MIN_VEL) leftVel = MIN_VEL;

                vrep->setJointTargetVelocity(rightWheel,-rightVel);
                vrep->setJointTargetVelocity(leftWheel,leftVel);                                              

                if(sim_time > TIME_INIT_MEASURING)
                {
                    position = vrep->getObjectPosition(centerDummy);
                    orientation = vrep->getObjectOrientation(centerDummy);

                    simfile->addRobotMovementFile((double)sim_time/1000000.0, position, orientation.at(2));
                    simfile->addRobotMotorVelocityFile((double)sim_time/1000000.0, rightVel, leftVel);

                    fitness->measuringValues(position, rightVel, leftVel, vrep->readCollision(structure));

                    if (abs(orientation.at(0)) > 0.78 || abs(orientation.at(1)) > 0.78)
                    {
                        flag_times++;
                        if(flag_times > 10) flag = false;
                    }else
                        flag_times = 0;
                }                         

                usleep(DELTA_TIME - EXECUTION_TIME);
                sim_time += DELTA_TIME;
            }            

            vrep->stopSimulation(simx_opmode_oneshot_wait);

            gettimeofday(&tv2, NULL);
            long int simulationtime = ((tv2.tv_sec - tv1.tv_sec)*1000000L + tv2.tv_usec) - tv1.tv_usec;   

            simfile->closeRobotMovementFile();
            simfile->closeRobotMotorVelocityFile();  

            if (flag)
            {                
                population.organisms.at(p).fitness = fitness->calculateFitness();             
                simfile->addFileResults(fitness->getFitness(), g, p);

                clog << "Fitness:\t" << fitness->getFitness() << endl;
                clog << "Distance:\t" << fitness->getDistance() << endl;
                clog << "Tiempo de simulación:\t" << (double)simulationtime/1000000 << endl;
                clog << endl;            

                message2 << "FITNESS : " << fitness->getFitness();
                vrep->addStatusbarMessage((char*)message2.str().c_str());

                if(generationChampionFitness < fitness->getFitness())
                {
                    generationChampionPopulation = p;
                    generationChampionFitness = fitness->getFitness();
                }
            }
            else
            {
                clog << "OVERTURNING! The simulation has stopped" << endl;
                population.organisms.at(p).fitness = FAILED_FITNESS;
            }                
        }

        simfile->addFileChampion(generationChampionFitness, g, generationChampionPopulation);
        simfile->addFileFitness(fitness->getGenerationFitness(), g);        

        //////////////////////////// SAVE CHAMPION FILES /////////////////////////////////

        stringstream generation_champion_filename;
        generation_champion_filename << "NEAT_organisms/Champion_G" << g << "P" << generationChampionPopulation << ".txt";
        population.organisms.at(generationChampionPopulation).save((char *)generation_champion_filename.str().c_str());

        stringstream cp_gen_champion_movement, cp_gen_champion_motorVelocity;

        cp_gen_champion_movement << "cp simulation_files/movement/movement_G" << g << "P" << generationChampionPopulation << ".txt ./simulation_files/movement/Champion_G" << g << "P" << generationChampionPopulation << ".txt";
        cp_gen_champion_motorVelocity << "cp simulation_files/motorVelocity/motorVelocity_G" << g << "P" << generationChampionPopulation << ".txt ./simulation_files/motorVelocity/Champion_G" << g << "P" << generationChampionPopulation << ".txt";

        if(system((char*)cp_gen_champion_movement.str().c_str()) == -1)
        {
            cerr << "TRAIN ERROR:\tFailed to copy the Champion movement File" << endl;
        }
        else
        {
            if(system("rm -f ./simulation_files/movement/movement_G*.txt") == -1)
            {
                cerr << "TRAIN ERROR:\tFailed to remove useless files" << endl;
            }
        }

        if(system((char*)cp_gen_champion_motorVelocity.str().c_str()) == -1)
        {
            cerr << "TRAIN ERROR:\tFailed to copy the Champion motor velocity File" << endl;
        }
        else
        {
            if(system("rm -f ./simulation_files/motorVelocity/motorVelocity_G*.txt") == -1)
            {
                cerr << "TRAIN ERROR:\tFailed to remove useless files" << endl;
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////

        population.epoch();        

        if(finalChampionFitness < generationChampionFitness)
        {
            finalChampionGeneration = g;
            finalChampionPopulation = generationChampionPopulation;
            finalChampionFitness = generationChampionFitness;
        }
    }

    //////////////////////////// SAVE CHAMPION FILES /////////////////////////////////

    stringstream cp_champion_organism, cp_champion_movement, cp_champion_motorVelocity;
    
    cp_champion_organism << "cp NEAT_organisms/Champion_G" << finalChampionGeneration << "P" << finalChampionPopulation << ".txt ./NEAT_organisms/Champion.txt";
    cp_champion_movement << "cp simulation_files/movement/Champion_G" << finalChampionGeneration << "P" << finalChampionPopulation << ".txt ./simulation_files/movement/Champion.txt";
    cp_champion_motorVelocity << "cp simulation_files/motorVelocity/Champion_G" << finalChampionGeneration << "P" << finalChampionPopulation << ".txt ./simulation_files/motorVelocity/Champion.txt";
        
    if(system((char*)cp_champion_organism.str().c_str()) == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to copy the Champion Organism File" << endl;
    }

    if(system((char*)cp_champion_movement.str().c_str()) == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to copy the Champion Movement File" << endl;
    }

    if(system((char*)cp_champion_motorVelocity.str().c_str()) == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to copy the Champion Motor Velocity File" << endl;
    }
    
    ///////////////////////////////////////////////////////////////////////////////////

    clog << "Fitness champion: " << finalChampionFitness << "\n\n"<< endl;

    delete(vrep);
    delete(simfile);
    delete(fitness);
    
    return(0);
}
示例#29
0
static void
init_screen(glw_ps3_t *gp)
{

  // Allocate a 1Mb buffer, alligned to a 1Mb boundary to be our shared IO memory with the RSX.
  void *host_addr = memalign(1024*1024, 1024*1024);
  assert(host_addr != NULL);

  // Initilise Reality, which sets up the command buffer and shared IO memory
  gp->gr.gr_be.be_ctx = realityInit(0x10000, 1024*1024, host_addr); 
  assert(gp->gr.gr_be.be_ctx != NULL);
  
  gcmConfiguration config;
  gcmGetConfiguration(&config);

  TRACE(TRACE_INFO, "RSX", "memory @ 0x%x size = %d\n",
	config.localAddress, config.localSize);

  hts_mutex_init(&gp->gr.gr_be.be_mempool_lock);
  gp->gr.gr_be.be_mempool = extent_create(0, config.localSize >> 4);
  gp->gr.gr_be.be_rsx_address = (void *)(uint64_t)config.localAddress;


  VideoState state;
  videoGetState(0, 0, &state);
  
  // Get the current resolution
  videoGetResolution(state.displayMode.resolution, &gp->res);
  
  int num = gp->res.width;
  int den = gp->res.height;
  
  switch(state.displayMode.aspect) {
  case VIDEO_ASPECT_4_3:
    num = 4; den = 3;
    break;
  case VIDEO_ASPECT_16_9:
    num = 16; den = 9;
    break;
  }

  gp->scale = (float)(num * gp->res.height) / (float)(den * gp->res.width);

  TRACE(TRACE_INFO, "RSX",
	"Video resolution %d x %d  aspect=%d, pixel wscale=%f",
	gp->res.width, gp->res.height, state.displayMode.aspect, gp->scale);


  gp->framebuffer_pitch = 4 * gp->res.width; // each pixel is 4 bytes
  gp->depthbuffer_pitch = 4 * gp->res.width; // And each value in the depth buffer is a 16 bit float
  
  // Configure the buffer format to xRGB
  VideoConfiguration vconfig;
  memset(&vconfig, 0, sizeof(VideoConfiguration));
  vconfig.resolution = state.displayMode.resolution;
  vconfig.format = VIDEO_BUFFER_FORMAT_XRGB;
  vconfig.pitch = gp->framebuffer_pitch;

  videoConfigure(0, &vconfig, NULL, 0);
  videoGetState(0, 0, &state);
  
  const s32 buffer_size = gp->framebuffer_pitch * gp->res.height; 
  const s32 depth_buffer_size = gp->depthbuffer_pitch * gp->res.height;
  TRACE(TRACE_INFO, "RSX", "Buffer will be %d bytes", buffer_size);
  
  gcmSetFlipMode(GCM_FLIP_VSYNC); // Wait for VSYNC to flip
  
  // Allocate two buffers for the RSX to draw to the screen (double buffering)
  gp->framebuffer[0] = rsx_alloc(&gp->gr, buffer_size, 16);
  gp->framebuffer[1] = rsx_alloc(&gp->gr, buffer_size, 16);

  TRACE(TRACE_INFO, "RSX", "Buffers at 0x%x 0x%x\n",
	gp->framebuffer[0], gp->framebuffer[1]);

  gp->depthbuffer = rsx_alloc(&gp->gr, depth_buffer_size * 4, 16);
  
  // Setup the display buffers
  gcmSetDisplayBuffer(0, gp->framebuffer[0],
		      gp->framebuffer_pitch, gp->res.width, gp->res.height);
  gcmSetDisplayBuffer(1, gp->framebuffer[1],
		      gp->framebuffer_pitch, gp->res.width, gp->res.height);

  gcmResetFlipStatus();
  flip(gp, 1);
}
示例#30
0
void rotate90(Mat& src, Mat& dst) {
    dst = src.t();
    dst = flip(dst,dst,1);
}