示例#1
0
        error_code deploy_svc_service_impl::start()
        {
            std::string pdir = utils::filesystem::path_combine(dsn_get_current_app_data_dir(), "services");
            _service_dir = dsn_config_get_value_string("deploy.service",
                "deploy_dir",
                pdir.c_str(),
                "where to put temporal deployment resources"
                );

            // load clusters
            const char* clusters[100];
            int sz = 100;
            int count = dsn_config_get_all_keys("deploy.service.clusters", clusters, &sz);
            dassert(count <= 100, "too many clusters");

            for (int i = 0; i < count; i++)
            {
                std::string cluster_name = dsn_config_get_value_string(
                    clusters[i],
                    "name",
                    "",
                    "cluster name"
                    );

                if (nullptr != get_cluster(cluster_name))
                {
                    derror("cluster %s already defined", cluster_name.c_str());
                    return ERR_CLUSTER_ALREADY_EXIST;
                }

                std::string cluster_factory_type = dsn_config_get_value_string(
                    clusters[i],
                    "factory",
                    "",
                    "factory name to create the target cluster scheduler"
                    );

                auto cluster = ::dsn::utils::factory_store<cluster_scheduler>::create(
                    cluster_factory_type.c_str(),
                    PROVIDER_TYPE_MAIN
                    );

                if (nullptr == cluster)
                {
                    derror("cluster type %s is not defined", cluster_factory_type.c_str());
                    return ERR_OBJECT_NOT_FOUND;
                }

                std::shared_ptr<cluster_ex> ce(new cluster_ex);
                ce->scheduler.reset(cluster);
                ce->cluster.name = cluster_name;
                ce->cluster.type = cluster->type();

                _clusters[cluster_name] = ce;
            }

            _cli_deploy = dsn_cli_app_register(
                "deploy",
                "deploy deploy_request(in json format)",
                "deploy an app via our deployment service",
                (void*)this,
                [](void *context, int argc, const char **argv, dsn_cli_reply *reply)
                {
                    auto this_ = (deploy_svc_service_impl*)context;
                    this_->on_deploy_cli(context, argc, argv, reply);
                },
                __svc_cli_freeer__
                );

            _cli_undeploy = dsn_cli_app_register(
                "undeploy",
                "undeploy service_name(in json format)",
                "undeploy an app via our deployment service",
                (void*)this,
                [](void *context, int argc, const char **argv, dsn_cli_reply *reply)
                {
                    auto this_ = (deploy_svc_service_impl*)context;
                    this_->on_undeploy_cli(context, argc, argv, reply);
                },
                __svc_cli_freeer__
                );

            _cli_get_service_list = dsn_cli_app_register(
                "service_list",
                "service_list package_id(in json format)",
                "get service list of a package via our deployment service",
                (void*)this,
                [](void *context, int argc, const char **argv, dsn_cli_reply *reply)
                {
                    auto this_ = (deploy_svc_service_impl*)context;
                    this_->on_get_service_list_cli(context, argc, argv, reply);
                },
                __svc_cli_freeer__
                );

            _cli_get_service_info = dsn_cli_app_register(
                "service_info",
                "service_info service_name(in json format)",
                "get service info of a service via our deployment service",
                (void*)this,
                [](void *context, int argc, const char **argv, dsn_cli_reply *reply)
                {
                    auto this_ = (deploy_svc_service_impl*)context;
                    this_->on_get_service_info_cli(context, argc, argv, reply);
                },
                __svc_cli_freeer__
                );

            _cli_get_cluster_list = dsn_cli_app_register(
                "cluster_list",
                "cluster_list format(in json format)",
                "get cluster list with a specific format via our deployment service",
                (void*)this,
                [](void *context, int argc, const char **argv, dsn_cli_reply *reply)
                {
                    auto this_ = (deploy_svc_service_impl*)context;
                    this_->on_get_cluster_list_cli(context, argc, argv, reply);
                },
                __svc_cli_freeer__
                );

            return ERR_OK;
        }
示例#2
0
/** solve one of the eight Appollonius Equations
| Cx - Ci|^2=(Rx+Ri)^2
with Cx the center of the common tangent circle, Rx the radius. Ci and Ri are the Center and radius of the i-th existing circle
**/
std::vector<RS_Circle> RS_Circle::solveAppolloniusSingle(const std::vector<RS_Circle>& circles)
{
//          std::cout<<__FILE__<<" : "<<__func__<<" : line "<<__LINE__<<std::endl;
//          for(int i=0;i<circles.size();i++){
//std::cout<<"i="<<i<<"\t center="<<circles[i].getCenter()<<"\tr="<<circles[i].getRadius()<<std::endl;
//          }
	std::vector<RS_Circle> ret;

	std::vector<RS_Vector> centers;
	std::vector<double> radii;

	for(auto c: circles){
		if(c.getCenter().valid==false) return ret;
		centers.push_back(c.getCenter());
		radii.push_back(c.getRadius());
	}
//              for(int i=0;i<circles.size();i++){
//    std::cout<<"i="<<i<<"\t center="<<circles[i].getCenter()<<"\tr="<<radii.at(i)<<std::endl;
//              }
/** form the linear equation to solve center in radius **/
	std::vector<std::vector<double> > mat(2,std::vector<double>(3,0.));
    mat[0][0]=centers[2].x - centers[0].x;
    mat[0][1]=centers[2].y - centers[0].y;
    mat[1][0]=centers[2].x - centers[1].x;
    mat[1][1]=centers[2].y - centers[1].y;
    if(fabs(mat[0][0]*mat[1][1] - mat[0][1]*mat[1][0])<RS_TOLERANCE2){
//        DEBUG_HEADER
//        std::cout<<"The provided circles are in a line, not common tangent circle"<<std::endl;
        size_t i0=0;
        if( centers[0].distanceTo(centers[1]) <= RS_TOLERANCE ||  centers[0].distanceTo(centers[2]) <= RS_TOLERANCE) i0 = 1;
        LC_Quadratic lc0(& (circles[i0]), & (circles[(i0+1)%3]));
        LC_Quadratic lc1(& (circles[i0]), & (circles[(i0+2)%3]));
		auto c0 = LC_Quadratic::getIntersection(lc0, lc1);
//        qDebug()<<"c0.size()="<<c0.size();
        for(size_t i=0; i<c0.size(); i++){
            const double dc =  c0[i].distanceTo(centers[i0]);
			ret.push_back(RS_Circle(nullptr, {c0[i], fabs(dc - radii[i0])}));
            if( dc > radii[i0]) {
				ret.push_back(RS_Circle(nullptr, {c0[i], dc + radii[i0]}));
            }
        }
        return ret;
    }
    // r^0 term
    mat[0][2]=0.5*(centers[2].squared()-centers[0].squared()+radii[0]*radii[0]-radii[2]*radii[2]);
    mat[1][2]=0.5*(centers[2].squared()-centers[1].squared()+radii[1]*radii[1]-radii[2]*radii[2]);
//    std::cout<<__FILE__<<" : "<<__func__<<" : line "<<__LINE__<<std::endl;
//    for(unsigned short i=0;i<=1;i++){
//        std::cout<<"eqs P:"<<i<<" : "<<mat[i][0]<<"*x + "<<mat[i][1]<<"*y = "<<mat[i][2]<<std::endl;
//    }
//    std::vector<std::vector<double> > sm(2,std::vector<double>(2,0.));
	std::vector<double> sm(2,0.);
    if(RS_Math::linearSolver(mat,sm)==false){
        return ret;
    }

    RS_Vector vp(sm[0],sm[1]);
//      std::cout<<__FILE__<<" : "<<__func__<<" : line "<<__LINE__<<std::endl;
//      std::cout<<"vp="<<vp<<std::endl;

    // r term
    mat[0][2]= radii[0]-radii[2];
    mat[1][2]= radii[1]-radii[2];
//    for(unsigned short i=0;i<=1;i++){
//        std::cout<<"eqs Q:"<<i<<" : "<<mat[i][0]<<"*x + "<<mat[i][1]<<"*y = "<<mat[i][2]<<std::endl;
//    }
    if(RS_Math::linearSolver(mat,sm)==false){
        return ret;
    }
    RS_Vector vq(sm[0],sm[1]);
//      std::cout<<"vq="<<vq<<std::endl;
    //form quadratic equation for r
    RS_Vector dcp=vp-centers[0];
    double a=vq.squared()-1.;
    if(fabs(a)<RS_TOLERANCE*1e-4) {
        return ret;
    }
    std::vector<double> ce(0,0.);
    ce.push_back(2.*(dcp.dotP(vq)-radii[0])/a);
    ce.push_back((dcp.squared()-radii[0]*radii[0])/a);
    std::vector<double>&& vr=RS_Math::quadraticSolver(ce);
    for(size_t i=0; i < vr.size();i++){
        if(vr.at(i)<RS_TOLERANCE) continue;
		ret.emplace_back(RS_Circle(nullptr, {vp+vq*vr.at(i),fabs(vr.at(i))}));
    }
//    std::cout<<__FILE__<<" : "<<__func__<<" : line "<<__LINE__<<std::endl;
//    std::cout<<"Found "<<ret.size()<<" solutions"<<std::endl;

    return ret;
}
//
//  Reinitialize this object using platform ticks.
//
void LocalTime::fromTicks(ticks_t tk) {
    CommonEra ce(0);
    ce.fromTicks(tk);
    this->fromCommonEra(ce);
}
/* ===========================================================================
 * offset_adjust_settings (internal)
 *
 * This function is called by offset_add_value() every time 10 samples have
 * been accumulated.  This function updates the internal statistics for
 * paranoia (dynoverlap, dyndrift) that compensate for jitter and drift.
 *
 * (dynoverlap) influences how far stage 1 and stage 2 search for matching
 * runs.  In low-jitter conditions, it will be very small (or even 0),
 * narrowing our search.  In high-jitter conditions, it will be much larger,
 * widening our search at the cost of speed.
 *
 * ???: To be studied further.
 */
void
offset_adjust_settings(cdrom_paranoia_t *p,
		       void(*callback)(long int, paranoia_cb_mode_t))
{
  if(p->stage2.offpoints>=10){
    /* drift: look at the average offset value.  If it's over one
       sector, frob it.  We just want a little hysteresis [sp?]*/
    long av=(p->stage2.offpoints?p->stage2.offaccum/p->stage2.offpoints:0);

    if(labs(av)>p->dynoverlap/4){
      av=(av/MIN_SECTOR_EPSILON)*MIN_SECTOR_EPSILON;

      if(callback)(*callback)(ce(p->root.vector),PARANOIA_CB_DRIFT);
      p->dyndrift+=av;

      /* Adjust all the values in the cache otherwise we get a
	 (potentially unstable) feedback loop */
      {
	c_block_t *c=c_first(p);
	v_fragment_t *v=v_first(p);

	while(v && v->one){
	  /* safeguard beginning bounds case with a hammer */
	  if(fb(v)<av || cb(v->one)<av){
	    v->one=NULL;
	  }else{
	    fb(v)-=av;
	  }
	  v=v_next(v);
	}
	while(c){
	  long adj=min(av,cb(c));
	  c_set(c,cb(c)-adj);
	  c=c_next(c);
	}
      }

      p->stage2.offaccum=0;
      p->stage2.offmin=0;
      p->stage2.offmax=0;
      p->stage2.offpoints=0;
      p->stage2.newpoints=0;
      p->stage2.offdiff=0;
    }
  }

  if(p->stage1.offpoints>=10){
    /* dynoverlap: we arbitrarily set it to 4x the running difference
       value, unless min/max are more */

    p->dynoverlap=(p->stage1.offpoints?p->stage1.offdiff/
		   p->stage1.offpoints*3:CD_FRAMEWORDS);

    if(p->dynoverlap<-p->stage1.offmin*1.5)
      p->dynoverlap=-p->stage1.offmin*1.5;

    if(p->dynoverlap<p->stage1.offmax*1.5)
      p->dynoverlap=p->stage1.offmax*1.5;

    if(p->dynoverlap<MIN_SECTOR_EPSILON)p->dynoverlap=MIN_SECTOR_EPSILON;
    if(p->dynoverlap>MAX_SECTOR_OVERLAP*CD_FRAMEWORDS)
      p->dynoverlap=MAX_SECTOR_OVERLAP*CD_FRAMEWORDS;

    if(callback)(*callback)(p->dynoverlap,PARANOIA_CB_OVERLAP);

    if(p->stage1.offpoints>600){ /* bit of a bug; this routine is
				    called too often due to the overlap
				    mesh alg we use in stage 1 */
      p->stage1.offpoints/=1.2;
      p->stage1.offaccum/=1.2;
      p->stage1.offdiff/=1.2;
    }
    p->stage1.offmin=0;
    p->stage1.offmax=0;
    p->stage1.newpoints=0;
  }
}
示例#5
0
int
answer()
{
	PLAYER			*pp;
	int			newsock;
	static u_long		mode;
	static char		name[NAMELEN];
	static char		team;
	static int		enter_status;
	static int		socklen;
	static u_long		machine;
	static u_int32_t	uid;
	static SOCKET		sockstruct;
	char			*cp1, *cp2;
	int			flags;
	u_int32_t		version;
	int			i;

# ifdef INTERNET
	socklen = sizeof sockstruct;
# else
	socklen = sizeof sockstruct - 1;
# endif
	errno = 0;
	newsock = accept(Socket, (struct sockaddr *) &sockstruct, &socklen);
	if (newsock < 0)
	{
		if (errno == EINTR)
			return FALSE;
# ifdef LOG
		syslog(LOG_ERR, "accept: %m");
# else
		perror("accept");
# endif
		cleanup(1);
	}

# ifdef INTERNET
	machine = ntohl(((struct sockaddr_in *) &sockstruct)->sin_addr.s_addr);
# else
	if (machine == 0)
		machine = gethostid();
# endif
	version = htonl((u_int32_t) HUNT_VERSION);
	(void) write(newsock, (char *) &version, LONGLEN);
	(void) read(newsock, (char *) &uid, LONGLEN);
	uid = ntohl((unsigned long) uid);
	(void) read(newsock, name, NAMELEN);
	(void) read(newsock, &team, 1);
	(void) read(newsock, (char *) &enter_status, LONGLEN);
	enter_status = ntohl((unsigned long) enter_status);
	(void) read(newsock, Ttyname, NAMELEN);
	(void) read(newsock, (char *) &mode, sizeof mode);
	mode = ntohl(mode);

	/*
	 * Turn off blocking I/O, so a slow or dead terminal won't stop
	 * the game.  All subsequent reads check how many bytes they read.
	 */
	flags = fcntl(newsock, F_GETFL, 0);
	flags |= O_NDELAY;
	(void) fcntl(newsock, F_SETFL, flags);

	/*
	 * Make sure the name contains only printable characters
	 * since we use control characters for cursor control
	 * between driver and player processes
	 */
	for (cp1 = cp2 = name; *cp1 != '\0'; cp1++)
		if (isprint((unsigned char)*cp1) || *cp1 == ' ')
			*cp2++ = *cp1;
	*cp2 = '\0';

# ifdef INTERNET
	if (mode == C_MESSAGE) {
		char	buf[BUFSIZ + 1];
		int	n;

		if (team == ' ')
			(void) sprintf(buf, "%s: ", name);
		else
			(void) sprintf(buf, "%s[%c]: ", name, team);
		n = strlen(buf);
		for (pp = Player; pp < End_player; pp++) {
			cgoto(pp, HEIGHT, 0);
			outstr(pp, buf, n);
		}
		while ((n = read(newsock, buf, BUFSIZ)) > 0)
			for (pp = Player; pp < End_player; pp++)
				outstr(pp, buf, n);
		for (pp = Player; pp < End_player; pp++) {
			ce(pp);
			sendcom(pp, REFRESH);
			sendcom(pp, READY, 0);
			(void) fflush(pp->p_output);
		}
		(void) close(newsock);
		return FALSE;
	}
	else
# endif
# ifdef MONITOR
	if (mode == C_MONITOR)
		if (End_monitor < &Monitor[MAXMON]) {
			pp = End_monitor++;
			i = pp - Monitor + MAXPL + 3;
		} else {
			socklen = 0;
			(void) write(newsock, (char *) &socklen,
				sizeof socklen);
			(void) close(newsock);
			return FALSE;
		}
	else
# endif
		if (End_player < &Player[MAXPL]) {
			pp = End_player++;
			i = pp - Player + 3;
		} else {
			socklen = 0;
			(void) write(newsock, (char *) &socklen,
				sizeof socklen);
			(void) close(newsock);
			return FALSE;
		}

#ifdef MONITOR
	if (mode == C_MONITOR && team == ' ')
		team = '*';
#endif
	pp->p_ident = get_ident(machine, uid, name, team);
	pp->p_output = fdopen(newsock, "w");
	pp->p_death[0] = '\0';
	pp->p_fd = newsock;
	fdset[i].fd = newsock;
	fdset[i].events = POLLIN;

	pp->p_y = 0;
	pp->p_x = 0;

# ifdef MONITOR
	if (mode == C_MONITOR)
		stmonitor(pp);
	else
# endif
		stplayer(pp, enter_status);
	return TRUE;
}
示例#6
0
void ConsoleUtils::ReportForServiceWorkerScopeInternal(
    const nsAString& aScope, const nsAString& aMessage,
    const nsAString& aFilename, uint32_t aLineNumber, uint32_t aColumnNumber,
    Level aLevel) {
  MOZ_ASSERT(NS_IsMainThread());

  AutoJSAPI jsapi;
  jsapi.Init();

  JSContext* cx = jsapi.cx();

  ConsoleCommon::ClearException ce(cx);
  JS::Rooted<JSObject*> global(cx, GetOrCreateSandbox(cx));
  if (NS_WARN_IF(!global)) {
    return;
  }

  // The GetOrCreateSandbox call returns a proxy to the actual sandbox object.
  // We don't need a proxy here.
  global = js::UncheckedUnwrap(global);

  JSAutoRealm ar(cx, global);

  RootedDictionary<ConsoleEvent> event(cx);

  event.mID.Construct();
  event.mID.Value().SetAsString() = aScope;

  event.mInnerID.Construct();
  event.mInnerID.Value().SetAsString() = NS_LITERAL_STRING("ServiceWorker");

  switch (aLevel) {
    case eLog:
      event.mLevel = NS_LITERAL_STRING("log");
      break;

    case eWarning:
      event.mLevel = NS_LITERAL_STRING("warn");
      break;

    case eError:
      event.mLevel = NS_LITERAL_STRING("error");
      break;
  }

  event.mFilename = aFilename;
  event.mLineNumber = aLineNumber;
  event.mColumnNumber = aColumnNumber;
  event.mTimeStamp = JS_Now() / PR_USEC_PER_MSEC;

  JS::Rooted<JS::Value> messageValue(cx);
  if (!dom::ToJSValue(cx, aMessage, &messageValue)) {
    return;
  }

  event.mArguments.Construct();
  if (!event.mArguments.Value().AppendElement(messageValue, fallible)) {
    return;
  }

  nsCOMPtr<nsIConsoleAPIStorage> storage =
      do_GetService("@mozilla.org/consoleAPI-storage;1");

  if (NS_WARN_IF(!storage)) {
    return;
  }

  JS::Rooted<JS::Value> eventValue(cx);
  if (!ToJSValue(cx, event, &eventValue)) {
    return;
  }

  // This is a legacy property.
  JS::Rooted<JSObject*> eventObj(cx, &eventValue.toObject());
  if (NS_WARN_IF(!JS_DefineProperty(cx, eventObj, "wrappedJSObject", eventObj,
                                    JSPROP_ENUMERATE))) {
    return;
  }

  storage->RecordEvent(NS_LITERAL_STRING("ServiceWorker"), aScope, eventValue);
}
示例#7
0
/*
 * zap:
 *	Kill off a player and take them out of the game.
 *	The 'was_player' flag indicates that the player was not
 *	a monitor and needs extra cleaning up.
 */
static void
zap(PLAYER *pp, FLAG was_player)
{
	int	len;
	BULLET	*bp;
	PLAYER	*np;
	int	x, y;
	int	savefd;

	if (was_player) {
		/* If they died from a shot, clean up shrapnel */
		if (pp->p_undershot)
			fixshots(pp->p_y, pp->p_x, pp->p_over);
		/* Let the player see their last position: */
		drawplayer(pp, FALSE);
		/* Remove from game: */
		Nplayer--;
	}

	/* Display the cause of death in the centre of the screen: */
	len = strlen(pp->p_death);
	x = (WIDTH - len) / 2;
	outyx(pp, HEIGHT / 2, x, "%s", pp->p_death);

	/* Put some horizontal lines around and below the death message: */
	memset(pp->p_death + 1, '-', len - 2);
	pp->p_death[0] = '+';
	pp->p_death[len - 1] = '+';
	outyx(pp, HEIGHT / 2 - 1, x, "%s", pp->p_death);
	outyx(pp, HEIGHT / 2 + 1, x, "%s", pp->p_death);

	/* Move to bottom left */
	cgoto(pp, HEIGHT, 0);

	savefd = pp->p_fd;

	if (was_player) {
		int	expl_charge;
		int	expl_type;
		int	ammo_exploding;

		/* Check all the bullets: */
		for (bp = Bullets; bp != NULL; bp = bp->b_next) {
			if (bp->b_owner == pp)
				/* Zapped players can't own bullets: */
				bp->b_owner = NULL;
			if (bp->b_x == pp->p_x && bp->b_y == pp->p_y)
				/* Bullets over the player are now over air: */
				bp->b_over = SPACE;
		}

		/* Explode a random fraction of the player's ammo: */
		ammo_exploding = rand_num(pp->p_ammo);

		/* Determine the type and amount of detonation: */
		expl_charge = rand_num(ammo_exploding + 1);
		if (pp->p_ammo == 0)
			/* Ignore the no-ammo case: */
			expl_charge = expl_type = 0;
		else if (ammo_exploding >= pp->p_ammo - 1) {
			/* Maximal explosions always appear as slime: */
			expl_charge = pp->p_ammo;
			expl_type = SLIME;
		} else {
			/*
			 * Figure out the best effective explosion
			 * type to use, given the amount of charge
			 */
			int btype, stype;
			for (btype = MAXBOMB - 1; btype > 0; btype--)
				if (expl_charge >= shot_req[btype])
					break;
			for (stype = MAXSLIME - 1; stype > 0; stype--)
				if (expl_charge >= slime_req[stype])
					break;
			/* Pick the larger of the bomb or slime: */
			if (btype >= 0 && stype >= 0) {
				if (shot_req[btype] > slime_req[btype])
					btype = -1;
			}
			if (btype >= 0)  {
				expl_type = shot_type[btype];
				expl_charge = shot_req[btype];
			} else
				expl_type = SLIME;
		}

		if (expl_charge > 0) {
			char buf[BUFSIZ];

			/* Detonate: */
			add_shot(expl_type, pp->p_y, pp->p_x,
			    pp->p_face, expl_charge, NULL,
			    TRUE, SPACE);

			/* Explain what the explosion is about. */
			snprintf(buf, sizeof buf, "%s detonated.",
				pp->p_ident->i_name);
			message(ALL_PLAYERS, buf);

			while (pp->p_nboots-- > 0) {
				/* Throw one of the boots away: */
				for (np = Boot; np < &Boot[NBOOTS]; np++)
					if (np->p_flying < 0)
						break;
#ifdef DIAGNOSTIC
				if (np >= &Boot[NBOOTS])
					err(1, "Too many boots");
#endif
				/* Start the boots from where the player is */
				np->p_undershot = FALSE;
				np->p_x = pp->p_x;
				np->p_y = pp->p_y;
				/* Throw for up to 20 steps */
				np->p_flying = rand_num(20);
				np->p_flyx = 2 * rand_num(6) - 5;
				np->p_flyy = 2 * rand_num(6) - 5;
				np->p_over = SPACE;
				np->p_face = BOOT;
				showexpl(np->p_y, np->p_x, BOOT);
			}
		}
		/* No explosion. Leave the player's boots behind. */
		else if (pp->p_nboots > 0) {
			if (pp->p_nboots == 2)
				Maze[pp->p_y][pp->p_x] = BOOT_PAIR;
			else
				Maze[pp->p_y][pp->p_x] = BOOT;
			if (pp->p_undershot)
				fixshots(pp->p_y, pp->p_x,
					Maze[pp->p_y][pp->p_x]);
		}

		/* Any unexploded ammo builds up in the volcano: */
		volcano += pp->p_ammo - expl_charge;

		/* Volcano eruption: */
		if (conf_volcano && rand_num(100) < volcano /
		    conf_volcano_max) {
			/* Erupt near the middle of the map */
			do {
				x = rand_num(WIDTH / 2) + WIDTH / 4;
				y = rand_num(HEIGHT / 2) + HEIGHT / 4;
			} while (Maze[y][x] != SPACE);

			/* Convert volcano charge into lava: */
			add_shot(LAVA, y, x, LEFTS, volcano,
				NULL, TRUE, SPACE);
			volcano = 0;

			/* Tell eveyone what's happening */
			message(ALL_PLAYERS, "Volcano eruption.");
		}

		/* Drone: */
		if (conf_drone && rand_num(100) < 2) {
			/* Find a starting place near the middle of the map: */
			do {
				x = rand_num(WIDTH / 2) + WIDTH / 4;
				y = rand_num(HEIGHT / 2) + HEIGHT / 4;
			} while (Maze[y][x] != SPACE);

			/* Start the drone going: */
			add_shot(DSHOT, y, x, rand_dir(),
				shot_req[conf_mindshot +
				rand_num(MAXBOMB - conf_mindshot)],
				NULL, FALSE, SPACE);
		}

		/* Tell the zapped player's client to shut down. */
		sendcom(pp, ENDWIN, ' ');
		fclose(pp->p_output);

		/* Close up the gap in the Player array: */
		End_player--;
		if (pp != End_player) {
			/* Move the last player into the gap: */
			memcpy(pp, End_player, sizeof *pp);
			outyx(ALL_PLAYERS,
				STAT_PLAY_ROW + 1 + (pp - Player),
				STAT_NAME_COL,
				"%5.2f%c%-10.10s %c",
				pp->p_ident->i_score, stat_char(pp),
				pp->p_ident->i_name, pp->p_ident->i_team);
		}

		/* Erase the last player from the display: */
		cgoto(ALL_PLAYERS, STAT_PLAY_ROW + 1 + Nplayer, STAT_NAME_COL);
		ce(ALL_PLAYERS);
	}
	else {
		/* Zap a monitor */

		/* Close the session: */
		sendcom(pp, ENDWIN, LAST_PLAYER);
		fclose(pp->p_output);

		/* shuffle the monitor table */
		End_monitor--;
		if (pp != End_monitor) {
			memcpy(pp, End_monitor, sizeof *pp);
			outyx(ALL_PLAYERS,
				STAT_MON_ROW + 1 + (pp - Player), STAT_NAME_COL,
				"%5.5s %-10.10s %c", " ",
				pp->p_ident->i_name, pp->p_ident->i_team);
		}

		/* Erase the last monitor in the list */
		cgoto(ALL_PLAYERS,
			STAT_MON_ROW + 1 + (End_monitor - Monitor),
			STAT_NAME_COL);
		ce(ALL_PLAYERS);
	}

	/* Update the file descriptor sets used by select: */
	FD_CLR(savefd, &Fds_mask);
	if (Num_fds == savefd + 1) {
		Num_fds = Socket;
		if (Server_socket > Socket)
			Num_fds = Server_socket;
		for (np = Player; np < End_player; np++)
			if (np->p_fd > Num_fds)
				Num_fds = np->p_fd;
		for (np = Monitor; np < End_monitor; np++)
			if (np->p_fd > Num_fds)
				Num_fds = np->p_fd;
		Num_fds++;
	}
}
void THISCLASS::OnSetNewValue() {
	ComponentEditor ce(mComponent);
	ce.SetConfigurationString(mName, mNewValue);
}
示例#9
0
/**
 * Handles command line events.
 */
void RS_EventHandler::commandEvent(RS_CommandEvent* e) {
    RS_DEBUG->print("RS_EventHandler::commandEvent");

    //RS_RegExp rex;
    RS_String cmd = e->getCommand();

    if (coordinateInputEnabled) {
        if (!e->isAccepted()) {
            // handle absolute cartesian coordinate input:
            if (cmd.contains(',') && cmd.at(0)!='@') {
                if (actionIndex>=0 && currentActions[actionIndex]!=NULL &&
                        !currentActions[actionIndex]->isFinished()) {
                    int commaPos = cmd.find(',');
                    RS_DEBUG->print("RS_EventHandler::commandEvent: 001");
                    bool ok1, ok2;
                    RS_DEBUG->print("RS_EventHandler::commandEvent: 002");
                    double x = RS_Math::eval(cmd.left(commaPos), &ok1);
                    RS_DEBUG->print("RS_EventHandler::commandEvent: 003a");
                    double y = RS_Math::eval(cmd.mid(commaPos+1), &ok2);
                    RS_DEBUG->print("RS_EventHandler::commandEvent: 004");

                    if (ok1 && ok2) {
                        RS_DEBUG->print("RS_EventHandler::commandEvent: 005");
                        RS_CoordinateEvent ce(RS_Vector(x,y));
                        RS_DEBUG->print("RS_EventHandler::commandEvent: 006");
                        currentActions[actionIndex]->coordinateEvent(&ce);
                    } else {
                        if (RS_DIALOGFACTORY!=NULL) {
                            RS_DIALOGFACTORY->commandMessage(
                                "Expression Syntax Error");
                        }
                    }
                    e->accept();
                }
            }
        }

        // handle relative cartesian coordinate input:
        if (!e->isAccepted()) {
            if (cmd.contains(',') && cmd.at(0)=='@') {
                if (actionIndex>=0 && currentActions[actionIndex]!=NULL &&
                        !currentActions[actionIndex]->isFinished()) {
                    int commaPos = cmd.find(',');
                    bool ok1, ok2;
                    double x = RS_Math::eval(cmd.mid(1, commaPos-1), &ok1);
                    double y = RS_Math::eval(cmd.mid(commaPos+1), &ok2);

                    if (ok1 && ok2) {
                        RS_CoordinateEvent ce(RS_Vector(x,y) +
                                              graphicView->getRelativeZero());
                        currentActions[actionIndex]->coordinateEvent(&ce);
                    } else {
                        if (RS_DIALOGFACTORY!=NULL) {
                            RS_DIALOGFACTORY->commandMessage(
                                "Expression Syntax Error");
                        }
                    }
                    e->accept();
                }
            }
        }

        // handle absolute polar coordinate input:
        if (!e->isAccepted()) {
            if (cmd.contains('<') && cmd.at(0)!='@') {
                if (actionIndex>=0 && currentActions[actionIndex]!=NULL &&
                        !currentActions[actionIndex]->isFinished()) {
                    int commaPos = cmd.find('<');
                    bool ok1, ok2;
                    double r = RS_Math::eval(cmd.left(commaPos), &ok1);
                    double a = RS_Math::eval(cmd.mid(commaPos+1), &ok2);

                    if (ok1 && ok2) {
                        RS_Vector pos;
                        pos.setPolar(r,RS_Math::deg2rad(a));
                        RS_CoordinateEvent ce(pos);
                        currentActions[actionIndex]->coordinateEvent(&ce);
                    } else {
                        if (RS_DIALOGFACTORY!=NULL) {
                            RS_DIALOGFACTORY->commandMessage(
                                "Expression Syntax Error");
                        }
                    }
                    e->accept();
                }
            }
        }

        // handle relative polar coordinate input:
        if (!e->isAccepted()) {
            if (cmd.contains('<') && cmd.at(0)=='@') {
                if (actionIndex>=0 && currentActions[actionIndex]!=NULL &&
                        !currentActions[actionIndex]->isFinished()) {
                    int commaPos = cmd.find('<');
                    bool ok1, ok2;
                    double r = RS_Math::eval(cmd.mid(1, commaPos-1), &ok1);
                    double a = RS_Math::eval(cmd.mid(commaPos+1), &ok2);

                    if (ok1 && ok2) {
                        RS_Vector pos;
                        pos.setPolar(r,RS_Math::deg2rad(a));
                        RS_CoordinateEvent ce(pos +
                                              graphicView->getRelativeZero());
                        currentActions[actionIndex]->coordinateEvent(&ce);
                    } else {
                        if (RS_DIALOGFACTORY!=NULL) {
                            RS_DIALOGFACTORY->commandMessage(
                                "Expression Syntax Error");
                        }
                    }
                    e->accept();
                }
            }
        }
    }

    // send command event directly to current action:
    if (!e->isAccepted()) {
        if (actionIndex>=0 && currentActions[actionIndex]!=NULL &&
                !currentActions[actionIndex]->isFinished()) {
            currentActions[actionIndex]->commandEvent(e);
            e->accept();
        } else {
            if (defaultAction!=NULL) {
                defaultAction->commandEvent(e);
                //e->accept();
            }
        }
    }

    RS_DEBUG->print("RS_EventHandler::commandEvent: OK");
}
示例#10
0
文件: chase.cpp 项目: daid/Rogue
    coord solve(coord start, coord end)
    {
        this->end = end;

        coord co;
        co.x = start.x;
        co.y = start.y - 1;
        addToList(co.x, co.y, co, 1);
        co.x = start.x - 1;
        co.y = start.y;
        addToList(co.x, co.y, co, 1);
        co.x = start.x + 1;
        co.y = start.y;
        addToList(co.x, co.y, co, 1);
        co.x = start.x;
        co.y = start.y + 1;
        addToList(co.x, co.y, co, 1);

        co.x = start.x - 1;
        co.y = start.y - 1;
        if (diag_ok(&start, &co)) addToList(co.x, co.y, co, 1);
        co.x = start.x + 1;
        co.y = start.y - 1;
        if (diag_ok(&start, &co)) addToList(co.x, co.y, co, 1);
        co.x = start.x - 1;
        co.y = start.y + 1;
        if (diag_ok(&start, &co)) addToList(co.x, co.y, co, 1);
        co.x = start.x + 1;
        co.y = start.y + 1;
        if (diag_ok(&start, &co)) addToList(co.x, co.y, co, 1);

        while(open_list.size() > 0)
        {
            int pos = open_list.front();
            open_list.pop_front();

            int score = info[pos].base_score;
            coord origin = info[pos].origin;

            co.x = pos & 0xFFFF;
            co.y = pos >> 16;
            if (ce(co, end))
                return origin;

            addToList(co.x,     co.y - 1, origin, score + 1);
            addToList(co.x - 1, co.y,     origin, score + 1);
            addToList(co.x + 1, co.y,     origin, score + 1);
            addToList(co.x,     co.y + 1, origin, score + 1);

            coord ct;
            ct.x = co.x - 1;
            ct.y = co.y - 1;
            if (diag_ok(&co, &ct)) addToList(ct.x, ct.y, origin, score + 1);
            ct.x = co.x + 1;
            ct.y = co.y - 1;
            if (diag_ok(&co, &ct)) addToList(ct.x, ct.y, origin, score + 1);
            ct.x = co.x - 1;
            ct.y = co.y + 1;
            if (diag_ok(&co, &ct)) addToList(ct.x, ct.y, origin, score + 1);
            ct.x = co.x + 1;
            ct.y = co.y + 1;
            if (diag_ok(&co, &ct)) addToList(ct.x, ct.y, origin, score + 1);
        }
        return start;
    }
示例#11
0
BOOL CKLinePrintApp::InitInstance()
{
#if 0

	//	维持网络连接/会话
	Net net("192.168.1.1:8080");
	net.start();

	//	执行命令
	CommandExecutor ce(&net);
	string ret = ce.Execute("login");

	//	接收数据
	DataHandler dh(&net);
	

	//	初始化网络连接
	//	创建线程,发起并维持连接
	//	

	CLoginDialog loginDlg;

	if(loginDlg.DoModal()!=IDOK)
	{
		return FALSE;
	}

	CommandExecutor ce();

	string result = ce.Execute("login:oscar,12345,sr");



#endif

	// 如果一个运行在 Windows XP 上的应用程序清单指定要
	// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
	//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// 将它设置为包括所有要在应用程序中使用的
	// 公共控件类。
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinAppEx::InitInstance();

	// 初始化 OLE 库
	if (!AfxOleInit())
	{
		AfxMessageBox(IDP_OLE_INIT_FAILED);
		return FALSE;
	}
	AfxEnableControlContainer();
	// 标准初始化
	// 如果未使用这些功能并希望减小
	// 最终可执行文件的大小,则应移除下列
	// 不需要的特定初始化例程
	// 更改用于存储设置的注册表项
	// TODO: 应适当修改该字符串,
	// 例如修改为公司或组织名
	SetRegistryKey(_T("Oscar"));
	LoadStdProfileSettings(4);  // 加载标准 INI 文件选项(包括 MRU)

	InitContextMenuManager();

	InitKeyboardManager();

	// 注册应用程序的文档模板。文档模板
	// 将用作文档、框架窗口和视图之间的连接
	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(CKLinePrintDoc),
		RUNTIME_CLASS(CMainFrame),       // 主 SDI 框架窗口
		RUNTIME_CLASS(CKLinePrintView));
	if (!pDocTemplate)
		return FALSE;
	AddDocTemplate(pDocTemplate);

	// 分析标准外壳命令、DDE、打开文件操作的命令行
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// 调度在命令行中指定的命令。如果
	// 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	CalendarGenerator cg;
	cg.Generate("C:\\FutureData\\ZZ", m_cal);

	//	读入账户/品种信息
	EXCHANGE.SetBalance(Utility::ReadBalance());
	TP = Utility::ReadExchangeConfig();

	//	设置默认交易日志文件
	EXCHANGE.SetLogFile(Utility::GetProgramPath() + "log\\manual.log.txt");

	srand(time(0));

	//	加载回放配置并生成日历
	m_PlaybackConfig = Utility::ReadPlaybackConfig();
	LoadPlaybackCalendar(m_PlaybackConfig);

	//	自动打开上次的文件
	char path[MAX_PATH];

	::GetPrivateProfileStringA("Files","Current","", 
							path, sizeof(path), 
							(Utility::GetProgramPath() + "klinep.ini").c_str());

	CKLinePrintDoc* pDoc = NULL;

	if(strlen(path))
	{
		pDoc = (CKLinePrintDoc*)OpenDocumentFile(CString(path));
		pDoc->LoadNextDay();
	}

	// 唯一的一个窗口已初始化,因此显示它并对其进行更新
	m_pMainWnd->ShowWindow(SW_SHOW);
	m_pMainWnd->UpdateWindow();
	// 仅当具有后缀时才调用 DragAcceptFiles
	//  在 SDI 应用程序中,这应在 ProcessShellCommand 之后发生
	return TRUE;
}
示例#12
0
CameraPtr Camera::init()
{
   // Create a transform to contain the location and orientation of the camera.
   mTransform = OSG::Transform::create();

   OSG::NodePtr beacon = OSG::Node::create();
#if OSG_MAJOR_VERSION < 2
   OSG::CPEditor be(beacon, OSG::Node::CoreFieldMask);
#endif
   beacon->setCore(mTransform);

   mLeftTexture = tex_chunk_t::create();
#if OSG_MAJOR_VERSION < 2
   OSG::CPEditor lte(mLeftTexture);
   mLeftTexture->setEnvMode(GL_MODULATE);
#else
   mLeftTexEnv = OSG::TextureEnvChunk::create();
   mLeftTexEnv->setEnvMode(GL_MODULATE);
#endif

   mRightTexture = tex_chunk_t::create();
#if OSG_MAJOR_VERSION < 2
   OSG::CPEditor rte(mRightTexture);
   mRightTexture->setEnvMode(GL_MODULATE);
#else
   mRightTexEnv = OSG::TextureEnvChunk::create();
   mRightTexEnv->setEnvMode(GL_MODULATE);
#endif

   mCurrentTexture = mLeftTexture;
#if OSG_MAJOR_VERSION >= 2
   mCurrentTexEnv = mLeftTexEnv;
#endif

   // setup camera
   mCamera = OSG::PerspectiveCamera::create();
#if OSG_MAJOR_VERSION < 2
   OSG::CPEditor ce(mCamera);
#endif
   mCamera->setFov(
#if OSG_MAJOR_VERSION < 2
      OSG::osgdegree2rad(60.0)
#else
      OSG::osgDegree2Rad(60.0)
#endif
   );
   mCamera->setNear(0.01);
   mCamera->setFar(10000);
   mCamera->setBeacon(beacon);

   mLeftImage = OSG::Image::create();
   mRightImage = OSG::Image::create();

   OSG::ImagePtr img;

   // Set up FBO textures.
   img = mLeftImage;
   mLeftTexture->setMinFilter(GL_LINEAR);
   mLeftTexture->setMagFilter(GL_LINEAR);
   mLeftTexture->setTarget(GL_TEXTURE_2D);
   mLeftTexture->setInternalFormat(GL_RGBA8);
   mLeftTexture->setImage(img);

   img = mRightImage;
   mRightTexture->setMinFilter(GL_LINEAR);
   mRightTexture->setMagFilter(GL_LINEAR);
   mRightTexture->setTarget(GL_TEXTURE_2D);
   mRightTexture->setInternalFormat(GL_RGBA8);
   mRightTexture->setImage(img);

   mCurrentImage = mLeftImage;

   return shared_from_this();
}
示例#13
0
/* rhf:
 * The routine that do Hartree Fock calculation, that is, to calculate:
 *  1) Hartree Fock eigenvalues, 
 *  2) Hartree Fock molecular orbitals,
 *  3) 0th, 1th order energy, Hartree Fock energy
 */
std::chrono::duration<double> hartree_fock(calculation_data &data, const double tol=1e-12){
	std::chrono::duration<double> elapsed_seconds(0);
	auto start = std::chrono::steady_clock::now();

	const int n_bases = data.n_baseset;
	const int dime = data.n_paired/2;
	const hermitian_matrix &h = data.ao_h;
	const hermitian_matrix &overlap = data.ao_overlap;
	const dbl_e_itgls &ce = data.ao_2eint;
	matrix &C = data.ao2mo;
	std::vector<double> &eigenvalues = data.eigenvalues;

	// SCF loop
	hermitian_matrix P = hermitian_matrix::idmat(n_bases);
	hermitian_matrix Fuv(n_bases);
	C = matrix(n_bases,n_bases);
	eigenvalues.resize(n_bases);
	bool converged = false;
	double E = 0;

	#ifdef DEBUG
	int count=0;
	#endif

	do{
		#ifdef DEBUG
		count++;
		std::cout << "Loop number: " << count << std::endl;
		matrix F_old = Fuv;
		matrix P_old = P;
		#endif

		matrix C_old = C;
		// build Fock matrix
		Fuv = h;
		for(int u=0;u<n_bases;u++)
			for(int v=0;v<n_bases;v++)
				for(int a=0;a<n_bases;a++)
					for(int b=0;b<n_bases;b++)
						Fuv(u,v) += P(b,a)*(2*ce(u,a,v,b)-ce(u,a,b,v));
		// calculate new C, P and e
		// FC=SCe, C = [c1,c2,...], e = diag(e1,e2,...)
		// Fc1 = e1*Sc1, Fc2 = e2*Sc2, ......
		hermitian_matrix::lowdin_diagonalization(Fuv,overlap,C,eigenvalues);
		matrix Cocc = C.left_columns(dime);
		P = Cocc*(Cocc.conjugate_transpose());

		// test convergence
		matrix diffC = C-C_old;
		double errorC = diffC.norm();
		converged = ( errorC < tol );


		#ifdef DEBUG
		// calculate energy
		E = data.nuclear_repulsion;
		for(int i=0;i<dime;i++)
			E += eigenvalues[i];
		for(int i=0;i<n_bases;i++)
			for(int j=0;j<n_bases;j++)
				E += P(j,i)*h(i,j);

		matrix diffP = P-P_old;
		matrix diffF = Fuv-F_old;
		double errorP = diffP.norm();
		double errorF = diffF.norm(); 
		std::cout << "Energy: " << E << std::endl;
		std::cout << "Error in C: " << errorC << std::endl;
		std::cout << "Error in P: " << errorP << std::endl;
		std::cout << "Error in F: " << errorF << std::endl;
		std::cout << "Eigenvalues:";
		for(int i=0;i<n_bases;i++)
			std::cout << eigenvalues[i] << ' ';
		std::cout << std::endl;
		#ifdef VERBOSE
		std::cout << "C: " << std::endl << C.mat << std::endl;
		std::cout << "delta C: " << std::endl << diffC.mat << std::endl;
		std::cout << "P: " << std::endl << P.mat << std::endl;
		std::cout << "delta P: " << std::endl << diffP.mat << std::endl;
		std::cout << "F: " << std::endl << Fuv.mat << std::endl;
		std::cout << "delta F: " << std::endl << diffF.mat << std::endl;
		std::cout << "-----------------" << std::endl;
		#endif
		#endif

	}while(!converged);

	#ifdef DEBUG
	std::cout << "Converged." << std::endl;
	std::cout << "Energy: " << E << std::endl;
	std::cout << "Eigenvalues:" << std::endl;
	for(int i=0;i<n_bases;i++)
		std::cout << eigenvalues[i] << ' ';
	std::cout << std::endl;
	std::cout << "==========================================" << std::endl;
	#endif

	// calculate energy
	data.E0 = 0;
	for(int i=0;i<dime;i++)
		data.E0 += 2*data.eigenvalues[i];
	E = data.nuclear_repulsion + data.E0/2;
	data.E0 += data.nuclear_repulsion;
	for(int i=0;i<n_bases;i++)
		for(int j=0;j<n_bases;j++)
			E += P(j,i)*h(i,j);
	for(int i=0;i<dime;i++)
	data.E1 = E - data.E0;
	auto end = std::chrono::steady_clock::now();
	elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(end-start);
	return elapsed_seconds;
}
示例#14
0
文件: answer.c 项目: PSR-hunt/hunt
/**
 * Manages the messages submission.
 * \return True in case of success, false instead.
 * [PSR]
 */
int answer() {
	PLAYER *pp;
	int newsock;
	static unsigned long mode; /* Changed from u_long. [PSR] */
	static char name[NAMELEN];
	static char team;
	static int enter_status;
	static unsigned int socklen; /* Edited from static int in order to match accept() parameter. [PSR] */
	static unsigned long machine; /* Edited from u_long in order to match accept() parameter. [PSR] */
	static u_int32_t uid;
	static SOCKET sockstruct;
	char *cp1, *cp2;
	int flags;
	u_int32_t version;
	int i;

# ifdef INTERNET
	socklen = sizeof sockstruct;
# else
	socklen = sizeof sockstruct - 1;
# endif
	errno = 0;
	newsock = accept(main_socket, (struct sockaddr *) &sockstruct, &socklen);
	if (newsock < 0) {
		if (errno == EINTR) {
			return false;
		}
# ifdef LOG
		iso_syslog(LOG_ERR, "accept: %m");
# else
		perror("accept");
# endif
		cleanup(1);
	}

# ifdef INTERNET
	machine = ntohl(((struct sockaddr_in *) &sockstruct)->sin_addr.s_addr);
# else
	if (machine == 0) {
		machine = gethostid();
	}
# endif
	version = htonl((u_int32_t) HUNT_VERSION);
	write_and_push(newsock, (char *) &version, LONGLEN);

	/* Authentication. [PSR] */
#ifdef INTERNET
	if(password_hash!=NULL) { /* A password has been set. [PSR] */
		write_and_push(newsock, &c_auth, SHORTLEN);
		bool auth = false;
		for(i=0; i<MAXATTEMPT && !auth; i++) { /* 3 password attempts. [PSR] */
			safe_read(newsock, &client_psw, (13 + 1) * sizeof(char));
			if(strcmp(client_psw, password_hash)!=0) { /* Authentication failed. New request. [PSR] */
				write_and_push(newsock, &c_auth, SHORTLEN);
			} else { /* Authentication successful. [PSR]*/
				write_and_push(newsock, &c_auth_success, SHORTLEN);
				auth = true;
			}
		}
		if(!auth) {
			write_and_push(newsock, &c_refuse, SHORTLEN);
			safe_close(newsock);
			return false;
		}
	} else { /* No authentication. [PSR] */
		write_and_push(newsock, &c_auth_success, SHORTLEN);
	}
#endif

	safe_read(newsock, (char *) &uid, LONGLEN);
	uid = ntohl((unsigned long) uid);
	safe_read(newsock, name, NAMELEN);
	safe_read(newsock, &team, 1);
	safe_read(newsock, (char *) &enter_status, LONGLEN);
	enter_status = ntohl((unsigned long) enter_status);
	safe_read(newsock, ttyname_glob, NAMELEN);
	safe_read(newsock, (char *) &mode, sizeof mode);
	mode = ntohl(mode);

	/*
	 * Turn off blocking I/O, so a slow or dead terminal won't stop
	 * the game.  All subsequent reads check how many bytes they read.
	 */
	flags = fcntl(newsock, F_GETFL, 0);
	flags |= O_NDELAY;
	(void) fcntl(newsock, F_SETFL, flags);

	/*
	 * Make sure the name contains only printable characters
	 * since we use control characters for cursor control
	 * between driver and player processes
	 */
	for (cp1 = cp2 = name; *cp1 != '\0'; cp1++) {
		if (isprint((unsigned char)*cp1) || *cp1 == ' ') {
			*cp2++ = *cp1;
		}
	}
	*cp2 = '\0';

# ifdef INTERNET
	if (mode == C_MESSAGE) {
		char buf[BUFSIZ + 1];
		int n;

		if (team == ' ') {
			(void) sprintf(buf, "%s: ", name);
		}
		else {
			(void) sprintf(buf, "%s[%c]: ", name, team);
		}
		n = strlen(buf);
		for (pp = player; pp < end_player; pp++) {
			cgoto(pp, HEIGHT, 0);
			outstr(pp, buf, n);
		}
		while ((n = read(newsock, buf, BUFSIZ)) > 0)
		for (pp = player; pp < end_player; pp++) {
			outstr(pp, buf, n);
		}
		for (pp = player; pp < end_player; pp++) {
			ce(pp);
			sendcom(pp, REFRESH);
			sendcom(pp, READY, 0);
			(void) fflush(pp->p_output);
		}
		safe_close(newsock);
		return false;
	}
	else
# endif
# ifdef MONITOR
	if (mode == C_MONITOR) {
		if (end_monitor < &monitor[MAXMON]) {
			pp = end_monitor++;
			i = pp - monitor + MAXPL + 3;
		} else {
			socklen = 0;
			write_and_push(newsock, (char *) &socklen, sizeof socklen);
			safe_close(newsock);
			return false;
		}
	}
	else
# endif
	if (end_player < &player[MAXPL]) {
		pp = end_player++;
		i = pp - player + 3;
	} else {
		socklen = 0;
		write_and_push(newsock, (char *) &socklen, sizeof socklen);
		safe_close(newsock);
		return false;
	}

#ifdef MONITOR
	if (mode == C_MONITOR && team == ' ') {
		team = '*';
	}
#endif
	pp->p_ident = get_ident(machine, uid, name, team);
	pp->p_output = fdopen(newsock, "w");
	pp->p_death[0] = '\0';
	pp->p_fd = newsock;
	fdset[i].fd = newsock;
	fdset[i].events = POLLIN;

	pp->p_y = 0;
	pp->p_x = 0;

# ifdef MONITOR
	if (mode == C_MONITOR) {
		stmonitor(pp);
	}
	else
# endif
	stplayer(pp, enter_status);
	return true;
}
/*
 * chase:
 *	Find the spot for the chaser(er) to move closer to the
 *	chasee(ee).  Returns TRUE if we want to keep on chasing later
 *	FALSE if we reach the goal.
 */
int
chase(struct thing *tp, coord *ee, int flee, int *mdead)
{
    register int x, y;
    register int dist, thisdist, monst_dist = MAXINT;
    register struct linked_list *weapon;
    register coord *er = &tp->t_pos, *shoot_dir;
    register int ch, mch;
    register int next_player = FALSE;
    int deadflg;

	if (mdead != NULL)
		*mdead = 0;

	shoot_dir = can_shoot(er, ee);
    weapon = get_hurl(tp);

    /*
     * If the thing is confused, let it move randomly. Invisible
     * Stalkers are slightly confused all of the time.
     */
    if ((on(*tp, ISHUH) && rnd(10) < 8) ||
	((on(*tp, ISINVIS) || on(*tp, ISSHADOW)) && rnd(100) < 20) ||
	(on(player, ISINVIS) && off(*tp, CANSEE))) { /* Player is invisible */
	/*
	 * get a valid random move
	 */
	ch_ret = *rndmove(tp);
	dist = DISTANCE(ch_ret.y, ch_ret.x, ee->y, ee->x);

    if (on(*tp, ISHUH) && rnd(20) == 0)  /* monster might lose confusion */
        turn_off(*tp, ISHUH);

	/*
	 * check to see if random move takes creature away from player
	 * if it does then turn off ISHELD
	 */
	if (dist > 1 && on(*tp, DIDHOLD)) {
	    turn_off(*tp, DIDHOLD);
	    turn_on(*tp, CANHOLD);
	    if (--hold_count <= 0)
	    {
	        hold_count = 0;
	        turn_off(player, ISHELD);
	    }
	}
    }

    /* If we can breathe, we may do so */
    else if (on(*tp, CANBREATHE) && (shoot_dir) &&
	     (rnd(100) < 67) &&
		 (off(player, ISDISGUISE) || (rnd(tp->t_stats.s_lvl) > 6)) &&
	     (DISTANCE(er->y, er->x, ee->y, ee->x) < BOLT_LENGTH*BOLT_LENGTH)) {
		register int chance;
		register char *breath;

		/* Will it breathe at random */
		if (on(*tp, CANBRANDOM)) {
		    if (rnd(level/20) == 0 && tp->t_index != NUMMONST+1)
			turn_off(*tp, CANBRANDOM);

		    /* Select type of breath */
		    chance = rnd(100);
		    if (chance < 11) breath = "acid";
		    else if (chance < 22) breath = "flame";
		    else if (chance < 33) breath = "lightning bolt";
		    else if (chance < 44) breath = "chlorine gas";
		    else if (chance < 55) breath = "ice";
		    else if (chance < 66) breath = "nerve gas";
		    else if (chance < 77) breath = "sleeping gas";
		    else if (chance < 88) breath = "slow gas";
		    else breath = "fear gas";
		}

		/* Or can it breathe acid? */
		else if (on(*tp, CANBACID)) {
		    if (rnd(level/20) == 0)
			turn_off(*tp, CANBACID);
		    breath = "acid";
		}

		/* Or can it breathe fire */
		else if (on(*tp, CANBFIRE)) {
		    if (rnd(level/20) == 0)
			turn_off(*tp, CANBFIRE);
		    breath = "flame";
		}

		/* Or can it breathe electricity? */
		else if (on(*tp, CANBBOLT)) {
		    if (rnd(level/20) == 0)
			turn_off(*tp, CANBBOLT);
		    breath = "lightning bolt";
		}

		/* Or can it breathe gas? */
		else if (on(*tp, CANBGAS)) {
		    if (rnd(level/20) == 0)
			turn_off(*tp, CANBGAS);
		    breath = "chlorine gas";
		}

		/* Or can it breathe ice? */
		else if (on(*tp, CANBICE)) {
		    if (rnd(level/20) == 0)
			turn_off(*tp, CANBICE);
		    breath = "ice";
		}

		else if (on(*tp, CANBPGAS)) {
		    if (rnd(level/20) == 0)
			turn_off(*tp, CANBPGAS);
		    breath = "nerve gas";
		}

		else if (on(*tp, CANBSGAS)) {
		    if (rnd(level/20) == 0)
			turn_off(*tp, CANBSGAS);
		    breath = "sleeping gas";
		}

		else if (on(*tp, CANBSLGAS)) {
		    if (rnd(level/20) == 0)
			turn_off(*tp, CANBSLGAS);
		    breath = "slow gas";
		}

		else {
		    if (rnd(level/20) == 0)
			turn_off(*tp, CANBFGAS);
		    breath = "fear gas";
		}

		/* Now breathe -- returns TRUE if kills itself */
		deadflg =
		    shoot_bolt(tp, *er, *shoot_dir, FALSE, tp->t_index, breath,
			       (save(VS_BREATH) ? tp->t_stats.s_hpt/2
					        : tp->t_stats.s_hpt));

		if (deadflg && mdead != NULL)
			*mdead = 1;

		ch_ret = *er;
		dist = DISTANCE(ch_ret.y, ch_ret.x, ee->y, ee->x);
		if (deadflg) return(TRUE);
	}

    /* 
     * If we can shoot or throw something, we might do so 
     * if we are running away, we may decide to shoot anyway if we are far 
     * enough
     */
    else if((off(*tp, ISFLEE) || rnd(DISTANCE(er->y,er->x,ee->y,ee->x)) > 2) && 
	     on(*tp, CANSHOOT) && (off(player, ISDISGUISE) ||
		 (rnd(tp->t_stats.s_lvl) > 6)) &&
	    (shoot_dir) &&
	    (weapon)) {
		missile(shoot_dir->y, shoot_dir->x, weapon, tp);
		ch_ret = *er;
		dist = DISTANCE(ch_ret.y, ch_ret.x, ee->y, ee->x);
	}

    /*
     * Otherwise, find the empty spot next to the chaser that is
     * closest to the chasee.
     */
    else {
	register int ey, ex;
	register struct room *rer, *ree;
	register int dist_to_old = MININT; /* Dist from goal to old position */

	/* Get rooms */
	rer = roomin(er);
	ree = roomin(ee);

	/*
	 * This will eventually hold where we move to get closer
	 * If we can't find an empty spot, we stay where we are.
	 */
	dist = flee ? 0 : MAXINT;
	ch_ret = *er;

	/* Are we at our goal already? */
	if (!flee && ce(ch_ret, *ee)) return(FALSE);

	ey = er->y + 1;
	ex = er->x + 1;
	for (x = er->x - 1; x <= ex; x++)
	    for (y = er->y - 1; y <= ey; y++) {
		coord tryp;

		/* Don't try off the board */
		if ((x < 0) || (x >= COLS) || (y < 1) || (y >= LINES - 2))
		    continue;

		/* Don't try the player if not going after the player */
		/* or he's disguised */
		if ( ((off(*tp, ISFLEE) && !ce(hero, *ee)) ||
			(on(player, ISDISGUISE) && (rnd(tp->t_stats.s_lvl) < 6))) &&
			x == hero.x && y == hero.y)
		    continue;

		tryp.x = x;
		tryp.y = y;

		/* Is there a monster on this spot closer to our goal?
		 * Don't look in our spot or where we were.
		 */
		if (!ce(tryp, *er) && !ce(tryp, tp->t_oldpos) &&
		    isalpha(mch = CCHAR( mvwinch(mw, y, x) ))) {
		    register int test_dist;

		    test_dist = DISTANCE(y, x, ee->y, ee->x);
		    if (test_dist <= 25 &&   /* Let's be fairly close */
			test_dist < monst_dist) {
			/* Could we really move there? */
			mvwaddch(mw, y, x, ' '); /* Temporarily blank monst */
			if (diag_ok(er, &tryp, tp)) monst_dist = test_dist;
			mvwaddch(mw, y, x, mch); /* Restore monster */
		    }
		}

		if (!diag_ok(er, &tryp, tp))
		    continue;
		ch = CCHAR( mvwinch(cw, y, x) );	/* Screen character */
		if (on(*tp, ISFLEE) && (ch == PLAYER)) next_player = TRUE;

		/* Stepping on player is NOT okay if we are fleeing */
		if (step_ok(y, x, NOMONST, tp) &&
		    (off(*tp, ISFLEE) || ch != PLAYER))
		{
		    /*
		     * If it is a trap, an intelligent monster may not
		     * step on it (unless our hero is on top!)
		     */
		    if (isatrap(ch)) {
			if (!(ch == RUSTTRAP) &&
				!(ch == FIRETRAP && on(*tp,NOFIRE)) &&
			    rnd(10) < tp->t_stats.s_intel &&
			    (y != hero.y || x != hero.x))
				continue;
		    }

		    /*
		     * OK -- this place counts
		     */
		    thisdist = DISTANCE(y, x, ee->y, ee->x);

		    /* Adjust distance if we are being shot at */
		    if (tp->t_wasshot && tp->t_stats.s_intel > 5 &&
			ce(hero, *ee)) {
			/* Move out of line of sight */
			if (straight_shot(tryp.y, tryp.x, ee->y, ee->x, NULL)) {
			    if (flee) thisdist -= SHOTPENALTY;
			    else thisdist += SHOTPENALTY;
			}

			/* But do we want to leave the room? */
			else if (rer && rer == ree && ch == DOOR)
			    thisdist += DOORPENALTY;
		    }

		    /* Don't move to the last position if we can help it */
		    if (ce(tryp, tp->t_oldpos)) dist_to_old = thisdist;

		    else if ((flee && (thisdist > dist)) ||
			(!flee && (thisdist < dist)))
		    {
			ch_ret = tryp;
			dist = thisdist;
		    }
		}
	    }

	/* If we are running from the player and he is in our way,
	 * go ahead and slug him.
	 */
	if (next_player && DISTANCE(er->y, er->x, ee->y, ee->x) < dist &&
	    step_ok(tp->t_dest->y, tp->t_dest->x, NOMONST, tp)) {
	    ch_ret = *(tp->t_dest);	/* Okay to hit player */
	    return FALSE;
	}


	/* If we can't get closer to the player (if that's our goal)
	 * because other monsters are in the way, just stay put
	 */
	if (!flee && ce(hero, *ee) && monst_dist < MAXINT &&
	    DISTANCE(er->y, er->x, hero.y, hero.x) < dist)
		ch_ret = *er;

	/* Do we want to go back to the last position? */
	else if (dist_to_old != MININT &&      /* It is possible to move back */
	    ((flee && dist == 0) ||	/* No other possible moves */
	     (!flee && dist == MAXINT))) {
	    /* Do we move back or just stay put (default)? */
	    dist = DISTANCE(er->y, er->x, ee->y, ee->x); /* Current distance */
	    if (!flee || (flee && (dist_to_old > dist))) ch_ret = tp->t_oldpos;
	}
    }

    /* Make sure we have the real distance now */
    dist = DISTANCE(ch_ret.y, ch_ret.x, ee->y, ee->x);

    /* Mark monsters in a wall */
    if (isrock(CCHAR( mvinch(ch_ret.y, ch_ret.x) ))) 
	turn_on(*tp, ISINWALL);
    else 
	turn_off(*tp, ISINWALL);

    if (off(*tp, ISFLEE) &&
	((tp->t_dest != &hero) || off(player, ISINWALL) || on(*tp, CANINWALL)))
	return (dist != 0);

    /* May actually hit here from a confused move */
    else return(!ce(ch_ret, hero));
}
    Status MMAPV1DatabaseCatalogEntry::renameCollection( OperationContext* txn,
                                                        const StringData& fromNS,
                                                        const StringData& toNS,
                                                        bool stayTemp ) {
        Status s = _renameSingleNamespace( txn, fromNS, toNS, stayTemp );
        if ( !s.isOK() )
            return s;

        NamespaceDetails* details = _namespaceIndex.details( toNS );
        invariant( details );

        RecordStoreV1Base* systemIndexRecordStore = _getIndexRecordStore();
        scoped_ptr<RecordIterator> it( systemIndexRecordStore->getIterator(txn) );

        while ( !it->isEOF() ) {
            DiskLoc loc = it->getNext();
            BSONObj oldIndexSpec = it->dataFor( loc ).toBson();
            if ( fromNS != oldIndexSpec["ns"].valuestrsafe() )
                continue;

            BSONObj newIndexSpec;
            {
                BSONObjBuilder b;
                BSONObjIterator i( oldIndexSpec );
                while( i.more() ) {
                    BSONElement e = i.next();
                    if ( strcmp( e.fieldName(), "ns" ) != 0 )
                        b.append( e );
                    else
                        b << "ns" << toNS;
                }
                newIndexSpec = b.obj();
            }

            StatusWith<DiskLoc> newIndexSpecLoc =
                systemIndexRecordStore->insertRecord( txn,
                                                      newIndexSpec.objdata(),
                                                      newIndexSpec.objsize(),
                                                      false );
            if ( !newIndexSpecLoc.isOK() )
                return newIndexSpecLoc.getStatus();

            const string& indexName = oldIndexSpec.getStringField( "name" );

            {
                // fix IndexDetails pointer
                NamespaceDetailsCollectionCatalogEntry ce( toNS,
                                                           details,
                                                           systemIndexRecordStore,
                                                           this );
                int indexI = ce._findIndexNumber( indexName );

                IndexDetails& indexDetails = details->idx(indexI);
                *txn->recoveryUnit()->writing(&indexDetails.info) = newIndexSpecLoc.getValue(); // XXX: dur
            }

            {
                // move underlying namespac
                string oldIndexNs = IndexDescriptor::makeIndexNamespace( fromNS, indexName );
                string newIndexNs = IndexDescriptor::makeIndexNamespace( toNS, indexName );

                Status s = _renameSingleNamespace( txn, oldIndexNs, newIndexNs, false );
                if ( !s.isOK() )
                    return s;
            }

            systemIndexRecordStore->deleteRecord( txn, loc );
        }

        return Status::OK();
    }
/*
 * do_chase:
 *	Make one thing chase another.
 */
void
do_chase(struct thing *th, int flee)
{
    register struct room *rer, *ree,	/* room of chaser, room of chasee */
			*old_room,	/* old room of monster */
			*new_room;	/* new room of monster */
    register int mindist = MAXINT, maxdist = MININT, dist = MININT, i,
		 last_door = -1;	/* Door we just came from */
    register int stoprun = FALSE,	/* TRUE means we are there */
		  rundoor;		/* TRUE means run to a door */
	int mdead = 0;
    register int sch;
    coord this;				/* Temporary destination for chaser */

    /* Make sure the monster can move */
    if (th->t_no_move != 0) {
	th->t_no_move--;
	return;
    }

    rer = roomin(&th->t_pos);	/* Find room of chaser */
    ree = roomin(th->t_dest);	/* Find room of chasee */

    /*
     * We don't count doors as inside rooms for this routine
     */
    if (mvwinch(stdscr, th->t_pos.y, th->t_pos.x) == DOOR)
	rer = NULL;
    this = *th->t_dest;

    /*
     * If we are not in a corridor and not a Xorn, then if we are running
     * after the player, we run to a door if he is not in the same room.
     * If we are fleeing, we run to a door if he IS in the same room.
     * Note:  We don't bother with doors in mazes.
     */
    if (levtype != MAZELEV && rer != NULL && off(*th, CANINWALL)) {
	if (flee) rundoor = (rer == ree);
	else rundoor = (rer != ree);
    }
    else rundoor = FALSE;

    if (rundoor) {
	coord exit;	/* A particular door */
	int exity, exitx;	/* Door's coordinates */

	if (th->t_doorgoal != -1) {	/* Do we already have the goal? */
	    this = rer->r_exit[th->t_doorgoal];
	    dist = 0;	/* Indicate that we have our door */
	}

	else for (i = 0; i < rer->r_nexits; i++) {	/* Loop through doors */
	    exit = rer->r_exit[i];
	    exity = exit.y;
	    exitx = exit.x;

	    /* Avoid secret doors */
	    if (mvwinch(stdscr, exity, exitx) == DOOR) {
		/* Were we just on this door? */
		if (ce(exit, th->t_oldpos)) last_door = i;

		else {
		    dist = DISTANCE(th->t_dest->y, th->t_dest->x, exity, exitx);

		    /* If fleeing, we want to maximize distance from door to
		     * what we flee, and minimize distance from door to us.
		     */
		    if (flee)
		       dist -= DISTANCE(th->t_pos.y, th->t_pos.x, exity, exitx);

		    /* Maximize distance if fleeing, otherwise minimize it */
		    if ((flee && (dist > maxdist)) ||
			(!flee && (dist < mindist))) {
			th->t_doorgoal = i;	/* Use this door */
			this = exit;
			mindist = maxdist = dist;
		    }
		}
	    }
	}

	/* Could we not find a door? */
	if (dist == MININT) {
	    /* If we were on a door, go ahead and use it */
	    if (last_door != -1) {
		th->t_doorgoal = last_door;
		this = th->t_oldpos;
		dist = 0;	/* Indicate that we found a door */
	    }
	}

	/* Indicate that we do not want to flee from the door */
	if (dist != MININT) flee = FALSE;
    }

    else th->t_doorgoal = -1;	/* Not going to any door */
    /*
     * this now contains what we want to run to this time
     * so we run to it.  If we hit it we either want to fight it
     * or stop running
     */
    if (!chase(th, &this, flee, &mdead)) {
	if (ce(ch_ret, hero)) {
	    /* merchants try to sell something */
	    if (on(*th, CANSELL)) 
		sell(th);
	    else if (on(*th, ISCHARMED))
		{}				/* future enhancements */
	    else if (on(*th, ISFRIENDLY))
		{}
	    else
		attack(th, NULL, FALSE);
	    return;
	}
	else if (on(*th, NOMOVE))
	    stoprun = TRUE;
    }

    if (on(*th, ISDEAD))
		return;	/* Did monster get itself killed? */

    if (on(*th, NOMOVE)) 
	return;

    /* If we have a scavenger, it can pick something up */
    if (on(*th, ISSCAVENGE)) {
	register struct linked_list *item;

	if ((item = find_obj(ch_ret.y, ch_ret.x)) != NULL) {
	    register int floor = (roomin(&ch_ret) == NULL) ? PASSAGE : FLOOR;

	    detach(lvl_obj, item);
	    mvaddch(ch_ret.y, ch_ret.x, floor);
	    mvwaddch(cw, ch_ret.y, ch_ret.x, floor);
	    attach(th->t_pack, item);
	}
    }

    mvwaddch(cw, th->t_pos.y, th->t_pos.x, th->t_oldch);
    sch = CCHAR( mvwinch(cw, ch_ret.y, ch_ret.x) );

    /* Get old and new room of monster */
    old_room=roomin(&th->t_pos);
    new_room=roomin(&ch_ret);

    /* If the monster can illuminate rooms, check for a change */
    if (on(*th, HASFIRE)) {
	/* Is monster entering a room? */
	if (old_room != new_room && new_room != NULL) {
	    new_room->r_flags |= HASFIRE;
	    new_room->r_fires++;
	    if (cansee(ch_ret.y, ch_ret.x) && new_room->r_fires == 1)
		light(&hero);
	}

	/* Is monster leaving a room? */
	if (old_room != new_room && old_room != NULL) {
	    if (--(old_room->r_fires) <= 0) {
		old_room->r_flags &= ~HASFIRE;
		if (cansee(th->t_pos.y, th->t_pos.x)) light(&th->t_pos);
	    }
	}
    }

    /* If monster is entering player's room and player can see it,
     * stop the player's running.
     */
    if (new_room != old_room && new_room != NULL &&
	new_room == ree && cansee(unc(ch_ret)) &&
	(off(*th, ISINVIS) || (off(*th, ISSHADOW) || rnd(10) == 0) ||
	on(player, CANSEE)) && off(*th, CANSURPRISE))
		running = FALSE;

    if (rer != NULL && (rer->r_flags & ISDARK) && 
	!(rer->r_flags & HASFIRE) && sch == FLOOR &&
	DISTANCE(ch_ret.y, ch_ret.x, th->t_pos.y, th->t_pos.x) < see_dist &&
	off(player, ISBLIND))
	    th->t_oldch = ' ';
    else
	th->t_oldch = sch;

    if (cansee(unc(ch_ret)) &&
	off(*th, ISINWALL) &&
	((off(*th, ISINVIS) && (off(*th, ISSHADOW) || rnd(100) < 10)) ||
	 on(player, CANSEE)) &&
	off(*th, CANSURPRISE))
        mvwaddch(cw, ch_ret.y, ch_ret.x, th->t_type);
    mvwaddch(mw, th->t_pos.y, th->t_pos.x, ' ');
    mvwaddch(mw, ch_ret.y, ch_ret.x, th->t_type);

    /* Record monster's last position (if new one is different) */
    if (!ce(ch_ret, th->t_pos)) th->t_oldpos = th->t_pos;
    th->t_pos = ch_ret;		/* Mark the monster's new position */

    /* If the monster is on a trap, trap it */
    sch = CCHAR( mvinch(ch_ret.y, ch_ret.x) );
    if (isatrap(sch)) {
	debug("Monster trapped by %c.", sch);
	if (cansee(ch_ret.y, ch_ret.x)) th->t_oldch = sch;
	be_trapped(th, &ch_ret);
    }


    /*
     * And stop running if need be
     */
    if (stoprun && ce(th->t_pos, *(th->t_dest)))
	turn_off(*th, ISRUN);
}
示例#18
0
/**
 * Handles command line events.
 */
void RS_EventHandler::commandEvent(RS_CommandEvent* e) {
    RS_DEBUG->print("RS_EventHandler::commandEvent");
    QString cmd = e->getCommand();

    // allow using command line as a calculator
    if (!e->isAccepted())  {
        if(cliCalculator(cmd)) {
            e->accept();
            return;
        }
    }

    if (coordinateInputEnabled) {
        if (!e->isAccepted()) {

            if(hasAction()){
                // handle absolute cartesian coordinate input:
                if (cmd.contains(',') && cmd.at(0)!='@') {

                    int commaPos = cmd.indexOf(',');
                    RS_DEBUG->print("RS_EventHandler::commandEvent: 001");
                    bool ok1, ok2;
                    RS_DEBUG->print("RS_EventHandler::commandEvent: 002");
                    double x = RS_Math::eval(cmd.left(commaPos), &ok1);
                    RS_DEBUG->print("RS_EventHandler::commandEvent: 003a");
                    double y = RS_Math::eval(cmd.mid(commaPos+1), &ok2);
                    RS_DEBUG->print("RS_EventHandler::commandEvent: 004");

                    if (ok1 && ok2) {
                        RS_DEBUG->print("RS_EventHandler::commandEvent: 005");
                        RS_CoordinateEvent ce(RS_Vector(x,y));
                        RS_DEBUG->print("RS_EventHandler::commandEvent: 006");
						currentActions.last()->coordinateEvent(&ce);
					} else
						RS_DIALOGFACTORY->commandMessage(
									"Expression Syntax Error");
					e->accept();
                }

                // handle relative cartesian coordinate input:
                if (!e->isAccepted()) {
                    if (cmd.contains(',') && cmd.at(0)=='@') {
                        int commaPos = cmd.indexOf(',');
                        bool ok1, ok2;
                        double x = RS_Math::eval(cmd.mid(1, commaPos-1), &ok1);
                        double y = RS_Math::eval(cmd.mid(commaPos+1), &ok2);

                        if (ok1 && ok2) {
                            RS_CoordinateEvent ce(RS_Vector(x,y) + relative_zero);

                            currentActions.last()->coordinateEvent(&ce);
                            //                            currentActions[actionIndex]->coordinateEvent(&ce);
						} else
							RS_DIALOGFACTORY->commandMessage(
										"Expression Syntax Error");
						e->accept();
                    }
                }

                // handle absolute polar coordinate input:
                if (!e->isAccepted()) {
                    if (cmd.contains('<') && cmd.at(0)!='@') {
                        int commaPos = cmd.indexOf('<');
                        bool ok1, ok2;
                        double r = RS_Math::eval(cmd.left(commaPos), &ok1);
                        double a = RS_Math::eval(cmd.mid(commaPos+1), &ok2);

                        if (ok1 && ok2) {
							RS_Vector pos{
								RS_Vector::polar(r,RS_Math::deg2rad(a))};
                            RS_CoordinateEvent ce(pos);
                            currentActions.last()->coordinateEvent(&ce);
						} else
                                RS_DIALOGFACTORY->commandMessage(
                                            "Expression Syntax Error");
                        e->accept();
                    }
                }

                // handle relative polar coordinate input:
                if (!e->isAccepted()) {
                    if (cmd.contains('<') && cmd.at(0)=='@') {
                        int commaPos = cmd.indexOf('<');
                        bool ok1, ok2;
                        double r = RS_Math::eval(cmd.mid(1, commaPos-1), &ok1);
                        double a = RS_Math::eval(cmd.mid(commaPos+1), &ok2);

                        if (ok1 && ok2) {
							RS_Vector pos = RS_Vector::polar(r,RS_Math::deg2rad(a));
                            RS_CoordinateEvent ce(pos + relative_zero);
                            currentActions.last()->coordinateEvent(&ce);
						} else
                                RS_DIALOGFACTORY->commandMessage(
                                            "Expression Syntax Error");
                        e->accept();
                    }
                }

                // send command event directly to current action:
                if (!e->isAccepted()) {
//                    std::cout<<"RS_EventHandler::commandEvent(RS_CommandEvent* e): sending cmd("<<qPrintable(e->getCommand()) <<") to action: "<<currentActions.last()->rtti()<<std::endl;
                    currentActions.last()->commandEvent(e);
                }
            }else{
            //send the command to default action
                if (defaultAction) {
                    defaultAction->commandEvent(e);
                }
            }
            // do not accept command here. Actions themselves should be responsible to accept commands
//            e->accept();
        }
    }

    RS_DEBUG->print("RS_EventHandler::commandEvent: OK");
}
示例#19
0
/** solve one of the eight Appollonius Equations
| Cx - Ci|^2=(Rx+Ri)^2
with Cx the center of the common tangent circle, Rx the radius. Ci and Ri are the Center and radius of the i-th existing circle
**/
QList<RS_Circle> RS_Circle::solveAppolloniusSingle(const QList<RS_Circle>& circles)
{
//          std::cout<<__FILE__<<" : "<<__FUNCTION__<<" : line "<<__LINE__<<std::endl;
//          for(int i=0;i<circles.size();i++){
//std::cout<<"i="<<i<<"\t center="<<circles[i].getCenter()<<"\tr="<<circles[i].getRadius()<<std::endl;
//          }
    QList<RS_Circle> ret;

    QList<RS_Vector> centers;
    QList<double> radii;

    for(size_t i=0;i<3;i++){
        if(circles[i].getCenter().valid==false) return ret;
        centers.push_back(circles[i].getCenter());
        radii.push_back(circles[i].getRadius());
    }
/** form the linear equation to solve center in radius **/
    QVector<QVector<double> > mat(2,QVector<double>(3,0.));
    mat[0][0]=centers[2].x - centers[0].x;
    mat[0][1]=centers[2].y - centers[0].y;
    mat[1][0]=centers[2].x - centers[1].x;
    mat[1][1]=centers[2].y - centers[1].y;
    if(fabs(mat[0][0]*mat[1][1] - mat[0][1]*mat[1][0])<RS_TOLERANCE*RS_TOLERANCE){
        std::cout<<"The provided circles are in a line, not common tangent circle"<<std::endl;
    }
    // r^0 term
    mat[0][2]=0.5*(centers[2].squared()-centers[0].squared()+radii[0]*radii[0]-radii[2]*radii[2]);
    mat[1][2]=0.5*(centers[2].squared()-centers[1].squared()+radii[1]*radii[1]-radii[2]*radii[2]);
//    std::cout<<__FILE__<<" : "<<__FUNCTION__<<" : line "<<__LINE__<<std::endl;
//    for(unsigned short i=0;i<=1;i++){
//        std::cout<<"eqs P:"<<i<<" : "<<mat[i][0]<<"*x + "<<mat[i][1]<<"*y = "<<mat[i][2]<<std::endl;
//    }
//    QVector<QVector<double> > sm(2,QVector<double>(2,0.));
    QVector<double> sm(2,0.);
    if(RS_Math::linearSolver(mat,sm)==false){
        return ret;
    }

    RS_Vector vp(sm[0],sm[1]);
//      std::cout<<__FILE__<<" : "<<__FUNCTION__<<" : line "<<__LINE__<<std::endl;
//      std::cout<<"vp="<<vp<<std::endl;

    // r term
    mat[0][2]= radii[0]-radii[2];
    mat[1][2]= radii[1]-radii[2];
//    for(unsigned short i=0;i<=1;i++){
//        std::cout<<"eqs Q:"<<i<<" : "<<mat[i][0]<<"*x + "<<mat[i][1]<<"*y = "<<mat[i][2]<<std::endl;
//    }
    if(RS_Math::linearSolver(mat,sm)==false){
        return ret;
    }
    RS_Vector vq(sm[0],sm[1]);
//      std::cout<<"vq="<<vq<<std::endl;
    //form quadratic equation for r
    RS_Vector dcp=vp-centers[0];
    double a=vq.squared()-1.;
    if(fabs(a)<RS_TOLERANCE*1e-4) {
        return ret;
    }
    std::vector<double> ce(0,0.);
    ce.push_back(2.*(dcp.dotP(vq)-radii[0])/a);
    ce.push_back((dcp.squared()-radii[0]*radii[0])/a);
    std::vector<double>&& vr=RS_Math::quadraticSolver(ce);
    for(size_t i=0; i < vr.size();i++){
        if(vr.at(i)<RS_TOLERANCE) continue;
        ret<<RS_Circle(NULL,RS_CircleData(vp+vq*vr.at(i),vr.at(i)));
    }
//    std::cout<<__FILE__<<" : "<<__FUNCTION__<<" : line "<<__LINE__<<std::endl;
//    std::cout<<"Found "<<ret.size()<<" solutions"<<std::endl;

    return ret;
}
示例#20
0
void eChannelInfo::ParseEITInfo(EITEvent *e)
{
		name=descr=genre=starttime="";
		cflags=0;
		eString t;
			
		if(e->start_time!=0)
		{
			tm *stime=localtime(&e->start_time);
			starttime.sprintf("%02d:%02d", stime->tm_hour, stime->tm_min);
			int show_current_remaining=1;
			eConfig::getInstance()->getKey("/ezap/osd/showCurrentRemaining", show_current_remaining);
			if (show_current_remaining)
			{
				time_t now = time(0) + eDVB::getInstance()->time_difference;
				int duration = e->duration - (now - e->start_time);
				if ( duration > e->duration )
					duration = e->duration;
				else if ( duration < 0 )
					duration = 0;
				t.sprintf("  (+%dmin)", (int)(duration/60));
			}
			else
				t.sprintf("  (%dmin)", (int)(e->duration/60));
		}

		if (e->free_CA_mode )
			cflags |= cflagScrambled;

		LocalEventData led;
		led.getLocalData(e, &name, &descr, 0);
		DescriptionForEPGSearch = name;
		for (ePtrList<Descriptor>::iterator d(e->descriptor); d != e->descriptor.end(); ++d)
		{
			Descriptor *descriptor=*d;
			if (descriptor->Tag()==DESCR_COMPONENT)
			{
				ComponentDescriptor *cd=(ComponentDescriptor*)descriptor;
				
				if( cd->stream_content == 2 && cd->component_type == 5)
					cflags |= cflagDolby;
				else if( cd->stream_content == 2 && cd->component_type == 3)
					cflags |= cflagStereo;
				else if( cd->stream_content == 1 && (cd->component_type == 2 || cd->component_type == 3) )
					cflags |= cflagWide;
			}
			else if(descriptor->Tag()==DESCR_CONTENT)
			{
				ContentDescriptor *cod=(ContentDescriptor*)descriptor;

				for(ePtrList<descr_content_entry_struct>::iterator ce(cod->contentList.begin()); ce != cod->contentList.end(); ++ce)
				{
					if(genresTableShort[ce->content_nibble_level_1*16+ce->content_nibble_level_2])
					{
/*						if ( !genre.length() )
							genre+=_("GENRE: ");*/
						genre += gettext( genresTableShort[ce->content_nibble_level_1*16+ce->content_nibble_level_2] );
						genre += " ";
					}
				}
			}
		}
		if(!t.isNull()) name += t;

		cname.setText( name );
		if ( genre.size() )
		{
			if ( name.size() )
				descr+=" / ";
			descr+=genre;
		}
		cdescr.setText( descr );
		ctime.setText( starttime );

		int n = 0;
		n = LayoutIcon(&cdolby, (cflags & cflagDolby), n);
		n = LayoutIcon(&cstereo, (cflags & cflagStereo), n);
		n = LayoutIcon(&cformat, (cflags & cflagWide), n );
		n = LayoutIcon(&cscrambled, (cflags & cflagScrambled), n );
}
示例#21
0
void setcoeff() {

      dxi   = 1.0 / ( nx0 - 1 );
      deta  = 1.0 / ( ny0 - 1 );
      dzeta = 1.0 / ( nz0 - 1 );

      tx1 = 1.0 / ( dxi * dxi );
      tx2 = 1.0 / ( 2.0 * dxi );
      tx3 = 1.0 / dxi;

      ty1 = 1.0 / ( deta * deta );
      ty2 = 1.0 / ( 2.0 * deta );
      ty3 = 1.0 / deta;

      tz1 = 1.0 / ( dzeta * dzeta );
      tz2 = 1.0 / ( 2.0 * dzeta );
      tz3 = 1.0 / dzeta;

      ii1 = 2;
      ii2 = nx0 - 1;
      ji1 = 2;
      ji2 = ny0 - 2;
      ki1 = 3;
      ki2 = nz0 - 1;

//c---------------------------------------------------------------------
//c   diffusion coefficients
//c---------------------------------------------------------------------
      dx1 = 0.75;
      dx2 = dx1;
      dx3 = dx1;
      dx4 = dx1;
      dx5 = dx1;

      dy1 = 0.75;
      dy2 = dy1;
      dy3 = dy1;
      dy4 = dy1;
      dy5 = dy1;

      dz1 = 1.00;
      dz2 = dz1;
      dz3 = dz1;
      dz4 = dz1;
      dz5 = dz1;

//c---------------------------------------------------------------------
//c   fourth difference dissipation
//c---------------------------------------------------------------------
      dssp = ( fmax (dx1, fmax (dy1, dz1) ) ) / 4.0;

//c---------------------------------------------------------------------
//c   coefficients of the exact solution to the first pde
//c---------------------------------------------------------------------
      ce(1,1) = 2.0;
      ce(1,2) = 0.0;
      ce(1,3) = 0.0;
      ce(1,4) = 4.0;
      ce(1,5) = 5.0;
      ce(1,6) = 3.0;
      ce(1,7) = 5.0e-01;
      ce(1,8) = 2.0e-02;
      ce(1,9) = 1.0e-02;
      ce(1,10) = 3.0e-02;
      ce(1,11) = 5.0e-01;
      ce(1,12) = 4.0e-01;
      ce(1,13) = 3.0e-01;

//c---------------------------------------------------------------------
//c   coefficients of the exact solution to the second pde
//c---------------------------------------------------------------------
      ce(2,1) = 1.0;
      ce(2,2) = 0.0;
      ce(2,3) = 0.0;
      ce(2,4) = 0.0;
      ce(2,5) = 1.0;
      ce(2,6) = 2.0;
      ce(2,7) = 3.0;
      ce(2,8) = 1.0e-02;
      ce(2,9) = 3.0e-02;
      ce(2,10) = 2.0e-02;
      ce(2,11) = 4.0e-01;
      ce(2,12) = 3.0e-01;
      ce(2,13) = 5.0e-01;

//c---------------------------------------------------------------------
//c   coefficients of the exact solution to the third pde
//c---------------------------------------------------------------------
      ce(3,1) = 2.0;
      ce(3,2) = 2.0;
      ce(3,3) = 0.0;
      ce(3,4) = 0.0;
      ce(3,5) = 0.0;
      ce(3,6) = 2.0;
      ce(3,7) = 3.0;
      ce(3,8) = 4.0e-02;
      ce(3,9) = 3.0e-02;
      ce(3,10) = 5.0e-02;
      ce(3,11) = 3.0e-01;
      ce(3,12) = 5.0e-01;
      ce(3,13) = 4.0e-01;

//c---------------------------------------------------------------------
//c   coefficients of the exact solution to the fourth pde
//c---------------------------------------------------------------------
      ce(4,1) = 2.0;
      ce(4,2) = 2.0;
      ce(4,3) = 0.0;
      ce(4,4) = 0.0;
      ce(4,5) = 0.0;
      ce(4,6) = 2.0;
      ce(4,7) = 3.0;
      ce(4,8) = 3.0e-02;
      ce(4,9) = 5.0e-02;
      ce(4,10) = 4.0e-02;
      ce(4,11) = 2.0e-01;
      ce(4,12) = 1.0e-01;
      ce(4,13) = 3.0e-01;

//c---------------------------------------------------------------------
//c   coefficients of the exact solution to the fifth pde
//c---------------------------------------------------------------------
      ce(5,1) = 5.0;
      ce(5,2) = 4.0;
      ce(5,3) = 3.0;
      ce(5,4) = 2.0;
      ce(5,5) = 1.0e-01;
      ce(5,6) = 4.0e-01;
      ce(5,7) = 3.0e-01;
      ce(5,8) = 5.0e-02;
      ce(5,9) = 4.0e-02;
      ce(5,10) = 3.0e-02;
      ce(5,11) = 1.0e-01;
      ce(5,12) = 3.0e-01;
      ce(5,13) = 2.0e-01;

      return;
}