Ejemplo n.º 1
0
JobBurner::JobBurner( const JobAssignment & jobAssignment, Slave * slave, int options )
: QObject( slave )
, mSlave( slave )
, mCmd( 0 )
, mJobAssignment( jobAssignment )
, mJob( jobAssignment.job() )
, mLoaded( false )
, mOutputTimer( 0 )
, mMemTimer( 0 )
, mLogFlushTimer( 0 )
, mCheckupTimer( 0 )
, mState( StateNew )
, mOptions( Options(options) )
, mCurrentCopy( 0 )
, mLogFilesReady( false )
, mLogFile( 0 )
, mLogStream( 0 )
, mCmdPid( 0 )
{
	mOutputTimer = new QTimer( this );
	connect( mOutputTimer, SIGNAL( timeout() ), SLOT( updateOutput() ) );

	mMemTimer = new QTimer( this );
	connect( mMemTimer, SIGNAL( timeout() ), SLOT( checkMemory() ) );

	mCheckupTimer = new QTimer( this );
	connect( mCheckupTimer, SIGNAL( timeout() ), SLOT( checkup() ) );
    mCheckupTimer->start(30000);
	
	/* Ensure we are actually assigned some tasks to work on */
	mTaskAssignments = mJobAssignment.jobTaskAssignments();
	if( mTaskAssignments.isEmpty() ) {
		jobErrored( QString("JobAssignment has no assigned tasks, Job Assignment key: %1").arg(mJobAssignment.key()) );
		return;
	}

	// Double check that we are still assigned
	mJobAssignment.reload();
	if( mJobAssignment.jobAssignmentStatus().status() != "ready" ) {
		LOG_1( "JobAssignment no longer ready, cancelling the burn" );
		cancel();
		return;
	}

	/* Make sure each of the tasks are still valid, some could have already been unassigned or cancelled */
	/* Also verify that the jobtask record matches the assignment */
	mTasks = JobTask::table()->records( mTaskAssignments.keys( JobTaskAssignment::schema()->field("fkeyjobtask")->pos() ), /*select=*/true, /*useCache=*/false );
	foreach( JobTaskAssignment jta, mTaskAssignments ) {
		JobTask task = jta.jobTask();
		if( jta.jobAssignmentStatus().status() != "ready" || task.status() != "assigned" || task.host() != Host::currentHost() ) {
			LOG_1( QString("JobTask no longer assigned, discarding. keyJobTask: %1  keyJobTaskAssignment: %2  jobtask status: %3 jobtaskassignment status: %4")
				.arg(task.key()).arg(jta.key()).arg(task.status()).arg(jta.jobAssignmentStatus().status()) );
			mTaskAssignments -= jta;
			mTasks -= task;
		}
	}
Ejemplo n.º 2
0
/**
 * Moves the craft to its destination.
 */
void Craft::think()
{
	move();
	if (reachedDestination() && _dest == (Target*)_base)
	{
		setInterceptionOrder(0);
		checkup();
		setDestination(0);
		setSpeed(0);
		_lowFuel = false;
	}
}
Ejemplo n.º 3
0
int quiesce(int alpha,int beta)
{
    int i, j, x;

    ++nodes;

    /* do some housekeeping every 1024 nodes */
    if ((nodes & 1023) == 0)
        checkup();

    pv_length[ply] = ply;

    /* are we too deep? */
    if (ply >= MAX_PLY - 1)
        return eval();
    if (hply >= HIST_STACK - 1)
        return eval();

    /* check with the evaluation function */
    x = eval();
    if (x >= beta)
        return beta;
    if (x > alpha)
        alpha = x;

    gen_caps();
    if (follow_pv)  /* are we following the PV? */
        sort_pv();

    /* loop through the moves */
    for (i = first_move[ply]; i < first_move[ply + 1]; ++i) {
        sort(i);
        if (!makemove(gen_dat[i].m.b))
            continue;
        x = -quiesce(-beta, -alpha);
        takeback();
        if (x > alpha) {
            if (x >= beta)
                return beta;
            alpha = x;

            /* update the PV */
            pv[ply][ply] = gen_dat[i].m;
            for (j = ply + 1; j < pv_length[ply + 1]; ++j)
                pv[ply][j] = pv[ply + 1][j];
            pv_length[ply] = pv_length[ply + 1];
        }
    }
    return alpha;
}
Ejemplo n.º 4
0
Human Human::LoadHuman()
{
	int i;

	cout<<"\n\n\4 Name - ";
	Enter(Name);
	cout<<"\n\n\4 Second name - ";
	Enter(Sname);
	cout<<"\n\n\4 Choose gender: 1) - Male,\n                 2) - Female.\n\n\n\4 Choice - ";
	i=checkup(2);
	if(i==1)
		Gender.setString("Male");

	else Gender.setString("Female");

	return *this;
}
Ejemplo n.º 5
0
/**
 * Moves the craft to its destination.
 */
void Craft::think()
{
	if (_takeoff == 0)
	{
		move();
	}
	else
	{
		_takeoff--;
	}
	if (reachedDestination() && _dest == (Target*)_base)
	{
		setInterceptionOrder(0);
		checkup();
		setDestination(0);
		setSpeed(0);
		_lowFuel = false;
		_mission = false;
		_takeoff = 0;
	}
}
Ejemplo n.º 6
0
dr_main()
{
	register int n;
	register struct ship *sp;
	int nat[NNATION];
	int value = 0;

	(void) signal(SIGINT, SIG_IGN);
	(void) signal(SIGQUIT, SIG_IGN);
	(void) signal(SIGTSTP, SIG_IGN);
	if (issetuid)
		(void) setuid(geteuid());
	if (game < 0 || game >= NSCENE) {
		fprintf(stderr, "DRIVER: Bad game number %d\n", game);
		exit(1);
	}
	cc = &scene[game];
	ls = SHIP(cc->vessels);
	if (sync_open() < 0) {
		perror("driver: syncfile");
		exit(1);
	}
	for (n = 0; n < NNATION; n++)
		nat[n] = 0;
	foreachship(sp) {
		if (sp->file == NULL &&
		    (sp->file = (struct File *)calloc(1, sizeof (struct File))) == NULL) {
			(void) fprintf(stderr, "DRIVER: Out of memory.\n");
			exit(1);
		}
		sp->file->index = sp - SHIP(0);
		sp->file->loadL = L_ROUND;
		sp->file->loadR = L_ROUND;
		sp->file->readyR = R_LOADED|R_INITIAL;
		sp->file->readyL = R_LOADED|R_INITIAL;
		sp->file->stern = nat[sp->nationality]++;
		sp->file->dir = sp->shipdir;
		sp->file->row = sp->shiprow;
		sp->file->col = sp->shipcol;
	}
	windspeed = cc->windspeed;
	winddir = cc->winddir;
	people = 0;
	for (;;) {
		sleep(7);
		if (Sync() < 0) {
			value = 1;
			break;
		}
		if (next() < 0)
			break;
		unfoul();
		checkup();
		prizecheck();
		moveall();
		thinkofgrapples();
		boardcomp();
		compcombat();
		resolve();
		reload();
		checksails();
		if (Sync() < 0) {
			value = 1;
			break;
		}
	}
	sync_close(1);
	return value;
}
Ejemplo n.º 7
0
int search(int alpha, int beta, int depth)
{
    int i, j, x;
    BOOL c, f;

    /* we're as deep as we want to be; call quiesce() to get
       a reasonable score and return it. */
    if (!depth)
        return quiesce(alpha,beta);
    ++nodes;

    /* do some housekeeping every 1024 nodes */
    if ((nodes & 1023) == 0)
        checkup();

    pv_length[ply] = ply;

    /* if this isn't the root of the search tree (where we have
       to pick a move and can't simply return 0) then check to
       see if the position is a repeat. if so, we can assume that
       this line is a draw and return 0. */
    if (ply && reps())
        return 0;

    /* are we too deep? */
    if (ply >= MAX_PLY - 1)
        return eval();
    if (hply >= HIST_STACK - 1)
        return eval();

    /* are we in check? if so, we want to search deeper */
    c = in_check(side);
    if (c)
        ++depth;
    gen();
    if (follow_pv)  /* are we following the PV? */
        sort_pv();
    f = FALSE;

    /* loop through the moves */
    for (i = first_move[ply]; i < first_move[ply + 1]; ++i) {
        sort(i);
        if (!makemove(gen_dat[i].m.b))
            continue;
        f = TRUE;
        x = -search(-beta, -alpha, depth - 1);
        takeback();
        if (x > alpha) {

            /* this move caused a cutoff, so increase the history
               value so it gets ordered high next time we can
               search it */
            history[(int)gen_dat[i].m.b.from][(int)gen_dat[i].m.b.to] += depth;
            if (x >= beta)
                return beta;
            alpha = x;

            /* update the PV */
            pv[ply][ply] = gen_dat[i].m;
            for (j = ply + 1; j < pv_length[ply + 1]; ++j)
                pv[ply][j] = pv[ply + 1][j];
            pv_length[ply] = pv_length[ply + 1];
        }
    }

    /* no legal moves? then we're in checkmate or stalemate */
    if (!f) {
        if (c)
            return -10000 + ply;
        else
            return 0;
    }

    /* fifty move draw rule */
    if (fifty >= 100)
        return 0;
    return alpha;
}
Ejemplo n.º 8
0
int Engine::QuiescenceSearch(int alpha,int beta)
{
	//quisctime.Start();

	if (isDraw()) return 0;

	nodes++;
	if(nodes%CheckupNodeCount == 0)
	{
		checkup();
		//nodes = 0;
	}
	/*if(pos.getGameStatus()!=STATUS_NOTOVER)
	{
		int val = LeafEval(alpha,beta);
		if(val >= beta)
			return beta;
		else if(val < alpha)
			return alpha;
		return val;
	}*/
	int stand_pat = 0;
	//ProbeStruct probe = Table.Probe(pos.TTKey, -1, alpha, beta);
	//if (probe.found && probe.entry->bound == TT_EXACT)
	//{
	//	return probe.score;
	//	stand_pat = probe.score; //use TT probe as leafeval
	//}
	//else
	//{
		stand_pat = LeafEval<false>();
	//} 
	if(stand_pat >= beta) //standpat
	{
		return stand_pat;
	}
	if(stand_pat <= alpha-PieceMaterial[PIECE_QUEEN]) //big delta pruning
	{
		return stand_pat;
	}
	if(alpha < stand_pat)
	{
		alpha = stand_pat;
	}
	Move m;
	int score = 0;

    vector<Move> vec; //generate moves
	vec.reserve(128);
	//movegentime.Start();
	pos.generateCaptures(vec);
	//pos.generatePawnPushes(vec);
	//movegentime.Stop();

	//vector<int> scores; //generate move scores
	//scores.reserve(128);
	//generateCaptureScores(vec, scores);

	int material = getBoardMaterial<COLOR_WHITE>()+getBoardMaterial<COLOR_BLACK>();
	Move bestmove = CONS_NULLMOVE;
	int bound = TT_ALPHA;
	for(int i = 0;i<vec.size();i++)
	{
		//m = getHighestScoringMove(vec,i);
		m = vec[i];
		int special = m.getSpecial();
		int captured = m.getCapturedPiece();
		if ((stand_pat + PieceMaterial[getSquare2Piece(captured)] + 200 < alpha) //delta pruning
			&& (special != PIECE_QUEEN && special != PIECE_KNIGHT  && special != PIECE_ROOK && special != PIECE_BISHOP) //not a promotion
			//&& (material > EndgameMaterial)
			)
		{
            continue;
		}
		if (StaticExchangeEvaluation(m.getTo(), m.getFrom(), m.getMovingPiece(), captured) < 0)
			continue;
			//break; //since moves are sorted by SEE, we know remaining moves will also have SEE<0
		//if (getSquare2Piece(m.getCapturedPiece()) == PIECE_KING) //captured opponent king
		//	return CONS_INF;
		if(!pos.makeMove(m))
		{
			continue;
		}
		//pos.forceMove(m);
		ply++;
		if (ply > SelectiveDepth)
		{
			SelectiveDepth = ply;
		}
		score = -QuiescenceSearch(-beta,-alpha);
		pos.unmakeMove(m);
		ply--;
		if (score >= beta)
		{
			//Table.Save(pos.TTKey, -1, score, TT_BETA, m);
			return score;
		}
			
		if (alpha < score)
		{
			alpha = score;
			bestmove = m;
			bound = TT_EXACT;
		}
			
	}
	//Table.Save(pos.TTKey, -1, alpha, TT_ALPHA, bestmove);
	//quisctime.Stop();
	return alpha;
}
Ejemplo n.º 9
0
static serv_state
run_rpc(void)
{
#ifdef HAVE_SIGACTION
  sigset_t smask;
  sigprocmask(SIG_BLOCK, &masked_sigs, &smask);
#else /* not HAVE_SIGACTION */
  int smask = sigblock(MASKED_SIGS);
#endif /* not HAVE_SIGACTION */

  next_softclock = clocktime();

  amd_state = Run;

  /*
   * Keep on trucking while we are in Run mode.  This state
   * is switched to Quit after all the file systems have
   * been unmounted.
   */
  while ((int) amd_state <= (int) Finishing) {
    struct timeval tvv;
    int nsel;
    time_t now;
#ifdef HAVE_SVC_GETREQSET
    fd_set readfds;

    memmove(&readfds, &svc_fdset, sizeof(svc_fdset));
    FD_SET(fwd_sock, &readfds);
#else /* not HAVE_SVC_GETREQSET */
# ifdef FD_SET
    fd_set readfds;
    FD_ZERO(&readfds);
    readfds.fds_bits[0] = svc_fds;
    FD_SET(fwd_sock, &readfds);
# else /* not FD_SET */
    int readfds = svc_fds | (1 << fwd_sock);
# endif /* not FD_SET */
#endif /* not HAVE_SVC_GETREQSET */

    checkup();

    /*
     * If the full timeout code is not called,
     * then recompute the time delta manually.
     */
    now = clocktime();

    if (next_softclock <= now) {
      if (amd_state == Finishing)
	umount_exported();
      tvv.tv_sec = softclock();
    } else {
      tvv.tv_sec = next_softclock - now;
    }
    tvv.tv_usec = 0;

    if (amd_state == Finishing && last_used_map < 0) {
      flush_mntfs();
      amd_state = Quit;
      break;
    }

#ifdef HAVE_FS_AUTOFS
    autofs_add_fdset(&readfds);
#endif /* HAVE_FS_AUTOFS */

    if (tvv.tv_sec <= 0)
      tvv.tv_sec = SELECT_MAXWAIT;
    if (tvv.tv_sec) {
      dlog("Select waits for %ds", (int) tvv.tv_sec);
    } else {
      dlog("Select waits for Godot");
    }

    nsel = do_select(smask, FD_SETSIZE, &readfds, &tvv);

    switch (nsel) {
    case -1:
      if (errno == EINTR) {
	dlog("select interrupted");
	continue;
      }
      plog(XLOG_ERROR, "select: %m");
      break;

    case 0:
      break;

    default:
      /*
       * Read all pending NFS responses at once to avoid having responses
       * queue up as a consequence of retransmissions.
       */
#ifdef FD_SET
      if (FD_ISSET(fwd_sock, &readfds)) {
	FD_CLR(fwd_sock, &readfds);
#else /* not FD_SET */
      if (readfds & (1 << fwd_sock)) {
	readfds &= ~(1 << fwd_sock);
#endif /* not FD_SET */
	--nsel;
	do {
	  fwd_reply();
	} while (rpc_pending_now() > 0);
      }

#ifdef HAVE_FS_AUTOFS
      if (nsel)
	nsel = autofs_handle_fdset(&readfds, nsel);
#endif /* HAVE_FS_AUTOFS */

      if (nsel) {
	/*
	 * Anything left must be a normal
	 * RPC request.
	 */
#ifdef HAVE_SVC_GETREQSET
	svc_getreqset(&readfds);
#else /* not HAVE_SVC_GETREQSET */
# ifdef FD_SET
	svc_getreq(readfds.fds_bits[0]);
# else /* not FD_SET */
	svc_getreq(readfds);
# endif /* not FD_SET */
#endif /* not HAVE_SVC_GETREQSET */
      }
      break;
    }
  }

#ifdef HAVE_SIGACTION
  sigprocmask(SIG_SETMASK, &smask, NULL);
#else /* not HAVE_SIGACTION */
  (void) sigsetmask(smask);
#endif /* not HAVE_SIGACTION */

  if (amd_state == Quit)
    amd_state = Done;

  return amd_state;
}


int
mount_automounter(int ppid)
{
  /*
   * Old code replaced by rpc-trash patch.
   * Erez Zadok <*****@*****.**>
   int so = socket(AF_INET, SOCK_DGRAM, 0);
   */
  SVCXPRT *udp_amqp = NULL, *tcp_amqp = NULL;
  int nmount, ret;
  int soNFS;
  int udp_soAMQ, tcp_soAMQ;
  struct netconfig *udp_amqncp, *tcp_amqncp;

  /*
   * Create the nfs service for amd
   */
  ret = create_nfs_service(&soNFS, &nfs_port, &nfsxprt, nfs_program_2);
  if (ret != 0)
    return ret;
  /* security: if user sets -D noamq, don't even create listening socket */
  amuDebug(D_AMQ) {
    ret = create_amq_service(&udp_soAMQ, &udp_amqp, &udp_amqncp, &tcp_soAMQ, &tcp_amqp, &tcp_amqncp);
    if (ret != 0)
      return ret;
  }

#ifdef HAVE_FS_AUTOFS
  if (amd_use_autofs) {
    /*
     * Create the autofs service for amd.
     */
    ret = create_autofs_service();
    /* if autofs service fails it is OK if using a test amd */
    if (ret != 0) {
      plog(XLOG_WARNING, "autofs service registration failed, turning off autofs support");
      amd_use_autofs = 0;
    }
  }
#endif /* HAVE_FS_AUTOFS */

  /*
   * Start RPC forwarding
   */
  if (fwd_init() != 0)
    return 3;

  /*
   * Construct the root automount node
   */
  make_root_node();

  /*
   * Pick up the pieces from a previous run
   * This is likely to (indirectly) need the rpc_fwd package
   * so it *must* come after the call to fwd_init().
   */
  if (gopt.flags & CFM_RESTART_EXISTING_MOUNTS)
    restart();

  /*
   * Mount the top-level auto-mountpoints
   */
  nmount = mount_exported();

  /*
   * Now safe to tell parent that we are up and running
   */
  if (ppid)
    kill(ppid, SIGQUIT);

  if (nmount == 0) {
    plog(XLOG_FATAL, "No work to do - quitting");
    amd_state = Done;
    return 0;
  }

#ifdef DEBUG
  amuDebug(D_AMQ)
#endif /* DEBUG */
  {
    /*
     * Complete registration of amq (first TCP service then UDP)
     */
    unregister_amq();

    ret = amu_svc_register(tcp_amqp, get_amd_program_number(), AMQ_VERSION,
			   amq_program_1, IPPROTO_TCP, tcp_amqncp);
    if (ret != 1) {
      plog(XLOG_FATAL, "unable to register (AMQ_PROGRAM=%d, AMQ_VERSION, tcp)", get_amd_program_number());
      return 3;
    }

    ret = amu_svc_register(udp_amqp, get_amd_program_number(), AMQ_VERSION,
			   amq_program_1, IPPROTO_UDP, udp_amqncp);
    if (ret != 1) {
      plog(XLOG_FATAL, "unable to register (AMQ_PROGRAM=%d, AMQ_VERSION, udp)", get_amd_program_number());
      return 4;
    }
  }

  /*
   * Start timeout_mp rolling
   */
  reschedule_timeout_mp();

  /*
   * Start the server
   */
  if (run_rpc() != Done) {
    plog(XLOG_FATAL, "run_rpc failed");
    amd_state = Done;
  }
  return 0;
}
Ejemplo n.º 10
0
int Quiescent (int alpha, int beta)
{
    int i = 0;
    int movescnt = 0;
    int score = 0;
    int best = 0;
    MOVE qMovesBuf[200];

    countquiesCalls++;
    nodes++;

    /* Do some housekeeping every 1024 nodes */
    if ((nodes & 1023) == 0)
        checkup(stop_time);
    if (must_stop)
        return 0;

    if (reps() >= 2)
        return 0;

    best = Eval(alpha, beta);
    // --- stand pat cutoff?
    if (best > alpha)
        {
            if (best >= beta)
                return best;
            alpha = best;
        }

    /* As we are in qasearch we generate the captures */
    movescnt = GenCaps (side, qMovesBuf);
    countCapCalls++;

#ifdef SEARCH_DEBUG
            if (movescnt > 200) printf("Too much moves!: %d", movescnt);
#endif

    /* Now the alpha-beta search in quiescent */
    for (i = 0; i < movescnt; ++i)
        {
        MoveOrder(i, movescnt, qMovesBuf);

            if (!MakeMove (qMovesBuf[i]))
            {
                /* If the current move isn't legal, we take it back
                 * and take the next move in the list */
                TakeBack ();
                continue;
            }

            score = -Quiescent (-beta, -alpha);
            TakeBack ();

            if ((nodes & 1023) == 0)
                checkup(stop_time);
            if (must_stop)
                return 0;

            if (score >= beta)
                return beta;
            if (score > alpha)
                alpha = score;
        }
#ifdef SEARCH_DEBUG
    if (alpha > MATE) printf("alpha too high: %d", alpha);
    if (alpha < -MATE) printf("alpha too low: %d", alpha);
#endif

    return alpha;
}
Ejemplo n.º 11
0
int Search (int alpha, int beta, int depth, MOVE * pBestMove, LINE * pline)
{

    /* Vars deffinition */
    int i;
    int value;			/* To store the evaluation */
    int havemove;		/* Either we have or not a legal move available */
    int movecnt;		/* The number of available moves */

//    int score;
    MOVE moveBuf[200];  /* List of movements */
    MOVE tmpMove;
    LINE    line;

    nodes++;
    countSearchCalls++;

    /* Do some housekeeping every 1024 nodes */
    if ((nodes & 1023) == 0)
        checkup(stop_time);
    if (must_stop)
        return 0;

    havemove = 0;		/* is there a move available? */
    pBestMove->type_of_move = MOVE_TYPE_NONE;

    /* If we are in a leaf node we cal quiescence instead of eval */
    if (depth == 0)
        {
            pline->cmove = 0;
            return Quiescent(alpha, beta);
            /* Uncomment nest line if want to make tests avoiding qsearch */
            //return Eval(alpha, beta);
        }

    /* If we're in check we want to search deeper */
    if (IsInCheck(side))
        ++depth;

    /* Static null move prunning */
    if (ply && !IsInCheck(side))
        {
            int ev = Eval(-MATE, MATE);
            int evalua = ev - 150;
            if (evalua >= beta)
                return beta;
        }

    /* Generate and count all moves for current position */
    movecnt = GenMoves (side, moveBuf);

    /* Once we have all the moves available, we loop through the posible
     * moves and apply an alpha-beta search */
    for (i = 0; i < movecnt; ++i)
        {
            /* Here must be called OrderMove, so we have the moves are ordered before
            picking one up from the list*/
            MoveOrder(i, movecnt, moveBuf);

            /* If the current move isn't legal, we take it back
             * and take the next move in the list */
            if (!MakeMove (moveBuf[i]))
                {
                    TakeBack ();
                    continue;
                }

            /* If we've reached this far, then we have a move available */
            havemove = 1;

            value = -Search(-beta, -alpha, depth - 1, &tmpMove, &line);

            /* We've evaluated the position, so we return to the previous position in such a way
               that when we take the next move from moveBuf everything is in order */
            TakeBack ();

            /* Once we have an evaluation, we use it in in an alpha-beta search */
            if (value > alpha)
                {
                    /* Este movimiento causo un cutoff, asi que incrementamos
                    el valor de historia para que sea ordenado antes la
                    proxima vez que se busque */
                    history[moveBuf[i].from][moveBuf[i].dest] += depth;

                    /* This move is so good and caused a cutoff */
                    if (value >= beta)
                        {
                            return beta;
                        }
                    alpha = value;
                    /* So far, current move is the best reaction for current position */
                    *pBestMove = moveBuf[i];

                    /* Update the principal line */
                    pline->argmove[0] = moveBuf[i];
                    memcpy(pline->argmove + 1, line.argmove, line.cmove * sizeof(MOVE));
                    pline->cmove = line.cmove + 1;
                }
        }

    /* Once we've checked all the moves, if we have no legal moves,
     * then that's checkmate or stalemate */
    if (!havemove)
        {
            if (IsInCheck (side))
                return -MATE + ply;	/* add ply to find the longest path to lose or shortest path to win */
            else
                return 0;
        }

    /* 3 vecez la misma posicion */
    if (reps() >= 2)
        return 0;

    if (fifty >= 100) /* 50 jugadas o mas */
        return 0;

    /* Finally we return alpha, the score value */
    return alpha;
}
Ejemplo n.º 12
0
Move Engine::IterativeDeepening(int mode, uint64_t wtime, uint64_t btime, uint64_t winc, uint64_t binc, bool print)
{
	int status = pos.getGameStatus();
	if(status==STATUS_WHITEMATED || status == STATUS_BLACKMATED || status == STATUS_STALEMATE)
	{
		return CONS_NULLMOVE;
	}

	vector<Move> moves;
	pos.generateMoves(moves);
	if (moves.size() == 1) //only 1 legal move
		return moves.at(0);

	//init
	prepareSearch();

	timeMode = mode;
	AllocatedTime = 1;
	uint64_t mytime = 1;
	uint64_t opptime = 1;
	if (mode == MODE_MOVETIME)
	{
		AllocatedTime = wtime;
	}
	else
	{
		if (pos.turn == COLOR_WHITE)
		{
			mytime = wtime;
			opptime = btime;
		}
		else
		{
			mytime = btime;
			opptime = wtime;
		}
		AllocatedTime = max((uint64_t)1, mytime / 15);
	}
	if(mode==MODE_DEPTH)
	{
		MAXDEPTH = wtime;
	}
	else
	{
		MAXDEPTH = 100;
	}
	if (opptime < mytime / 4 && timeMode == MODE_DEFAULT)
	{
		AllocatedTime = max((uint64_t)1, mytime / 4); //if opponent is in time trouble lets take our sweet time
	}

#ifdef BLITZKRIEG_DEBUG
	if(print)
		cout << "Allocated Time: " << AllocatedTime << endl;
#endif

	vector<Move> line;
	line.reserve(128);
	
	int score = AlphaBeta(1,CONS_NEGINF,CONS_INF,&line,false,false);
	//int score = think(1,CONS_NEGINF,CONS_INF,&line);
	//PrincipalVariation = line;
	int val = 0;
	int lastscore = 0;
	timer.Start();
	int takeback = 0;
	int initialmovenumber = pos.movelist.size();
	Move bestmove = line.at(line.size()-1);

	/*for (int i = 0;i < 128;i++)
	{
		PrincipalVariation[i] = CONS_NULLMOVE;
	}*/
	//cout << "takeback set " << takeback << " " << PrincipalVariation.size() << endl;
	takeback = setjmp(env);
	if(takeback!=0)
	{
		while(pos.movelist.size()>initialmovenumber)
		{
			pos.takebackMove();
			takeback--;
		}

		if (print)
		{
			cout << "info string ";
			//cout << "Eval time: " << evaltime.time << ", Sort time: " << sorttime.time << ", Quisc time: " << quisctime.time << ", movegen time: " << movegentime.time << ", Timer: " << timer.ElapsedMilliseconds();
			cout << "Nodes: " << nodes << ", Pruned nodes: " << prunednodes << ": " << ((double)(prunednodes * 100) / nodes) << "%, Futility nodes: " << futilitynodes << ": " << ((double)(futilitynodes * 100) / nodes) << "%";
			cout << ", Avg. beta: " << ((double)betacutoff_sum / betacutoff_counter);
			cout << ", First beta: " << ((double)(firstbetacutoffcount*100) / betacutoff_counter) << "%";
			cout << ", Latemove researches: " << latemoveresearch;
			cout << ", PV researches: " << pvresearch;
			//cout << ", Bad null: " << badavoidnull;
			cout << ", Aspiration Resets: " << aspirationresets;
			cout << ", Nullcutoffs: " << nullcutoffs;
			/*cout << ", Avg. alpha first: " << ((double)alphafirst_sum / alpha_counter);
			cout << ", Avg. alpha last: " << ((double)alphalast_sum / alpha_counter);*/
			cout << ", Fake Hits: " << ((double)(Table.hits * 100) / nodes);
			cout << ", TT hits: " << tthitcount << ": " << ((double)(tthitcount * 100) / nodes) << "%" << endl;
			Table.hits = 0;
		}
		
		/*if (PvSize < 0)
		{
			cout << "info string ERROR: pv size is 0\n";
			return CONS_NULLMOVE;
		}*/
		ply = 0;
		return bestmove;
	}
	incheck[0] = pos.underCheck(pos.turn);
	for (int i = 2;i <= MAXDEPTH;i++)
	{
		//mr = think(i,CONS_NEGINF,CONS_INF);
		//mr = think(i,score - 100,score + 100); //aspiration search
		//if(mr.eval <= score-150 || mr.eval >= score+150)
		//{
		//	cout << "Aspiration fail " << mr.eval << endl;
		//	mr = think(i,CONS_NEGINF,CONS_INF);
		//}
		//int low = 8;
		//int high = 8;

		/*PvSize = -1;
		PvPly = -1;*/

		int delta = 32;
		int alpha = max(score - delta, int(CONS_NEGINF));
		int beta = min(score + delta, int(CONS_INF));

		while (true)
		{
			//line = deque<Move>();
			ply = 0;
			//PvSize = -1;
			line.clear();
			val = AlphaBeta(i, alpha, beta, &line, true, true);
			checkup();
			//cout << "asp. " << alpha << " " << beta << endl;
			/*for (int i = 0;i < 2;i++)
			{
				for (int j = 0;j < 100;j++)
				{
					KillerScores[i][j] = CONS_NEGINF;
				}
			}*/
			if (val <= alpha)
			{
				beta = (alpha + beta) / 2;
				alpha = max(score - delta, int(CONS_NEGINF));
				//cout << "val is " << val << endl;
				//low = low << 1;
			}
			else if (val >= beta)
			{
				alpha = (alpha + beta) / 2;
				beta = min(score + delta, int(CONS_INF));
				//cout << "val is " << val << endl;
				//high = high << 1;
			}
			else break;

			delta += delta / 2;
			aspirationresets++;
		}
		lastscore = score;
		score = val;
		assert(score > CONS_NEGINF && score < CONS_INF);
		timer.Stop();
		if (print)
		{
			cout << "info score cp " << score << " depth " << i << " seldepth " << SelectiveDepth << " nodes " << nodes << " nps " << getNPS(nodes, timer.ElapsedMilliseconds()) << " time " << timer.ElapsedMilliseconds() << " pv ";
			for (int j = line.size() - 1;j >= 0;j--)
			{
				cout << line.at(j).toString() << " ";
			}
			cout << endl;
			/*for (int j = 0;j < 128;j++)
			{
				if (PrincipalVariation[j].isNullMove())
					break;
				cout << PrincipalVariation[j].toString() << " ";
			}*/
		}
		PrincipalVariation = line;
		bestmove = line.at(line.size()-1);
		if (timeMode == MODE_DEFAULT)
		{
			if (score > lastscore + 100 || score < lastscore - 100) //score changed? allocate more time
			{
				AllocatedTime = min(AllocatedTime + mytime / 30, max((uint64_t)1, mytime / 4));
			}
		}
	}
	if (print)
	{
		cout << "Nodes: " << nodes << endl;
		cout << "info string Eval time: " << evaltime.ElapsedMilliseconds() << ", Sort time: " << sorttime.ElapsedMilliseconds() << ", Quisc time: " << quisctime.ElapsedMilliseconds() << ", movegen time: " << movegentime.ElapsedMilliseconds() << endl;
	}
	/*if (PvSize < 0)
	{
		cout << "info string ERROR: principal variation size is 0\n";
		return CONS_NULLMOVE;
	}*/
	//Move bestmove = PrincipalVariation[0];
	ply = 0;
	return bestmove;
}
Ejemplo n.º 13
0
int Engine::AlphaBeta(int depth, int alpha, int beta, vector<Move>* variation, bool cannull, bool dopv)
{
#ifdef BLITZKRIEG_DEBUG
	Bitset tablekey = pos.PawnKey;
	if (alpha > beta || alpha < CONS_NEGINF || beta > CONS_INF)
	{
		cout << "info string ERROR: alpha > beta" << alpha << " " << beta << " " << ply << endl;
	}
#endif

	if (isDraw()) return 0;

	///Quiescence
	if (depth == 0)
	{
		int value = QuiescenceSearch(alpha, beta); //go to quiescence
		/*if (value > alpha && value < beta)
			PvSize = ply - 1;*/
		//Table.Save(pos.TTKey,0,value,TT_EXACT,CONS_NULLMOVE);
		return value;
	}

	nodes++;
	if (nodes%CheckupNodeCount == 0)
	{
		checkup();
		//nodes = 0;
	}

	///Repetition
	if (ply != 0 && pos.isRepetition()) //check for repetition
	{
		//Table.Save(pos.TTKey,depth,0,TT_EXACT,CONS_NULLMOVE);
		return 0;
	}

	///Probe
	int probe = Table.Probe(pos.TTKey, depth, alpha, beta);
	Move ttbestmove = createNullMove(pos.epsquare);
	if (probe != CONS_TTUNKNOWN)
	{
		//cout << probe << " found " << pos.TTKey << endl;
		if (ply != 0)
		{
			tthitcount++;
			return probe;
		}
		/*else
		{
			ttbestmove = Table.getBestMove(pos.TTKey);
			if (!ttbestmove.isNullMove())
			{
				variation->push_back(ttbestmove);
				tthitcount++;
				return probe;
			}
		}*/
	}
	//if (probe.avoidnull) cannull = false;

	int leafevalprobe = Table.Probe(pos.TTKey, 0, alpha, beta);
	if (leafevalprobe!=CONS_TTUNKNOWN 
		//&& leafevalprobe.entry->bound==TT_EXACT
		)
	{
		Evaluation[ply] = leafevalprobe; //use TT probe as a better leafeval
	}
	else
	{
		if (ply > 0 && currentVariation[ply] == CONS_NULLMOVE) //if last move was a nullmove, just invert score
		{
			Evaluation[ply] = -Evaluation[ply-1];
			assert(!cannull);
		}
		else
		{
			Evaluation[ply] = LeafEval<false>();
		}	
	}

	///Razoring
	if (!dopv && ply != 0 && depth < 4 && !incheck[ply] &&
		(((Evaluation[ply] + getRazorMargin(depth)) <= alpha)))
	{
		prunednodes++;
		if (depth <= 1 && (Evaluation[ply] + getRazorMargin(3)) <= alpha)
			return QuiescenceSearch(alpha, beta);

		int ralpha = alpha - getRazorMargin(depth);
		int v = QuiescenceSearch(ralpha, ralpha + 1);
		if (v <= ralpha)
			return v;
	}

	///Futility
	if (depth < 5 && ply != 0 && !incheck[ply] && ((Evaluation[ply] - getFutilityMargin(depth)) >= beta))
	{
		futilitynodes++;
		return (Evaluation[ply] - getFutilityMargin(depth));
	}

	int bound = TT_ALPHA;
	/*vector<Move> dummyline;
	dummyline.reserve(128);*/
	/*vector<Move> lineptr;
	lineptr.reserve(128);*/
	vector<Move> line;
	line.reserve(128);
	Move m;
	int score = 0;

	///Null Move
	bool madenullmove = false;
	Bitset Pieces = pos.OccupiedSq ^ pos.Pieces[COLOR_WHITE][PIECE_PAWN] ^ pos.Pieces[COLOR_BLACK][PIECE_PAWN];
	int pieceCount = popcnt(Pieces);
	if (cannull && !dopv && depth >= 3 && incheck[ply] == false
		&& (pieceCount>2) //side to move does not have only pawns(to avoid zugzwang)
		//&& Evaluation[ply] >= beta
		)
	{
		madenullmove = true;

		//int R = depth > 5 ? 3 : 2; //dynamic depth-based reduction
		int R = ((823 + 67 * depth) / 256 + std::min(max(0, Evaluation[ply] - beta) / PieceMaterial[PIECE_PAWN], 3));
		m = createNullMove(pos.epsquare);
		ply++;

#ifdef BLITZKRIEG_DEBUG
		Bitset ttkeynull = pos.TTKey;
#endif

		pos.forceMove(m);

		/*bool fullnullmovesearch = true;

		if (depth >= 7)
		{
			score = -QuiescenceSearchStandPat(-beta, -beta+1);
			if (score < beta)
				fullnullmovesearch = false;
		}
		if(fullnullmovesearch)*/
		score = -AlphaBeta(max(0, depth - R), -beta, -beta+1, &line, false, false); //make a null-window search (we don't care by how much it fails high, if it does)
		ply--;
		pos.unmakeMove(m);
		if (line.empty()!=true)
			Threats[ply] = line.at(line.size() - 1);

#ifdef BLITZKRIEG_DEBUG
		if (ttkeynull != pos.TTKey)
		{
			cout << "info string ERROR: Null TT fail" << endl;
			_getch();
		}
#endif

		if (score >= beta)
		{
			//cout << "Null move cutoff " << beta << endl;
			/*if (probe.avoidnull)
				badavoidnull++;*/
			nullcutoffs++;
			return score;
		}
		//if (score < alpha - 100) //score is so bad, we are in danger, so increase depth
		//{
		//	depth++;
		//}
	}

	//futility pruning
	//bool futilityprune = false;

	//if (depth < 4 && !underCheck && 
	//	(((leafeval + FutilityMargin[depth]) <= alpha))) //futility pruning
	//{
	//	futilitynodes++;
	//	futilityprune = true;
	//}

	//movesort(vec,depth);
	bool alpharaised = false;
	bool foundlegal = false;
	Move alphamove = CONS_NULLMOVE;
	int finalalpha = -1;
	int firstalpha = -1;
	//vec = pos.generateMoves();
	vector<Move> vec;
	vec.reserve(128);
	//movegentime.Start();
	//if (futilityprune)
	//{
	//	pos.generateCaptures(vec); //search only captures in futility pruning
	//}
	//else
	//{
	pos.generateMoves(vec);
	//}
	//movegentime.Stop();
	/*vector<Move> line;
	line.reserve(128);*/
	/*vector<int> scores;
	scores.reserve(128);
	generateCaptureScores(vec, scores);*/

	if (probe==CONS_TTUNKNOWN && (dopv || Evaluation[ply] + 256 >= beta) && depth >= 2) //internal iterative deepening
	{
		int score = AlphaBeta(depth-2, alpha, beta, &line, false, dopv);
	}	

	int evaldiff = ply >= 2 ? Evaluation[ply] - Evaluation[ply - 2] : 0;
	
	vector<Move> quietmoves;
	quietmoves.reserve(128);
	int bestscore = CONS_NEGINF;
	//int oldsortphase = SORTPHASE_NONE;
	for (unsigned int i = 0;i < vec.size();i++) //search
	{
		line.clear();
		//dummyline.clear();
		//m = vec.at(i);
		//int tablekey2 = pos.TTKey;
		m = getHighestScoringMove(vec, i);

#ifdef BLITZKRIEG_DEBUG
		if (SortPhase == SORTPHASE_NONE)
			cout << "info string Sort Phase error" << endl;
#endif

		int capturedpiece = m.getCapturedPiece();
		int special = m.getSpecial();
		int movingpiece = m.getMovingPiece();
		int moveto = m.getTo();
		int movefrom = m.getFrom();

		int iscapture = isCapture(m);
		/*int see = 0;
		int evade_see = 0;
		Move smallestattckr = pos.getSmallestAttacker(getOpponent(pos.turn), movefrom);
		if (iscapture)
		{
			see = StaticExchangeEvaluation(moveto, movefrom, movingpiece, capturedpiece);
		}
		if (!smallestattckr.isNullMove())
		{
			evade_see = StaticExchangeEvaluation(movefrom, smallestattckr.getTo(), smallestattckr.getMovingPiece(), movingpiece);
		}*/

		//if (iscapture && depth <= 1 && see < 0)
		//{ //prune bad captures at low depths
		//	continue;
		//}

		//if (depth < 8
		//	&& !alpharaised
		//	&& noMaterialGain(m)
		//	//&& !incheck[ply]
		//	&& !incheck[ply - 1]
		//	&& movingpiece!=PIECE_PAWN
		//	)
		//{
		//	if (i >= 2+depth*depth)
		//	{
		//		continue;
		//	}
		//}

		if (!pos.makeMove(m))
		{
			continue;
		}
		//if (vec.size() == 1 || (foundlegal==false && i==vec.size()-1)) //singular extension, only 1 legal move, so extend
		//{
		//	depth++;
		//}
		foundlegal = true;
		ply++;
		currentVariation[ply] = m;
		
		score = 0;

		int reductiondepth = 1;

		///Check Extension
		if (pos.underCheck(pos.turn))
		{
			incheck[ply] = true;
			reductiondepth--;
		}
		else
		{
			incheck[ply] = false;
		}

		///Recapture Extension
		/*if (ply > 1 && m.getTo() == currentVariation[ply - 1].getTo() && iscapture && isCapture(currentVariation[ply - 1]))
		{
			reductiondepth--;
		}*/

		//extend when capturing the last piece
		/*if (isCapture(m) && getSquare2Piece(capturedpiece) != PIECE_PAWN
			&& popcnt(pos.Pieces[COLOR_WHITE][PIECE_PAWN]) + popcnt(pos.Pieces[COLOR_BLACK][PIECE_PAWN]) + 2 == popcnt(pos.OccupiedSq))
		{
			reductiondepth -= 3;
		}*/

		/*if (depth < 16)
		{
			if (!incheck[ply - 1]
				&& !incheck[ply]
				&& movingpiece != PIECE_PAWN
				&& noMaterialGain(m))
			{
				if(i > 3 + (1 << (depth-1)))
				{
					pos.unmakeMove(m);
					incheck[ply] = false;
					ply--;
					continue;
				}
			}
		}*/

		//if (!dopv && depth < 4 && ((Evaluation[ply] + getSmallRazorMargin(depth)) <= alpha)) //small forward razoring
		//{
		//	reductiondepth++;
		//}

		///Latemove Reduction
		if (!alpharaised
			//&& i >= 4
			&& depth >= 4
			//&& special!=PIECE_QUEEN
			//&& (see < 0 || !iscapture)
			&& SortPhase >= SORTPHASE_HISTORY
			//&& noMaterialGain(m)
			//&& (KillerMoves[0][ply].getTo() != moveto || KillerMoves[0][ply].getFrom() != movefrom)
			//&& (KillerMoves[1][ply].getTo() != moveto || KillerMoves[1][ply].getFrom() != movefrom)
			&& !incheck[ply]
			&& !incheck[ply-1]
			//&& (movingpiece!=PIECE_PAWN || getRank(getColorMirror(getOpponent(pos.turn), moveto))<6) //dont reduce pawn moves past 6th rank
			//&& m!=Threats[ply]
			)
		{
			if (evaldiff > 0)
				reductiondepth += min(depth - 4, min((int)i,4));
			else
				reductiondepth += min(depth - 4, min((int)i+1,5));
			assert((depth - reductiondepth) >= 3);
			if (!dopv && HistoryScores[movingpiece][moveto] < 0) //history reduction
			{
				reductiondepth++;
			}
			if (m == Threats[ply] && reductiondepth > 0) //decrease reduction if move is a threat
			{
				reductiondepth = max(reductiondepth - 1, 0);
			}
			//if (noMaterialGain(m) && !smallestattckr.isNullMove() && evade_see < 0) //decrease reduction if move evades a capture
			//{
			//	reductiondepth = max(reductiondepth - 1, 0);
			//}
		}

		//if (isCapture(m) && !dopv && see > 400 && depth>=5) //prune really good captures
		//{
		//	reductiondepth += 4;
		//}

		//if (alpha_counter != 0 && (depth-reductiondepth)>=3 && i>((double)alphalast_sum/alpha_counter) && capturedpiece == SQUARE_EMPTY && special == PIECE_NONE
		//	&& !pos.underCheck(pos.turn)
		//	&& (KillerMoves[0][ply].getTo() != m.getTo() || KillerMoves[0][ply].getFrom() != m.getFrom())
		//	&& (KillerMoves[1][ply].getTo() != m.getTo() || KillerMoves[1][ply].getFrom() != m.getFrom())) //latemove reduction
		//{
		//	reductiondepth += 2;
		//	/*reductiondepth ++;
		//	if (i >= 8 && depth >= 6)
		//	{
		//		reductiondepth++;
		//		if (i >= 12 && depth >= 9) 
		//			reductiondepth++;
		//	}*/
		//}
		
		///Search
		if(dopv && i>0 && depth>=3) //principal variation search
		{
			score = -AlphaBeta(max(depth - reductiondepth, 0), -alpha - 1, -alpha, &line, true, false);
			if(score > alpha && score < beta) //check for failure
			{
				line.clear();
				score = -AlphaBeta(depth - 1, -beta, -alpha, &line, true, true); //research
				alpharaised = false;
				pvresearch++;
				//cout << "pv research" << endl;
			}
		}
		else
		{
			score = -AlphaBeta(max(depth - reductiondepth,0), -beta, -alpha, &line, true, dopv);
			//cout << "latemove" << endl;
			if(score > alpha && score < beta && reductiondepth>1)
			{
				line.clear();
				score = -AlphaBeta(depth - 1, -beta, -alpha, &line, true, dopv);
				latemoveresearch++;
			}
		}
		currentVariation[ply] = CONS_NULLMOVE;
		incheck[ply] = false;
		ply--;
		pos.unmakeMove(m);

		assert(score > CONS_NEGINF && score < CONS_INF);
		assert(score >= CONS_MATED && score <= -CONS_MATED);

		if(score>=beta)
		{
			if(noMaterialGain(m))
			{
				//if(Table.getBestMove(pos.TTKey)!=m) //dont store hash move as a killer
				setKiller(m, depth, score);

				int bonus = depth*depth;
				HistoryScores[movingpiece][m.getTo()] += bonus;
				if (HistoryScores[movingpiece][m.getTo()] > 200000) //prevent overflow of history values
				{
					for (int i = 0;i < 6;i++)
					{
						for (int j = 0;j < 64;j++)
						{
							HistoryScores[i][j] /= 2;
						}
					}
				}
				for (int i = 0;i < quietmoves.size();i++)
				{
					/*if(HistoryScores[quietmoves.at(i).getMovingPiece()][quietmoves.at(i).getTo()] <= bonus)
						HistoryScores[quietmoves.at(i).getMovingPiece()][quietmoves.at(i).getTo()] = 0;
					else*/
						HistoryScores[quietmoves.at(i).getMovingPiece()][quietmoves.at(i).getTo()] -= bonus;
				}
			}
			Table.Save(pos.TTKey, depth, score, TT_BETA, m);

#ifdef BLITZKRIEG_STATS
			betacutoff_counter++;
			betacutoff_sum += i+1;
			if (i == 0)
				firstbetacutoffcount++;
#endif
			return score; //fail soft beta cutoff
		}
		else if(score>bestscore)
		{
			bestscore = score;
			if (score > alpha)
			{
				bound = TT_EXACT;
				alpha = score;
				alpharaised = true;
				alphamove = m;

				*variation = line;

				if (noMaterialGain(m))
					HistoryScores[movingpiece][m.getTo()] += depth;

#ifdef BLITZKRIEG_STATS
				if (firstalpha == -1)
				{
					firstalpha = i;
				}
				finalalpha = i;
#endif
			}
		}

		if (noMaterialGain(m))
		{
			quietmoves.push_back(m);
		}
	}
	if(!foundlegal)
	{
		//if(futilityprune)
		//{
		//	//movegentime.Start();
		//	vec.clear();
		//	pos.generateMoves(vec);
		//	//movegentime.Stop();
		//	int flag = 1;
		//	for(int i = 0;i<vec.size();i++)
		//	{
		//		if(pos.makeMove(m))
		//		{
		//			unmakeMove(m);
		//			flag = 0;
		//			break;
		//		}
		//	}
		//	if(flag)
		//	{
		//		if(pos.underCheck(pos.turn))
		//		{
		//			return CONS_MATED-ply;
		//		}
		//		else
		//		{
		//			return CONS_DRAW;
		//		}
		//	}
		//}
		//else
		{
			if(pos.underCheck(pos.turn))
			{
				return CONS_MATED+ply;
			}
			else
			{
				return CONS_DRAW;
			}
		}
	}
	if(!alphamove.isNullMove())
	{
		variation->push_back(alphamove);
		//if(dopv)
		//	PrincipalVariation[ply] = alphamove;
		/*if (depth == 1)
		{
			PvSize = ply;
			PvPly = ply;
		}*/
		/*else if (ply == PvPly - 1)
		{
			PrincipalVariation[ply] = alphamove;
			PvPly = ply;
		}*/
		//HistoryScores[alphamove.getFrom()][alphamove.getTo()] += depth+finalalpha;
#ifdef BLITZKRIEG_STATS
		alpha_counter++;
		alphalast_sum += (finalalpha + 1);
		alphafirst_sum += (firstalpha + 1);
#endif
	}
	Table.Save(pos.TTKey, depth, bestscore, bound, alphamove);
	/*if (ply == 0)
	{
		cout << "info string Stored: " << alphamove.toString() << " " << bound << " " << depth << endl;
	}*/

#ifdef BLITZKRIEG_DEBUG
	if (pos.PawnKey != tablekey)
	{
		cout << "info string ERROR: Pawn TT key doesnt match" << endl;
	}
#endif
	return bestscore;
}
Ejemplo n.º 14
0
void MyPlane::move_up()
{
    if (checkup()) {
        move(0, -speed);
    }
}
Ejemplo n.º 15
0
static serv_state
run_rpc(void)
{
#ifdef HAVE_SIGACTION
  sigset_t smask;
  sigprocmask(SIG_BLOCK, &masked_sigs, &smask);
#else /* not HAVE_SIGACTION */
  int smask = sigblock(MASKED_SIGS);
#endif /* not HAVE_SIGACTION */

  next_softclock = clocktime(NULL);

  amd_state = Run;

  /*
   * Keep on trucking while we are in Run mode.  This state
   * is switched to Quit after all the file systems have
   * been unmounted.
   */
  while ((int) amd_state <= (int) Finishing) {
    struct timeval tvv;
    int nsel;
    time_t now;
    fd_set readfds;

#ifdef HAVE_SVC_GETREQSET
    memmove(&readfds, &svc_fdset, sizeof(svc_fdset));
#else /* not HAVE_SVC_GETREQSET */
    FD_ZERO(&readfds);
# ifdef HAVE_FD_SET_FDS_BITS
    readfds.fds_bits[0] = svc_fds;
# else /* not HAVE_FD_SET_FDS_BITS */
    readfds = svc_fds;
# endif  /* not HAVE_FD_SET_FDS_BITS */
#endif /* not HAVE_SVC_GETREQSET */
    FD_SET(fwd_sock, &readfds);

    checkup();

    /*
     * If the full timeout code is not called,
     * then recompute the time delta manually.
     */
    now = clocktime(NULL);

    if (next_softclock <= now) {
      if (amd_state == Finishing)
	umount_exported();
      tvv.tv_sec = softclock();
    } else {
      tvv.tv_sec = next_softclock - now;
    }
    tvv.tv_usec = 0;

    if (amd_state == Finishing && get_exported_ap(0) == NULL) {
      flush_mntfs();
      amd_state = Quit;
      break;
    }

#ifdef HAVE_FS_AUTOFS
    autofs_add_fdset(&readfds);
#endif /* HAVE_FS_AUTOFS */

    if (tvv.tv_sec <= 0)
      tvv.tv_sec = SELECT_MAXWAIT;
    if (tvv.tv_sec) {
      dlog("Select waits for %ds", (int) tvv.tv_sec);
    } else {
      dlog("Select waits for Godot");
    }

    nsel = do_select(smask, FD_SETSIZE, &readfds, &tvv);

    switch (nsel) {
    case -1:
      if (errno == EINTR) {
	dlog("select interrupted");
	continue;
      }
      plog(XLOG_ERROR, "select: %m");
      break;

    case 0:
      break;

    default:
      /*
       * Read all pending NFS responses at once to avoid having responses
       * queue up as a consequence of retransmissions.
       */
      if (FD_ISSET(fwd_sock, &readfds)) {
	FD_CLR(fwd_sock, &readfds);
	--nsel;
	do {
	  fwd_reply();
	} while (rpc_pending_now() > 0);
      }

#ifdef HAVE_FS_AUTOFS
      if (nsel)
	nsel = autofs_handle_fdset(&readfds, nsel);
#endif /* HAVE_FS_AUTOFS */

      if (nsel) {
	/*
	 * Anything left must be a normal
	 * RPC request.
	 */
#ifdef HAVE_SVC_GETREQSET
	svc_getreqset(&readfds);
#else /* not HAVE_SVC_GETREQSET */
# ifdef HAVE_FD_SET_FDS_BITS
	svc_getreq(readfds.fds_bits[0]);
# else /* not HAVE_FD_SET_FDS_BITS */
	svc_getreq(readfds);
# endif /* not HAVE_FD_SET_FDS_BITS */
#endif /* not HAVE_SVC_GETREQSET */
      }
      break;
    }
  }

#ifdef HAVE_SIGACTION
  sigprocmask(SIG_SETMASK, &smask, NULL);
#else /* not HAVE_SIGACTION */
  (void) sigsetmask(smask);
#endif /* not HAVE_SIGACTION */

  if (amd_state == Quit)
    amd_state = Done;

  return amd_state;
}