Ejemplo n.º 1
0
template <bool IsDrop> void MovePicker::scoreNonCapturesMinusPro() {
	for (MoveStack* curr = currMove(); curr != lastMove(); ++curr) {
		const Move move = curr->move;
		curr->score =
			history().value(IsDrop,
							colorAndPieceTypeToPiece(pos().turn(),
													 (IsDrop ? move.pieceTypeDropped() : move.pieceTypeFrom())),
							move.to());
	}
}
Ejemplo n.º 2
0
bool ChessPiece::isOpponentPieceEnPassant(const int boardPos) const
{
    Q_ASSERT(!m_parentPlayer.isNull());

    auto opponentPlayer(m_parentPlayer.toStrongRef()->opponentPlayer());
    Q_ASSERT(!opponentPlayer.isNull());

    if (opponentPlayer->lastMove())
    {
        auto oppMove = opponentPlayer->lastMove();
        if (oppMove->moveStates() & ChessTypes::MoveEnPassant &&
                oppMove->newPos().col() == ChessPos::col(boardPos))
        {
            const int boardMiddlePos = (oppMove->oldPos() + oppMove->newPos()) / 2;
            if (boardMiddlePos == boardPos &&
                    opponentPlayer->chessPieceAt(oppMove->newPos()))
                return true;
        }
    }

    return false;
}
Ejemplo n.º 3
0
void MovePicker::scoreEvasions() {
	for (MoveStack* curr = currMove(); curr != lastMove(); ++curr) {
		const Move move = curr->move;
		const Score seeScore = pos().seeSign(move);
		if (seeScore < 0) {
			curr->score = seeScore - History::MaxScore;
		}
		else if (move.isCaptureOrPromotion()) {
			curr->score = pos().capturePieceScore(pos().piece(move.to())) + History::MaxScore;
			if (move.isPromotion()) {
				const PieceType pt = pieceToPieceType(pos().piece(move.from()));
				curr->score += pos().promotePieceScore(pt);
			}
		}
		else {
			curr->score = history().value(move.isDrop(), colorAndPieceTypeToPiece(pos().turn(), move.pieceTypeFromOrDropped()), move.to());
		}
	}
}
Ejemplo n.º 4
0
int main()

{

    int i;

    DracView dv;



//NEW SET

    printf("Test for basic functions, just before Dracula's first move\n");

    PlayerMessage messages1[] = {"Hello","Rubbish","Stuff",""};

    dv = newDracView("GST.... SAO.... HZU.... MBB....", messages1);

    assert(giveMeTheRound(dv) == 0);

    assert(whereIs(dv,PLAYER_LORD_GODALMING) == STRASBOURG);

    assert(whereIs(dv,PLAYER_DR_SEWARD) == ATLANTIC_OCEAN);

    assert(whereIs(dv,PLAYER_VAN_HELSING) == ZURICH);

    assert(whereIs(dv,PLAYER_MINA_HARKER) == BAY_OF_BISCAY);

    assert(whereIs(dv,PLAYER_DRACULA) == UNKNOWN_LOCATION);

    assert(howHealthyIs(dv,PLAYER_DRACULA) == GAME_START_BLOOD_POINTS);

    printf("passed\n");

    disposeDracView(dv);



//NEW SET

    printf("Test for encountering Dracula and hunter history\n");

    PlayerMessage messages2[] = {"Hello","Rubbish","Stuff","","Mwahahah","Aha!","","",""};

    dv = newDracView("GST.... SAO.... HCD.... MAO.... DGE.... "

                     "GGED... SAO.... HCD.... MAO....", messages2);

    assert(giveMeTheRound(dv) == 1);

    assert(whereIs(dv,PLAYER_DRACULA) == GENEVA);

    assert(howHealthyIs(dv,PLAYER_LORD_GODALMING) == 5);

    assert(howHealthyIs(dv,PLAYER_DRACULA) == 30);

    assert(whereIs(dv,PLAYER_LORD_GODALMING) == GENEVA);

    LocationID history[TRAIL_SIZE];

    giveMeTheTrail(dv,PLAYER_DRACULA,history);

    assert(history[0] == GENEVA);

    assert(history[2] == UNKNOWN_LOCATION);

    giveMeTheTrail(dv,PLAYER_LORD_GODALMING,history);

    assert(history[0] == GENEVA);

    assert(history[1] == STRASBOURG);

    assert(history[2] == UNKNOWN_LOCATION);

    giveMeTheTrail(dv,PLAYER_DR_SEWARD,history);

    assert(history[0] == ATLANTIC_OCEAN);

    assert(history[1] == ATLANTIC_OCEAN);

    assert(history[2] == UNKNOWN_LOCATION);

    printf("passed\n");        

    disposeDracView(dv);



//NEW SET

    printf("Test for Dracula leaving minions\n");

    PlayerMessage messages3[] = {"Hello","Rubbish","Stuff","","Mwahahah","Aha!","","","","Drop a V","Party in Strasbourg","Party","Party","Party"};

    dv = newDracView("GGE.... SGE.... HGE.... MGE.... DED.V.. "

                     "GST.... SST.... HST.... MST.... DMNT... "

                     "GST.... SST.... HST.... MST....", messages3);

    int nT, nV;

    whatsThere(dv,EDINBURGH,&nT,&nV);

    assert(nT == 0 && nV == 1);

    whatsThere(dv,MANCHESTER,&nT,&nV);

    assert(nT == 1 && nV == 0);

    assert(whereIs(dv,PLAYER_DRACULA) == MANCHESTER);

    giveMeTheTrail(dv,PLAYER_DRACULA,history);

    assert(history[0] == MANCHESTER);

    assert(history[1] == EDINBURGH);

    assert(history[2] == UNKNOWN_LOCATION);

    giveMeTheTrail(dv,PLAYER_MINA_HARKER,history);

    assert(history[0] == STRASBOURG);

    assert(history[1] == STRASBOURG);

    assert(history[2] == GENEVA);

    assert(history[3] == UNKNOWN_LOCATION);

    printf("passed\n");

    disposeDracView(dv);



//NEW SET

    printf("Test for connections\n");

    int size, seen[NUM_MAP_LOCATIONS], *edges;



    printf("Checking Galatz road connections\n");

    PlayerMessage messages5[] = {"Gone to Galatz"};

    dv = newDracView("GGA....", messages5);

    edges = whereCanTheyGo(dv,&size,PLAYER_LORD_GODALMING,1,0,0);

    memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));

    for (i = 0; i< size ; i++) seen[edges[i]] = 1;

    assert(size == 5); assert(seen[GALATZ]); assert(seen[CONSTANTA]);

    assert(seen[BUCHAREST]); assert(seen[KLAUSENBURG]); assert(seen[CASTLE_DRACULA]);

    free(edges);

    disposeDracView(dv);



    printf("Checking Ionian Sea sea connections\n");

    PlayerMessage messages6[] = {"Sailing the Ionian"};

    dv = newDracView("GIO....", messages6);

    edges = whereCanTheyGo(dv,&size,PLAYER_LORD_GODALMING,0,0,1);

    memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));

    for (i = 0; i < size; i++) seen[edges[i]] = 1;

    assert(size == 7); assert(seen[IONIAN_SEA]); assert(seen[BLACK_SEA]);

    assert(seen[ADRIATIC_SEA]); assert(seen[TYRRHENIAN_SEA]);

    assert(seen[ATHENS]); assert(seen[VALONA]); assert(seen[SALONICA]);

    free(edges);

    disposeDracView(dv);



    printf("Checking Athens rail connections (none)\n");

    PlayerMessage messages7[] = {"Leaving Athens by train"};

    dv = newDracView("GAT....", messages7);

    edges = whereCanTheyGo(dv,&size,PLAYER_LORD_GODALMING,0,1,0);

    assert(size == 1);

    assert(edges[0] == ATHENS);

    free(edges);

    disposeDracView(dv);

    printf("passed\n");



//NEW SET

    printf("test for mature vampire (drac view)\n");

    PlayerMessage messages8[] = {"im sorry i'm lazy", "copy paste is a great thing"};

    dv= newDracView("GST.... SAO.... HCD.... MBO.... DLET... " //0

                    "GST.... SAO.... HCD.... MNA.... DPAT... " //1

                    "GST.... SAO.... HCD.... MCF.... DSTT... " //2

                    "GSTT... SAO.... HCD.... MGE.... DZUT... " //3 -2 LG

                    "GST.... SAO.... HCD.... MZUTD.. DCDT... " //4 trap at castle dracula??? -10hp drac, -6hp mina harker, +2LG, + 10hp drac

                    "GST.... SAO.... HCDTD.. MZU.... DGAT... " //5 + 3hp mina harker -6hp van helsing, -10 hp drac

                    "GST.... SAO.... HGATD.. MZU.... DCNT.M. " //6 -6hp vh (van helsing dies), -10hp drac, +3 mina marker

                    "GST.... SAO.... HSZ.... MMU.... DBS..M. " //7 -2hp dracula, helsing been in hospital

                    "GST.... SAO.... HKL.... MZA.... DCDT.M. " //8 +10hp drac

                    "GST.... SAO.... HKL.... MZA.... DCDT.M. " //9 +10hp drac

                    "GST.... SAO.... HCDTTD. MZA.... DCDT.M. " //10 -8hp vn, drac is constant

                    "GST.... SAO.... HGA.... MZA.... DKLT.M. " //11 +3hp vh

                    "GST.... SAO.... HGA.... MZA.... DBE.VM. " //12 +3hp vh

                    "GST.... SAO.... HGA.... MZA.... DSOT... " //13 +2hp vh

                    "GST.... SAO.... HCDTTT. MZA.... DSJT.M. " //14 -6hp vh

                    "GST.... SAO.... HCD.... MZA.... DVET.M. " //15 +3hp vh

                    "GST.... SAO.... HCD.... MZA.... DZAT.M. " //16 +3hp vh

                    "GMU.... SAO.... HCD.... MZA.... DVIT.M. " //17 

                    "GVITD.. SAO.... HCD.... MZA.... DPRT... " //18 -6LG, -10 drac

                    "GVI.... SAO.... HCD.... MZA.... DCDT.V.", messages8); //19 +3 LG

    //basically copied from testGameView...

    //making sure the basics of drac view works

    assert(giveMeTheRound(dv)==20);

    assert(giveMeTheScore(dv)==GAME_START_SCORE -20 -6 -13);

    assert(howHealthyIs(dv, PLAYER_LORD_GODALMING)==GAME_START_HUNTER_LIFE_POINTS-3);

    assert(howHealthyIs(dv, PLAYER_DR_SEWARD)==GAME_START_HUNTER_LIFE_POINTS);

    assert(howHealthyIs(dv, PLAYER_VAN_HELSING)==GAME_START_HUNTER_LIFE_POINTS);

    assert(howHealthyIs(dv, PLAYER_MINA_HARKER)==GAME_START_HUNTER_LIFE_POINTS);

    assert(whereIs(dv, PLAYER_LORD_GODALMING)==VIENNA);

    assert(whereIs(dv, PLAYER_DR_SEWARD)==ATLANTIC_OCEAN);

    assert(whereIs(dv, PLAYER_VAN_HELSING)==CASTLE_DRACULA);

    assert(whereIs(dv, PLAYER_MINA_HARKER)==ZAGREB);

    

    giveMeTheTrail(dv,PLAYER_DRACULA,history);

    assert(history[0] == CASTLE_DRACULA);

    assert(history[1] == PRAGUE); 

    assert(history[2] == VIENNA);  

    assert(history[3] == ZAGREB);   

    assert(history[4] == VENICE);  

    assert(history[5] == SARAJEVO); 

    giveMeTheTrail(dv,PLAYER_LORD_GODALMING,history);

    assert(history[0] == VIENNA);

    assert(history[1] == VIENNA); 

    assert(history[2] == MUNICH);  

    assert(history[3] == STRASBOURG);

    giveMeTheTrail(dv,PLAYER_DR_SEWARD,history);

    assert(history[0] == ATLANTIC_OCEAN);

    assert(history[1] == ATLANTIC_OCEAN);

    assert(history[2] == ATLANTIC_OCEAN);

    assert(history[3] == ATLANTIC_OCEAN);

    assert(history[4] == ATLANTIC_OCEAN);

    assert(history[5] == ATLANTIC_OCEAN);



    //start and end are the same for all

    int start, end;

    lastMove(dv, PLAYER_LORD_GODALMING, &start, &end);

    assert(start==VIENNA && end==VIENNA); 

    lastMove(dv, PLAYER_DR_SEWARD, &start, &end);

    assert(start==ATLANTIC_OCEAN && end==ATLANTIC_OCEAN); 

    lastMove(dv, PLAYER_VAN_HELSING, &start, &end);

    assert(start==CASTLE_DRACULA && end==CASTLE_DRACULA); 

    lastMove(dv, PLAYER_MINA_HARKER, &start, &end);

    assert(start==ZAGREB && end==ZAGREB); 

    disposeDracView(dv);

    printf("passed\n");



//NEW SET

    printf("test more many traps\n"); 

    PlayerMessage messages9[] = {"hey look!, something new..."};

    dv= newDracView("GST.... SAO.... HCD.... MBO.... DLET... "

                    "GCO.... SIR.... HGA.... MNA.... DD1T...",messages9 );

    int nnT, nnV;

    whatsThere(dv,LE_HAVRE,&nnT,&nnV);

    assert(nnT == 2 && nnV == 0);

    assert(giveMeTheRound(dv)==2);

    assert(giveMeTheScore(dv)==GAME_START_SCORE -2);

    

    lastMove(dv, PLAYER_LORD_GODALMING, &start, &end);

    assert(start==STRASBOURG && end==COLOGNE); 

    lastMove(dv, PLAYER_DR_SEWARD, &start, &end);

    assert(start==ATLANTIC_OCEAN && end==IRISH_SEA); 

    lastMove(dv, PLAYER_VAN_HELSING, &start, &end);

    assert(start==CASTLE_DRACULA && end==GALATZ); 

    lastMove(dv, PLAYER_MINA_HARKER, &start, &end);

    assert(start==BORDEAUX && end==NANTES);



    //more basics

    giveMeTheTrail(dv,PLAYER_LORD_GODALMING,history);

    assert(history[0] == COLOGNE);

    assert(history[1] == STRASBOURG); 

    assert(history[2] == UNKNOWN_LOCATION); 

    giveMeTheTrail(dv,PLAYER_DR_SEWARD,history);

    assert(history[0] == IRISH_SEA);

    assert(history[1] == ATLANTIC_OCEAN); 

    assert(history[2] == UNKNOWN_LOCATION); 

    giveMeTheTrail(dv,PLAYER_VAN_HELSING,history);

    assert(history[0] == GALATZ);

    assert(history[1] == CASTLE_DRACULA); 

    assert(history[2] == UNKNOWN_LOCATION); 

    giveMeTheTrail(dv,PLAYER_MINA_HARKER,history);

    assert(history[0] == NANTES);

    assert(history[1] == BORDEAUX); 

    assert(history[2] == UNKNOWN_LOCATION);    

    assert(history[3] == UNKNOWN_LOCATION);

    assert(history[4] == UNKNOWN_LOCATION);

    assert(history[5] == UNKNOWN_LOCATION);             

    disposeDracView(dv);

    printf("passed\n"); 



//NEW SET

    printf("test for dracula paths (where can i go)\n");

    //int size, seen[NUM_MAP_LOCATIONS], *edges; -->declared at top    

    PlayerMessage messages10[] = {"going from le havre"};

    dv= newDracView("GST.... SAO.... HCD.... MBO.... DLET...", messages10);

    printf("Checking Le Havre Road connections\n");

    edges = whereCanIgo(dv, &size, 1,0);

    memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));

    for (i = 0; i< size ; i++) seen[edges[i]] = 1;

    assert(size==4);

    assert(seen[LE_HAVRE]); assert(seen[NANTES]); assert(seen[PARIS]); 

    assert(seen[BRUSSELS]);

    free(edges);

    printf("Checking Le Havre boat connections\n");

    edges = whereCanIgo(dv, &size, 0,1);

    memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));

    for (i = 0; i< size ; i++) seen[edges[i]] = 1;    

    assert(size==2); //only one boat

    assert(seen[LE_HAVRE]); assert(seen[ENGLISH_CHANNEL]);

    free(edges);

    disposeDracView(dv);



    PlayerMessage messages11[] = {"going from bucharest"};

    dv= newDracView("GST.... SAO.... HCD.... MBO.... DBCT...", messages11);

    printf("Checking bucharest road connections\n");

    edges = whereCanIgo(dv, &size, 1,0);

    memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));

    for (i = 0; i< size ; i++) seen[edges[i]] = 1;

    assert(size==6); 

    assert(seen[BUCHAREST]); assert(seen[BELGRADE]); assert(seen[CONSTANTA]); 

    assert(seen[GALATZ]); assert(seen[KLAUSENBURG]); assert(seen[SOFIA]);

    free(edges);

    disposeDracView(dv);



    PlayerMessage messages12[] = {"going from galway"};

    dv= newDracView("GST.... SAO.... HCD.... MBO.... DGWT...", messages12);

    printf("Checking galway road AND boat connections\n");

    edges = whereCanIgo(dv, &size, 1,1);

    memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));

    for (i = 0; i< size ; i++) seen[edges[i]] = 1;

    assert(size==3); 

    assert(seen[GALWAY]); assert(seen[DUBLIN]); assert(seen[ATLANTIC_OCEAN]);

    free(edges);

    disposeDracView(dv);

    

    PlayerMessage messages13[] = {"going from cologne"};

    dv= newDracView("GST.... SAO.... HCD.... MBO.... DCOT...", messages13);

    printf("Checking cologne boat connections (none)\n");

    edges = whereCanIgo(dv, &size, 0,1);

    memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));

    for (i = 0; i< size ; i++) seen[edges[i]] = 1;

    assert(size==1); assert(seen[COLOGNE]);

    free(edges);

    disposeDracView(dv);

    printf("passed\n");



//NEW SET

    printf("test for double back in train when seeing where dracula goes \n");

    PlayerMessage messages14[] = {"going from cologne","to cologne lol"};

    dv= newDracView("GST.... SAO.... HCD.... MBO.... DCOT... " 

                    "GST.... SAO.... HCD.... MBO.... DD1T...", messages14);

    edges = whereCanIgo(dv, &size, 0,1);

    //cannot have another double back so cannot stay in cologne via boat       

    assert(size==1); //cant hide at sea

    free(edges);

      

    edges = whereCanIgo(dv, &size, 1,0);

    memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));

    for (i = 0; i< size ; i++) seen[edges[i]] = 1;

    assert(size==7);

    assert(seen[COLOGNE]); //can hide in city again

    assert(seen[AMSTERDAM]); assert(seen[BRUSSELS]); assert(seen[FRANKFURT]);

    assert(seen[HAMBURG]); assert(seen[LEIPZIG]); assert(seen[STRASBOURG]);

    free(edges);

    disposeDracView(dv);    

    printf("passed\n");



//NEW SET

    printf("check for hide AND double back\n");

    dv= newDracView("GST.... SAO.... HCD.... MBO.... DCOT... " 

                    "GST.... SAO.... HCD.... MBO.... DD1T... "

                    "GST.... SAO.... HCD.... MBO.... DHI....", messages14);

    edges = whereCanIgo(dv, &size, 0,1);

    //cannot have another double back so cannot stay in cologne via boat       

    assert(size==0); //cant hide at sea

    free(edges);

      

    edges = whereCanIgo(dv, &size, 1,0);

    memset(seen, 0, NUM_MAP_LOCATIONS*sizeof(int));

    for (i = 0; i< size ; i++) seen[edges[i]] = 1;

    assert(size==6);

    assert(seen[AMSTERDAM]); assert(seen[BRUSSELS]); assert(seen[FRANKFURT]);

    assert(seen[HAMBURG]); assert(seen[LEIPZIG]); assert(seen[STRASBOURG]);

    free(edges);

    disposeDracView(dv);    

    printf("passed\n");

    

    return 0;

}
Ejemplo n.º 5
0
int main(int argc, char **argv)
{
  int res;

  try {
    socket.bind ("tcp://*:14444");
    s_sendmore (socket, "event");
        s_send (socket, "{type:\"up\"}");
  }
  catch (zmq::error_t e) {
    cerr << "Cannot bind to socket: " <<e.what() << endl;
    return -1;
  }

  //  printf("Kinect camera test\n");
  //
  //  int i;
  //  for (i=0; i<2048; i++) {
  //    float v = i/2048.0;
  //    v = powf(v, 3)* 6;
  //    t_gamma[i] = v*6*256;
  //  }
  //
  //  g_argc = argc;
  //  g_argv = argv;
  //
  //  //setup Freenect...
  //  if (freenect_init(&f_ctx, NULL) < 0) {
  //    printf("freenect_init() failed\n");
  //    return 1;
  //  }
  //
  //  freenect_set_log_level(f_ctx, FREENECT_LOG_ERROR);
  //
  //  int nr_devices = freenect_num_devices (f_ctx);
  //  printf ("Number of devices found: %d\n", nr_devices);
  //
  //  int user_device_number = 0;
  //  if (argc > 1)
  //    user_device_number = atoi(argv[1]);
  //
  //  if (nr_devices < 1)
  //    return 1;
  //
  //  if (freenect_open_device(f_ctx, &f_dev, user_device_number) < 0) {
  //    printf("Could not open device\n");
  //    return 1;
  //  }
  //
  //  freenect_set_tilt_degs(f_dev,freenect_angle);
  //  freenect_set_led(f_dev,LED_RED);
  //  freenect_set_depth_callback(f_dev, depth_cb);
  //  freenect_set_video_callback(f_dev, rgb_cb);
  //  freenect_set_video_format(f_dev, FREENECT_VIDEO_RGB);
  //  freenect_set_depth_format(f_dev, FREENECT_DEPTH_11BIT);
  //
  //  freenect_start_depth(f_dev);
  //  freenect_start_video(f_dev);

  initFreenect();

  //start the freenect thread to poll for events
  res = pthread_create(&ocv_thread, NULL, freenect_threadfunc, NULL);
  if (res) {
    printf("pthread_create failed\n");
    return 1;
  }

  Mat depthf;

  Mat frameMat(rgbMat);
  Mat blobMaskOutput(frameMat.size(),CV_8UC1),
  outC(frameMat.size(),CV_8UC3);
  Mat prevImg(frameMat.size(),CV_8UC1),
  nextImg(frameMat.size(),CV_8UC1),
  prevDepth(depthMat.size(),CV_8UC1);
  vector<Point2f> prevPts,nextPts;
  vector<uchar> statusv;
  vector<float> errv;
  Rect cursor(frameMat.cols/2,frameMat.rows/2,10,10);
  bool update_bg_model = true;
  int fr = 1;
  int register_ctr = 0,register_secondbloc_ctr = 0;
  bool registered = false;

  Point2i appear(-1,-1); double appearTS = -1;

  Point2i midBlob(-1,-1);
  Point2i lastMove(-1,-1);

  int hcr_ctr = -1;
  vector<int> hc_stack(20); int hc_stack_ptr = 0;

  while (!die) {
    fr++;

    //    imshow("rgb", rgbMat);
    pthread_mutex_lock(&buf_mutex);

    //Linear interpolation
    {
      Mat _tmp = (depthMat - 400.0);          //minimum observed value is ~440. so shift a bit
      _tmp.setTo(Scalar(2048), depthMat > ((!registered) ? 700.0 : 750.0));   //cut off at 600 to create a "box" where the user interacts
      _tmp.convertTo(depthf, CV_8UC1, 255.0/1648.0);  //values are 0-2048 (11bit), account for -400 = 1648
    }

    {
      Mat _tmp;
      depthMat.convertTo(_tmp, CV_8UC1, 255.0/2048.0);
      cvtColor(_tmp, outC, CV_GRAY2BGR);
    }

    pthread_mutex_unlock(&buf_mutex);

    //    { //saving the frames to files for debug
    //      stringstream ss; ss << "depth_"<<fr<<".png";
    //      imwrite(ss.str(), depthf);
    //    }

    //Logarithm interpolation - try it!, It should be more "sensitive" for closer depths
    //    {
    //      Mat tmp,tmp1;
    //      depthMat.convertTo(tmp, CV_32FC1);
    //      log(tmp,tmp1);
    //      tmp1.convertTo(depthf, CV_8UC1, 255.0/7.6246189861593985);
    //    }
    //    imshow("depth",depthf);


    Mat blobMaskInput = depthf < 255; //anything not white is "real" depth
    vector<Point> ctr,ctr2;


    Scalar blb = refineSegments(Mat(),blobMaskInput,blobMaskOutput,ctr,ctr2,midBlob); //find contours in the foreground, choose biggest
    imshow("first", blobMaskOutput);
    /////// blb :
    //blb[0] = x, blb[1] = y, blb[2] = 1st blob size, blb[3] = 2nd blob size.

    //    uint mode_counters[3] = {0};

    if(blb[0]>=0 && blb[2] > 500) { //1st blob detected, and is big enough
      //cvtColor(depthf, outC, CV_GRAY2BGR);

      //closest point to the camera
      Point minLoc; double minval,maxval;
      minMaxLoc(depthf, &minval, &maxval, &minLoc, NULL, blobMaskInput);
      circle(outC, minLoc, 5, Scalar(0,255,0), 3);

      Scalar mn,stdv;
      meanStdDev(depthf,mn,stdv,blobMaskInput);

      //cout << "min: " << minval << ", max: " << maxval << ", mean: " << mn[0] << endl;

      blobMaskInput = depthf < (mn[0] + stdv[0]*.5);

      blb = refineSegments(Mat(),blobMaskInput,blobMaskOutput,ctr,ctr2,midBlob);

      imshow("second", blobMaskOutput);

      if(blb[0] >= 0 && blb[2] > 300) {
        //draw contour
        Scalar color(0,0,255);
        for (int idx=0; idx<ctr.size()-1; idx++)
          line(outC, ctr[idx], ctr[idx+1], color, 1);
        line(outC, ctr[ctr.size()-1], ctr[0], color, 1);

        if(ctr2.size() > 0) {
          Scalar color2(255,0,255);
          for (int idx=0; idx<ctr2.size()-1; idx++)
            line(outC, ctr2[idx], ctr2[idx+1], color2, 2);
          line(outC, ctr2[ctr2.size()-1], ctr2[0], color2, 2);
        }

        //draw "major axis"
        //      Vec4f _line;
        Mat curve(ctr);
        //      fitLine(curve, _line, CV_DIST_L2, 0, 0.01, 0.01);
        //      line(outC, Point(blb[0]-_line[0]*70,blb[1]-_line[1]*70),
        //            Point(blb[0]+_line[0]*70,blb[1]+_line[1]*70),
        //            Scalar(255,255,0), 1);

        //blob center
        circle(outC, Point(blb[0],blb[1]), 50, Scalar(255,0,0), 3);


        //      cout << "min depth " << minval << endl;

        register_ctr = MIN((register_ctr + 1),60);

        if(blb[3] > 5000)
          register_secondbloc_ctr = MIN((register_secondbloc_ctr + 1),60);

        if (register_ctr > 30 && !registered) {
          registered = true;
          appear.x = -1;
          update_bg_model = false;
          lastMove.x = blb[0]; lastMove.y = blb[1];

          cout << "blob size " << blb[2] << endl;

          if(register_secondbloc_ctr < 30) {
            if(blb[2] > 10000) {
              cout << "register panner" << endl;
              send_event("Register", "\"mode\":\"openhand\"");
            } else {
              cout << "register pointer" << endl;
              send_event("Register", "\"mode\":\"theforce\"");
            }
          } else {
            cout << "register tab swithcer" << endl;
            send_event("Register", "\"mode\":\"twohands\"");
          }
        }

        if(registered) {
          stringstream ss;
          ss  << "\"x\":"  << (int)floor(blb[0]*100.0/640.0)
            << ",\"y\":" << (int)floor(blb[1]*100.0/480.0)
            << ",\"z\":" << (int)(mn[0] * 2.0);
          //cout << "move: " << ss.str() << endl;
          send_event("Move", ss.str());

          //---------------------- fist detection ---------------------
          //calc laplacian of curve
          vector<Point> approxCurve;  //approximate curve
          approxPolyDP(curve, approxCurve, 10.0, true);
          Mat approxCurveM(approxCurve);

          Mat curve_lap;
          calc_laplacian(approxCurveM, curve_lap);  //calc laplacian

          hcr_ctr = 0;
          for (int i=0; i<approxCurve.size(); i++) {
            double n = norm(((Point2d*)(curve_lap.data))[i]);
            if (n > 10.0) {
              //high curvature point
              circle(outC, approxCurve[i], 3, Scalar(50,155,255), 2);
              hcr_ctr++;
            }
          }

          hc_stack.at(hc_stack_ptr) = hcr_ctr;
          hc_stack_ptr = (hc_stack_ptr + 1) % hc_stack.size();

          Scalar _avg = mean(Mat(hc_stack));
          if (abs(_avg[0] - (double)hcr_ctr) > 5.0) { //a big change in curvature = hand fisted/opened?
            cout << "Hand click!" << endl;
            send_event("HandClick", "");
          }

          if (mode_state == MODE_NONE) {

          }

          //        imshow("out",out);
          //doHist(depthf,out);

          { //some debug on screen..
            stringstream ss; ss << "high curve pts " << hcr_ctr << ", avg " << _avg[0];
            putText(outC, ss.str(), Point(50,50), CV_FONT_HERSHEY_PLAIN, 2.0,Scalar(0,0,255), 2);
          }
        } else {
          //not registered, look for gestures
          if(appear.x<0) {
            //first appearence of blob
            appear = midBlob;
            //          update_bg_model = false;
            appearTS = getTickCount();
            cout << "appear ("<<appearTS<<") " << appear.x << "," << appear.y << endl;
          } else {
            //blob was seen before, how much time passed
            double timediff = ((double)getTickCount()-appearTS)/getTickFrequency();
            if (timediff > .2 && timediff < 1.0) {
              //enough time passed from appearence
              line(outC, appear, Point(blb[0],blb[1]), Scalar(0,0,255), 3);
              if (appear.x - blb[0] > 100) {
                cout << "right"<<endl; appear.x = -1;
                send_event("SwipeRight", "");
                update_bg_model = true;
                register_ctr = 0;
              } else if (appear.x - blb[0] < -100) {
                cout << "left" <<endl; appear.x = -1;
                send_event("SwipeLeft", "");
                update_bg_model = true;
                register_ctr = 0;
              } else if (appear.y - blb[1] > 100) {
                cout << "up" << endl; appear.x = -1;
                send_event("SwipeUp", "");
                update_bg_model = true;
                register_ctr = 0;
              } else if (appear.y - blb[1] < -100) {
                cout << "down" << endl; appear.x = -1;
                send_event("SwipeDown", "");
                update_bg_model = true;
                register_ctr = 0;
              }
            }
            if(timediff >= 1.0) {
              cout << "a ghost..."<<endl;
              update_bg_model = true;
              //a second passed from appearence - reset 1st appear
              appear.x = -1;
              appearTS = -1;
              midBlob.x = midBlob.y = -1;
            }
          }
        }
        send_image(outC);
      }
    } else {
      send_image(depthf);
      register_ctr = MAX((register_ctr - 1),0);
      register_secondbloc_ctr = MAX((register_secondbloc_ctr - 1),0);
    }
    imshow("blob",outC);

    if (register_ctr <= 15 && registered) {
      midBlob.x = midBlob.y = -1;
      registered = false;
      mode_state = MODE_NONE;
      update_bg_model = true;
      cout << "unregister" << endl;
      send_event("Unregister", "");
    }

        char k = cvWaitKey(5);
        if( k == 27 ) break;
        if( k == ' ' )
            update_bg_model = !update_bg_model;
    if (k=='s') {
      cout << "send test event" << endl;
      send_event("TestEvent", "");
    }
  }

  printf("-- done!\n");

  pthread_join(ocv_thread, NULL);
  pthread_exit(NULL);
  return 0;
}
Ejemplo n.º 6
0
template <> Move MovePicker::nextMove<false>() {
	MoveStack* ms;
	Move move;
	do {
		// lastMove() に達したら次の phase に移る。
		while (currMove() == lastMove()) {
			goNextPhase();
		}

		switch (phase()) {

		case MainSearch: case EvasionSearch: case QSearch: case QEvasionSearch: case ProbCut:
			++currMove_;
			return ttMove_;

		case PH_TacticalMoves0:
			ms = pickBest(currMove_++, lastMove());
			if (ms->move != ttMove_) {
				assert(captureThreshold_ <= 0);

				if (captureThreshold_ <= pos().see(ms->move)) {
					return ms->move;
				}

				// 後ろから SEE の点数が高い順に並ぶようにする。
				(endBadCaptures_--)->move = ms->move;
			}
			break;

		case PH_Killers:
			move = (currMove_++)->move;
			if (!move.isNone()
				&& move != ttMove_
				&& pos().moveIsPseudoLegal(move, true)
				&& pos().piece(move.to()) == Empty)
			{
				return move;
			}
			break;

		case PH_NonTacticalMoves0:
		case PH_NonTacticalMoves1:
			move = (currMove_++)->move;
			if (move != ttMove_
				&& move != killerMoves_[0].move
				&& move != killerMoves_[1].move
				)
			{
				return move;
			}
			break;

		case PH_BadCaptures:
			return (currMove_--)->move;

		case PH_Evasions: case PH_QEvasions: case PH_QCaptures0:
			move = pickBest(currMove_++, lastMove())->move;
			if (move != ttMove_) {
				return move;
			}
			break;

		case PH_TacticalMoves1:
			ms = pickBest(currMove_++, lastMove());
			// todo: see が確実に駒打ちじゃないから、内部で駒打ちか判定してるのは少し無駄。
			if (ms->move != ttMove_ && captureThreshold_ < pos().see(ms->move)) {
				return ms->move;
			}
			break;

		case PH_QCaptures1:
			move = pickBest(currMove_++, lastMove())->move;
			assert(move.to() == recaptureSquare_);
			return move;

		case PH_Stop:
			return Move::moveNone();
		default:
			UNREACHABLE;
		}
	} while (true);
}
Ejemplo n.º 7
0
void MovePicker::goNextPhase() {
	currMove_ = firstMove(); // legalMoves_[0] は番兵
	++phase_;

	switch (phase()) {
	case PH_TacticalMoves0: case PH_TacticalMoves1:
		lastMove_ = generateMoves<CapturePlusPro>(currMove(), pos());
		scoreCaptures();
		return;

	case PH_Killers:
		currMove_ = killerMoves_;
		lastMove_ = currMove() + 2;
		return;

	case PH_NonTacticalMoves0:
		lastMove_ = generateMoves<NonCaptureMinusPro>(currMove(), pos());
		scoreNonCapturesMinusPro<false>();
		currMove_ = lastMove();
		lastNonCapture_ = lastMove_ = generateMoves<Drop>(currMove(), pos());
		scoreNonCapturesMinusPro<true>();
		currMove_ = firstMove();
		lastMove_ = std::partition(currMove(), lastNonCapture(), HasPositiveScore());
		// 要素数は10個くらいまでであることが多い。要素数が少ないので、insertionSort() を使用する。
		insertionSort<MoveStack*, true>(currMove(), lastMove());
		return;

	case PH_NonTacticalMoves1:
		currMove_ = lastMove();
		lastMove_ = lastNonCapture();
		if (static_cast<Depth>(3 * OnePly) <= depth_) {
			std::sort(currMove(), lastMove(), std::greater<MoveStack>());
		}
		return;

	case PH_BadCaptures:
		currMove_ = legalMoves_ + MaxLegalMoves - 1;
		lastMove_ = endBadCaptures_;
		return;

	case PH_Evasions:
	case PH_QEvasions:
		lastMove_ = generateMoves<Evasion>(currMove(), pos());
		if (currMove() + 1 < lastMove()) {
			scoreEvasions();
		}
		return;

	case PH_QCaptures0:
		lastMove_ = generateMoves<CapturePlusPro>(firstMove(), pos());
		scoreCaptures();
		return;

	case PH_QCaptures1:
		lastMove_ = generateMoves<Recapture>(firstMove(), pos(), recaptureSquare_);
		scoreCaptures();
		return;

	case EvasionSearch: case QSearch: case QEvasionSearch: case QRecapture: case ProbCut:
		// これが無いと、MainSearch の後に EvasionSearch が始まったりしてしまう。
		phase_ = PH_Stop;

	case PH_Stop:
		lastMove_ = currMove() + 1;
		return;

	default: UNREACHABLE;
	}
}
Ejemplo n.º 8
0
void MovePicker::scoreCaptures() {
	for (MoveStack* curr = currMove(); curr != lastMove(); ++curr) {
		const Move move = curr->move;
		curr->score = Position::pieceScore(pos().piece(move.to())) - LVA(move.pieceTypeFrom());
	}
}